_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q4700
ChimeraVisualizer.show_stacking
train
def show_stacking(self): """Visualizes pi-stacking interactions.""" grp = self.getPseudoBondGroup("pi-Stacking-%i" % self.tid, associateWith=[self.model]) grp.lineWidth = 3 grp.lineType = self.chimera.Dash for i, stack in enumerate(self.plcomplex.pistacking): m = self.model r = m.newResidue("pseudoatoms", " ", 1, " ") centroid_prot = m.newAtom("CENTROID", self.chimera.Element("CENTROID")) x, y, z = stack.proteinring_center centroid_prot.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(centroid_prot) centroid_lig = m.newAtom("CENTROID", self.chimera.Element("CENTROID")) x, y, z = stack.ligandring_center centroid_lig.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(centroid_lig) b = grp.newPseudoBond(centroid_lig, centroid_prot) b.color = self.colorbyname('forest green') self.bs_res_ids += stack.proteinring_atoms
python
{ "resource": "" }
q4701
ChimeraVisualizer.show_cationpi
train
def show_cationpi(self): """Visualizes cation-pi interactions""" grp = self.getPseudoBondGroup("Cation-Pi-%i" % self.tid, associateWith=[self.model]) grp.lineWidth = 3 grp.lineType = self.chimera.Dash for i, cat in enumerate(self.plcomplex.pication): m = self.model r = m.newResidue("pseudoatoms", " ", 1, " ") chargecenter = m.newAtom("CHARGE", self.chimera.Element("CHARGE")) x, y, z = cat.charge_center chargecenter.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(chargecenter) centroid = m.newAtom("CENTROID", self.chimera.Element("CENTROID")) x, y, z = cat.ring_center centroid.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(centroid) b = grp.newPseudoBond(centroid, chargecenter) b.color = self.colorbyname('orange') if cat.protcharged: self.bs_res_ids += cat.charge_atoms else: self.bs_res_ids += cat.ring_atoms
python
{ "resource": "" }
q4702
ChimeraVisualizer.show_sbridges
train
def show_sbridges(self): """Visualizes salt bridges.""" # Salt Bridges grp = self.getPseudoBondGroup("Salt Bridges-%i" % self.tid, associateWith=[self.model]) grp.lineWidth = 3 grp.lineType = self.chimera.Dash for i, sbridge in enumerate(self.plcomplex.saltbridges): m = self.model r = m.newResidue("pseudoatoms", " ", 1, " ") chargecenter1 = m.newAtom("CHARGE", self.chimera.Element("CHARGE")) x, y, z = sbridge.positive_center chargecenter1.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(chargecenter1) chargecenter2 = m.newAtom("CHARGE", self.chimera.Element("CHARGE")) x, y, z = sbridge.negative_center chargecenter2.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(chargecenter2) b = grp.newPseudoBond(chargecenter1, chargecenter2) b.color = self.colorbyname('yellow') if sbridge.protispos: self.bs_res_ids += sbridge.positive_atoms else: self.bs_res_ids += sbridge.negative_atoms
python
{ "resource": "" }
q4703
ChimeraVisualizer.show_wbridges
train
def show_wbridges(self): """Visualizes water bridges""" grp = self.getPseudoBondGroup("Water Bridges-%i" % self.tid, associateWith=[self.model]) grp.lineWidth = 3 for i, wbridge in enumerate(self.plcomplex.waterbridges): c = grp.newPseudoBond(self.atoms[wbridge.water_id], self.atoms[wbridge.acc_id]) c.color = self.colorbyname('cornflower blue') self.water_ids.append(wbridge.water_id) b = grp.newPseudoBond(self.atoms[wbridge.don_id], self.atoms[wbridge.water_id]) b.color = self.colorbyname('cornflower blue') self.water_ids.append(wbridge.water_id) if wbridge.protisdon: self.bs_res_ids.append(wbridge.don_id) else: self.bs_res_ids.append(wbridge.acc_id)
python
{ "resource": "" }
q4704
ChimeraVisualizer.show_metal
train
def show_metal(self): """Visualizes metal coordination.""" grp = self.getPseudoBondGroup("Metal Coordination-%i" % self.tid, associateWith=[self.model]) grp.lineWidth = 3 for i, metal in enumerate(self.plcomplex.metal_complexes): c = grp.newPseudoBond(self.atoms[metal.metal_id], self.atoms[metal.target_id]) c.color = self.colorbyname('magenta') if metal.location == 'water': self.water_ids.append(metal.target_id) if metal.location.startswith('protein'): self.bs_res_ids.append(metal.target_id)
python
{ "resource": "" }
q4705
ChimeraVisualizer.cleanup
train
def cleanup(self): """Clean up the visualization.""" if not len(self.water_ids) == 0: # Hide all non-interacting water molecules water_selection = [] for wid in self.water_ids: water_selection.append('serialNumber=%i' % wid) self.rc("~display :HOH") self.rc("display :@/%s" % " or ".join(water_selection)) # Show all interacting binding site residues self.rc("~display #%i & ~:/isHet" % self.model_dict[self.plipname]) self.rc("display :%s" % ",".join([str(self.atoms[bsid].residue.id) for bsid in self.bs_res_ids])) self.rc("color lightblue :HOH")
python
{ "resource": "" }
q4706
ChimeraVisualizer.zoom_to_ligand
train
def zoom_to_ligand(self): """Centers the view on the ligand and its binding site residues.""" self.rc("center #%i & :%s" % (self.model_dict[self.plipname], self.hetid))
python
{ "resource": "" }
q4707
ChimeraVisualizer.refinements
train
def refinements(self): """Details for the visualization.""" self.rc("setattr a color gray @CENTROID") self.rc("setattr a radius 0.3 @CENTROID") self.rc("represent sphere @CENTROID") self.rc("setattr a color orange @CHARGE") self.rc("setattr a radius 0.4 @CHARGE") self.rc("represent sphere @CHARGE") self.rc("display :pseudoatoms")
python
{ "resource": "" }
q4708
Formatter.format
train
def format(self): """ Crop and resize the supplied image. Return the image and the crop_box used. If the input format is JPEG and in EXIF there is information about rotation, use it and rotate resulting image. """ if hasattr(self.image, '_getexif'): self.rotate_exif() crop_box = self.crop_to_ratio() self.resize() return self.image, crop_box
python
{ "resource": "" }
q4709
Formatter.center_important_part
train
def center_important_part(self, crop_box): """ If important_box was specified, make sure it lies inside the crop box. """ if not self.important_box: return crop_box # shortcuts ib = self.important_box cl, ct, cr, cb = crop_box iw, ih = self.image.size # compute the move of crop center onto important center move_horiz = (ib[0] + ib[2]) // 2 - (cl + cr) // 2 move_verti = (ib[1] + ib[3]) // 2 - (ct + cb) // 2 # make sure we don't get out of the image # ... horizontaly if move_horiz > 0: move_horiz = min(iw - cr, move_horiz) else: move_horiz = max(-cl, move_horiz) # .. and verticaly if move_verti > 0: move_verti = min(ih - cb, move_verti) else: move_verti = max(-ct, move_verti) # move the crop_box return (cl + move_horiz, ct + move_verti, cr + move_horiz, cb + move_verti)
python
{ "resource": "" }
q4710
Formatter.crop_to_ratio
train
def crop_to_ratio(self): " Get crop coordinates and perform the crop if we get any. " crop_box = self.get_crop_box() if not crop_box: return crop_box = self.center_important_part(crop_box) iw, ih = self.image.size # see if we want to crop something from outside of the image out_of_photo = min(crop_box[0], crop_box[1]) < 0 or crop_box[2] > iw or crop_box[3] > ih # check whether there's transparent information in the image transparent = self.image.mode in ('RGBA', 'LA') if photos_settings.DEFAULT_BG_COLOR != 'black' and out_of_photo and not transparent: # if we do, just crop the image to the portion that will be visible updated_crop_box = ( max(0, crop_box[0]), max(0, crop_box[1]), min(iw, crop_box[2]), min(ih, crop_box[3]), ) cropped = self.image.crop(updated_crop_box) # create new image of the proper size and color self.image = Image.new('RGB', (crop_box[2] - crop_box[0], crop_box[3] - crop_box[1]), photos_settings.DEFAULT_BG_COLOR) # and paste the cropped part into it's proper position self.image.paste(cropped, (abs(min(crop_box[0], 0)), abs(min(crop_box[1], 0)))) else: # crop normally if not the case self.image = self.image.crop(crop_box) return crop_box
python
{ "resource": "" }
q4711
Formatter.get_resized_size
train
def get_resized_size(self): """ Get target size for the stretched or shirnked image to fit within the target dimensions. Do not stretch images if not format.stretch. Note that this method is designed to operate on already cropped image. """ f = self.fmt iw, ih = self.image.size if not f.stretch and iw <= self.fw and ih <= self.fh: return if self.image_ratio == self.format_ratio: # same ratio, just resize return (self.fw, self.fh) elif self.image_ratio < self.format_ratio: # image taller than format return (self.fh * iw / ih, self.fh) else: # self.image_ratio > self.format_ratio # image wider than format return (self.fw, self.fw * ih / iw)
python
{ "resource": "" }
q4712
Formatter.resize
train
def resize(self): """ Get target size for a cropped image and do the resizing if we got anything usable. """ resized_size = self.get_resized_size() if not resized_size: return self.image = self.image.resize(resized_size, Image.ANTIALIAS)
python
{ "resource": "" }
q4713
Formatter.rotate_exif
train
def rotate_exif(self): """ Rotate image via exif information. Only 90, 180 and 270 rotations are supported. """ exif = self.image._getexif() or {} rotation = exif.get(TAGS['Orientation'], 1) rotations = { 6: -90, 3: -180, 8: -270, } if rotation not in rotations: return self.image = self.image.rotate(rotations[rotation])
python
{ "resource": "" }
q4714
get_content_type
train
def get_content_type(ct_name): """ A helper function that returns ContentType object based on its slugified verbose_name_plural. Results of this function is cached to improve performance. :Parameters: - `ct_name`: Slugified verbose_name_plural of the target model. :Exceptions: - `Http404`: if no matching ContentType is found """ try: ct = CONTENT_TYPE_MAPPING[ct_name] except KeyError: for model in models.get_models(): if ct_name == slugify(model._meta.verbose_name_plural): ct = ContentType.objects.get_for_model(model) CONTENT_TYPE_MAPPING[ct_name] = ct break else: raise Http404 return ct
python
{ "resource": "" }
q4715
get_templates_from_publishable
train
def get_templates_from_publishable(name, publishable): """ Returns the same template list as `get_templates` but gets values from `Publishable` instance. """ slug = publishable.slug category = publishable.category app_label = publishable.content_type.app_label model_label = publishable.content_type.model return get_templates(name, slug, category, app_label, model_label)
python
{ "resource": "" }
q4716
export
train
def export(request, count, name='', content_type=None): """ Export banners. :Parameters: - `count`: number of objects to pass into the template - `name`: name of the template ( page/export/banner.html is default ) - `models`: list of Model classes to include """ t_list = [] if name: t_list.append('page/export/%s.html' % name) t_list.append('page/export/banner.html') try: cat = Category.objects.get_by_tree_path('') except Category.DoesNotExist: raise Http404() listing = Listing.objects.get_listing(count=count, category=cat) return render( request, t_list, { 'category' : cat, 'listing' : listing }, content_type=content_type )
python
{ "resource": "" }
q4717
EllaCoreView.get_templates
train
def get_templates(self, context, template_name=None): " Extract parameters for `get_templates` from the context. " if not template_name: template_name = self.template_name kw = {} if 'object' in context: o = context['object'] kw['slug'] = o.slug if context.get('content_type', False): ct = context['content_type'] kw['app_label'] = ct.app_label kw['model_label'] = ct.model return get_templates(template_name, category=context['category'], **kw)
python
{ "resource": "" }
q4718
Format.get_blank_img
train
def get_blank_img(self): """ Return fake ``FormatedPhoto`` object to be used in templates when an error occurs in image generation. """ if photos_settings.DEBUG: return self.get_placeholder_img() out = { 'blank': True, 'width': self.max_width, 'height': self.max_height, 'url': photos_settings.EMPTY_IMAGE_SITE_PREFIX + 'img/empty/%s.png' % (self.name), } return out
python
{ "resource": "" }
q4719
Format.get_placeholder_img
train
def get_placeholder_img(self): """ Returns fake ``FormatedPhoto`` object grabbed from image placeholder generator service for the purpose of debugging when images are not available but we still want to see something. """ pars = { 'width': self.max_width, 'height': self.max_height } out = { 'placeholder': True, 'width': self.max_width, 'height': self.max_height, 'url': photos_settings.DEBUG_PLACEHOLDER_PROVIDER_TEMPLATE % pars } return out
python
{ "resource": "" }
q4720
FormatedPhoto.generate
train
def generate(self, save=True): """ Generates photo file in current format. If ``save`` is ``True``, file is saved too. """ stretched_photo, crop_box = self._generate_img() # set crop_box to (0,0,0,0) if photo not cropped if not crop_box: crop_box = 0, 0, 0, 0 self.crop_left, self.crop_top, right, bottom = crop_box self.crop_width = right - self.crop_left self.crop_height = bottom - self.crop_top self.width, self.height = stretched_photo.size f = StringIO() imgf = (self.photo._get_image().format or Image.EXTENSION[path.splitext(self.photo.image.name)[1]]) stretched_photo.save(f, format=imgf, quality=self.format.resample_quality) f.seek(0) self.image.save(self.file(), ContentFile(f.read()), save)
python
{ "resource": "" }
q4721
FormatedPhoto.save
train
def save(self, **kwargs): """Overrides models.Model.save - Removes old file from the FS - Generates new file. """ self.remove_file() if not self.image: self.generate(save=False) else: self.image.name = self.file() super(FormatedPhoto, self).save(**kwargs)
python
{ "resource": "" }
q4722
FormatedPhoto.file
train
def file(self): """ Method returns formated photo path - derived from format.id and source Photo filename """ if photos_settings.FORMATED_PHOTO_FILENAME is not None: return photos_settings.FORMATED_PHOTO_FILENAME(self) source_file = path.split(self.photo.image.name) return path.join(source_file[0], str(self.format.id) + '-' + source_file[1])
python
{ "resource": "" }
q4723
_get_category_from_pars_var
train
def _get_category_from_pars_var(template_var, context): ''' get category from template variable or from tree_path ''' cat = template_var.resolve(context) if isinstance(cat, basestring): cat = Category.objects.get_by_tree_path(cat) return cat
python
{ "resource": "" }
q4724
position
train
def position(parser, token): """ Render a given position for category. If some position is not defined for first category, position from its parent category is used unless nofallback is specified. Syntax:: {% position POSITION_NAME for CATEGORY [nofallback] %}{% endposition %} {% position POSITION_NAME for CATEGORY using BOX_TYPE [nofallback] %}{% endposition %} Example usage:: {% position top_left for category %}{% endposition %} """ bits = token.split_contents() nodelist = parser.parse(('end' + bits[0],)) parser.delete_first_token() return _parse_position_tag(bits, nodelist)
python
{ "resource": "" }
q4725
pistacking
train
def pistacking(rings_bs, rings_lig): """Return all pi-stackings between the given aromatic ring systems in receptor and ligand.""" data = namedtuple( 'pistack', 'proteinring ligandring distance angle offset type restype resnr reschain restype_l resnr_l reschain_l') pairings = [] for r, l in itertools.product(rings_bs, rings_lig): # DISTANCE AND RING ANGLE CALCULATION d = euclidean3d(r.center, l.center) b = vecangle(r.normal, l.normal) a = min(b, 180 - b if not 180 - b < 0 else b) # Smallest of two angles, depending on direction of normal # RING CENTER OFFSET CALCULATION (project each ring center into the other ring) proj1 = projection(l.normal, l.center, r.center) proj2 = projection(r.normal, r.center, l.center) offset = min(euclidean3d(proj1, l.center), euclidean3d(proj2, r.center)) # RECEPTOR DATA resnr, restype, reschain = whichresnumber(r.atoms[0]), whichrestype(r.atoms[0]), whichchain(r.atoms[0]) resnr_l, restype_l, reschain_l = whichresnumber(l.orig_atoms[0]), whichrestype( l.orig_atoms[0]), whichchain(l.orig_atoms[0]) # SELECTION BY DISTANCE, ANGLE AND OFFSET passed = False if not config.MIN_DIST < d < config.PISTACK_DIST_MAX: continue if 0 < a < config.PISTACK_ANG_DEV and offset < config.PISTACK_OFFSET_MAX: ptype = 'P' passed = True if 90 - config.PISTACK_ANG_DEV < a < 90 + config.PISTACK_ANG_DEV and offset < config.PISTACK_OFFSET_MAX: ptype = 'T' passed = True if passed: contact = data(proteinring=r, ligandring=l, distance=d, angle=a, offset=offset, type=ptype, resnr=resnr, restype=restype, reschain=reschain, resnr_l=resnr_l, restype_l=restype_l, reschain_l=reschain_l) pairings.append(contact) return filter_contacts(pairings)
python
{ "resource": "" }
q4726
halogen
train
def halogen(acceptor, donor): """Detect all halogen bonds of the type Y-O...X-C""" data = namedtuple('halogenbond', 'acc acc_orig_idx don don_orig_idx distance don_angle acc_angle restype ' 'resnr reschain restype_l resnr_l reschain_l donortype acctype sidechain') pairings = [] for acc, don in itertools.product(acceptor, donor): dist = euclidean3d(acc.o.coords, don.x.coords) if not config.MIN_DIST < dist < config.HALOGEN_DIST_MAX: continue vec1, vec2 = vector(acc.o.coords, acc.y.coords), vector(acc.o.coords, don.x.coords) vec3, vec4 = vector(don.x.coords, acc.o.coords), vector(don.x.coords, don.c.coords) acc_angle, don_angle = vecangle(vec1, vec2), vecangle(vec3, vec4) is_sidechain_hal = acc.o.OBAtom.GetResidue().GetAtomProperty(acc.o.OBAtom, 8) # Check if sidechain atom if not config.HALOGEN_ACC_ANGLE - config.HALOGEN_ANGLE_DEV < acc_angle \ < config.HALOGEN_ACC_ANGLE + config.HALOGEN_ANGLE_DEV: continue if not config.HALOGEN_DON_ANGLE - config.HALOGEN_ANGLE_DEV < don_angle \ < config.HALOGEN_DON_ANGLE + config.HALOGEN_ANGLE_DEV: continue restype, reschain, resnr = whichrestype(acc.o), whichchain(acc.o), whichresnumber(acc.o) restype_l, reschain_l, resnr_l = whichrestype(don.orig_x), whichchain(don.orig_x), whichresnumber(don.orig_x) contact = data(acc=acc, acc_orig_idx=acc.o_orig_idx, don=don, don_orig_idx=don.x_orig_idx, distance=dist, don_angle=don_angle, acc_angle=acc_angle, restype=restype, resnr=resnr, reschain=reschain, restype_l=restype_l, reschain_l=reschain_l, resnr_l=resnr_l, donortype=don.x.OBAtom.GetType(), acctype=acc.o.type, sidechain=is_sidechain_hal) pairings.append(contact) return filter_contacts(pairings)
python
{ "resource": "" }
q4727
XMLStorage.getdata
train
def getdata(self, tree, location, force_string=False): """Gets XML data from a specific element and handles types.""" found = tree.xpath('%s/text()' % location) if not found: return None else: data = found[0] if force_string: return data if data == 'True': return True elif data == 'False': return False else: try: return int(data) except ValueError: try: return float(data) except ValueError: # It's a string return data
python
{ "resource": "" }
q4728
XMLStorage.getcoordinates
train
def getcoordinates(self, tree, location): """Gets coordinates from a specific element in PLIP XML""" return tuple(float(x) for x in tree.xpath('.//%s/*/text()' % location))
python
{ "resource": "" }
q4729
BSite.get_atom_mapping
train
def get_atom_mapping(self): """Parses the ligand atom mapping.""" # Atom mappings smiles_to_pdb_mapping = self.bindingsite.xpath('mappings/smiles_to_pdb/text()') if smiles_to_pdb_mapping == []: self.mappings = {'smiles_to_pdb': None, 'pdb_to_smiles': None} else: smiles_to_pdb_mapping = {int(y[0]): int(y[1]) for y in [x.split(':') for x in smiles_to_pdb_mapping[0].split(',')]} self.mappings = {'smiles_to_pdb': smiles_to_pdb_mapping} self.mappings['pdb_to_smiles'] = {v: k for k, v in self.mappings['smiles_to_pdb'].items()}
python
{ "resource": "" }
q4730
BSite.get_counts
train
def get_counts(self): """counts the interaction types and backbone hydrogen bonding in a binding site""" hbondsback = len([hb for hb in self.hbonds if not hb.sidechain]) counts = {'hydrophobics': len(self.hydrophobics), 'hbonds': len(self.hbonds), 'wbridges': len(self.wbridges), 'sbridges': len(self.sbridges), 'pistacks': len(self.pi_stacks), 'pications': len(self.pi_cations), 'halogens': len(self.halogens), 'metal': len(self.metal_complexes), 'hbond_back': hbondsback, 'hbond_nonback': (len(self.hbonds) - hbondsback)} counts['total'] = counts['hydrophobics'] + counts['hbonds'] + counts['wbridges'] + \ counts['sbridges'] + counts['pistacks'] + counts['pications'] + counts['halogens'] + counts['metal'] return counts
python
{ "resource": "" }
q4731
PLIPXMLREST.load_data
train
def load_data(self, pdbid): """Loads and parses an XML resource and saves it as a tree if successful""" f = urlopen("http://projects.biotec.tu-dresden.de/plip-rest/pdb/%s?format=xml" % pdbid.lower()) self.doc = etree.parse(f)
python
{ "resource": "" }
q4732
check_pdb_status
train
def check_pdb_status(pdbid): """Returns the status and up-to-date entry in the PDB for a given PDB ID""" url = 'http://www.rcsb.org/pdb/rest/idStatus?structureId=%s' % pdbid xmlf = urlopen(url) xml = et.parse(xmlf) xmlf.close() status = None current_pdbid = pdbid for df in xml.xpath('//record'): status = df.attrib['status'] # Status of an entry can be either 'UNKWOWN', 'OBSOLETE', or 'CURRENT' if status == 'OBSOLETE': current_pdbid = df.attrib['replacedBy'] # Contains the up-to-date PDB ID for obsolete entries return [status, current_pdbid.lower()]
python
{ "resource": "" }
q4733
fetch_pdb
train
def fetch_pdb(pdbid): """Get the newest entry from the RCSB server for the given PDB ID. Exits with '1' if PDB ID is invalid.""" pdbid = pdbid.lower() write_message('\nChecking status of PDB ID %s ... ' % pdbid) state, current_entry = check_pdb_status(pdbid) # Get state and current PDB ID if state == 'OBSOLETE': write_message('entry is obsolete, getting %s instead.\n' % current_entry) elif state == 'CURRENT': write_message('entry is up to date.\n') elif state == 'UNKNOWN': sysexit(3, 'Invalid PDB ID (Entry does not exist on PDB server)\n') write_message('Downloading file from PDB ... ') pdburl = 'http://www.rcsb.org/pdb/files/%s.pdb' % current_entry # Get URL for current entry try: pdbfile = urlopen(pdburl).read().decode() # If no PDB file is available, a text is now shown with "We're sorry, but ..." # Could previously be distinguished by an HTTP error if 'sorry' in pdbfile: sysexit(5, "No file in PDB format available from wwPDB for the given PDB ID.\n") except HTTPError: sysexit(5, "No file in PDB format available from wwPDB for the given PDB ID.\n") return [pdbfile, current_entry]
python
{ "resource": "" }
q4734
PositionBox
train
def PositionBox(position, *args, **kwargs): " Delegate the boxing. " obj = position.target return getattr(position.target, 'box_class', Box)(obj, *args, **kwargs)
python
{ "resource": "" }
q4735
PositionManager.get_active_position
train
def get_active_position(self, category, name, nofallback=False): """ Get active position for given position name. params: category - Category model to look for name - name of the position nofallback - if True than do not fall back to parent category if active position is not found for category """ now = timezone.now() lookup = (Q(active_from__isnull=True) | Q(active_from__lte=now)) & \ (Q(active_till__isnull=True) | Q(active_till__gt=now)) while True: try: return self.get(lookup, category=category, name=name, disabled=False) except Position.DoesNotExist: # if nofallback was specified, do not look into parent categories if nofallback: return False # traverse the category tree to the top otherwise category = category.tree_parent # we reached the top and still haven't found the position - return if category is None: return False
python
{ "resource": "" }
q4736
Position.render
train
def render(self, context, nodelist, box_type): " Render the position. " if not self.target: if self.target_ct: # broken Generic FK: log.warning('Broken target for position with pk %r', self.pk) return '' try: return Template(self.text, name="position-%s" % self.name).render(context) except TemplateSyntaxError: log.error('Broken definition for position with pk %r', self.pk) return '' if self.box_type: box_type = self.box_type if self.text: nodelist = Template('%s\n%s' % (nodelist.render({}), self.text), name="position-%s" % self.name).nodelist b = self.box_class(self, box_type, nodelist) return b.render(context)
python
{ "resource": "" }
q4737
PyMOLVisualizer.set_initial_representations
train
def set_initial_representations(self): """General settings for PyMOL""" self.standard_settings() cmd.set('dash_gap', 0) # Show not dashes, but lines for the pliprofiler cmd.set('ray_shadow', 0) # Turn on ray shadows for clearer ray-traced images cmd.set('cartoon_color', 'mylightblue') # Set clipping planes for full view cmd.clip('far', -1000) cmd.clip('near', 1000)
python
{ "resource": "" }
q4738
PyMOLVisualizer.standard_settings
train
def standard_settings(self): """Sets up standard settings for a nice visualization.""" cmd.set('bg_rgb', [1.0, 1.0, 1.0]) # White background cmd.set('depth_cue', 0) # Turn off depth cueing (no fog) cmd.set('cartoon_side_chain_helper', 1) # Improve combined visualization of sticks and cartoon cmd.set('cartoon_fancy_helices', 1) # Nicer visualization of helices (using tapered ends) cmd.set('transparency_mode', 1) # Turn on multilayer transparency cmd.set('dash_radius', 0.05) self.set_custom_colorset()
python
{ "resource": "" }
q4739
PyMOLVisualizer.set_custom_colorset
train
def set_custom_colorset(self): """Defines a colorset with matching colors. Provided by Joachim.""" cmd.set_color('myorange', '[253, 174, 97]') cmd.set_color('mygreen', '[171, 221, 164]') cmd.set_color('myred', '[215, 25, 28]') cmd.set_color('myblue', '[43, 131, 186]') cmd.set_color('mylightblue', '[158, 202, 225]') cmd.set_color('mylightgreen', '[229, 245, 224]')
python
{ "resource": "" }
q4740
PyMOLVisualizer.show_halogen
train
def show_halogen(self): """Visualize halogen bonds.""" halogen = self.plcomplex.halogen_bonds all_don_x, all_acc_o = [], [] for h in halogen: all_don_x.append(h.don_id) all_acc_o.append(h.acc_id) cmd.select('tmp_bs', 'id %i & %s' % (h.acc_id, self.protname)) cmd.select('tmp_lig', 'id %i & %s' % (h.don_id, self.ligname)) cmd.distance('HalogenBonds', 'tmp_bs', 'tmp_lig') if not len(all_acc_o) == 0: self.select_by_ids('HalogenAccept', all_acc_o, restrict=self.protname) self.select_by_ids('HalogenDonor', all_don_x, restrict=self.ligname) if self.object_exists('HalogenBonds'): cmd.set('dash_color', 'greencyan', 'HalogenBonds')
python
{ "resource": "" }
q4741
PyMOLVisualizer.show_stacking
train
def show_stacking(self): """Visualize pi-stacking interactions.""" stacks = self.plcomplex.pistacking for i, stack in enumerate(stacks): pires_ids = '+'.join(map(str, stack.proteinring_atoms)) pilig_ids = '+'.join(map(str, stack.ligandring_atoms)) cmd.select('StackRings-P', 'StackRings-P or (id %s & %s)' % (pires_ids, self.protname)) cmd.select('StackRings-L', 'StackRings-L or (id %s & %s)' % (pilig_ids, self.ligname)) cmd.select('StackRings-P', 'byres StackRings-P') cmd.show('sticks', 'StackRings-P') cmd.pseudoatom('ps-pistack-1-%i' % i, pos=stack.proteinring_center) cmd.pseudoatom('ps-pistack-2-%i' % i, pos=stack.ligandring_center) cmd.pseudoatom('Centroids-P', pos=stack.proteinring_center) cmd.pseudoatom('Centroids-L', pos=stack.ligandring_center) if stack.type == 'P': cmd.distance('PiStackingP', 'ps-pistack-1-%i' % i, 'ps-pistack-2-%i' % i) if stack.type == 'T': cmd.distance('PiStackingT', 'ps-pistack-1-%i' % i, 'ps-pistack-2-%i' % i) if self.object_exists('PiStackingP'): cmd.set('dash_color', 'green', 'PiStackingP') cmd.set('dash_gap', 0.3, 'PiStackingP') cmd.set('dash_length', 0.6, 'PiStackingP') if self.object_exists('PiStackingT'): cmd.set('dash_color', 'smudge', 'PiStackingT') cmd.set('dash_gap', 0.3, 'PiStackingT') cmd.set('dash_length', 0.6, 'PiStackingT')
python
{ "resource": "" }
q4742
PyMOLVisualizer.show_cationpi
train
def show_cationpi(self): """Visualize cation-pi interactions.""" for i, p in enumerate(self.plcomplex.pication): cmd.pseudoatom('ps-picat-1-%i' % i, pos=p.ring_center) cmd.pseudoatom('ps-picat-2-%i' % i, pos=p.charge_center) if p.protcharged: cmd.pseudoatom('Chargecenter-P', pos=p.charge_center) cmd.pseudoatom('Centroids-L', pos=p.ring_center) pilig_ids = '+'.join(map(str, p.ring_atoms)) cmd.select('PiCatRing-L', 'PiCatRing-L or (id %s & %s)' % (pilig_ids, self.ligname)) for a in p.charge_atoms: cmd.select('PosCharge-P', 'PosCharge-P or (id %i & %s)' % (a, self.protname)) else: cmd.pseudoatom('Chargecenter-L', pos=p.charge_center) cmd.pseudoatom('Centroids-P', pos=p.ring_center) pires_ids = '+'.join(map(str, p.ring_atoms)) cmd.select('PiCatRing-P', 'PiCatRing-P or (id %s & %s)' % (pires_ids, self.protname)) for a in p.charge_atoms: cmd.select('PosCharge-L', 'PosCharge-L or (id %i & %s)' % (a, self.ligname)) cmd.distance('PiCation', 'ps-picat-1-%i' % i, 'ps-picat-2-%i' % i) if self.object_exists('PiCation'): cmd.set('dash_color', 'orange', 'PiCation') cmd.set('dash_gap', 0.3, 'PiCation') cmd.set('dash_length', 0.6, 'PiCation')
python
{ "resource": "" }
q4743
PyMOLVisualizer.show_sbridges
train
def show_sbridges(self): """Visualize salt bridges.""" for i, saltb in enumerate(self.plcomplex.saltbridges): if saltb.protispos: for patom in saltb.positive_atoms: cmd.select('PosCharge-P', 'PosCharge-P or (id %i & %s)' % (patom, self.protname)) for latom in saltb.negative_atoms: cmd.select('NegCharge-L', 'NegCharge-L or (id %i & %s)' % (latom, self.ligname)) for sbgroup in [['ps-sbl-1-%i' % i, 'Chargecenter-P', saltb.positive_center], ['ps-sbl-2-%i' % i, 'Chargecenter-L', saltb.negative_center]]: cmd.pseudoatom(sbgroup[0], pos=sbgroup[2]) cmd.pseudoatom(sbgroup[1], pos=sbgroup[2]) cmd.distance('Saltbridges', 'ps-sbl-1-%i' % i, 'ps-sbl-2-%i' % i) else: for patom in saltb.negative_atoms: cmd.select('NegCharge-P', 'NegCharge-P or (id %i & %s)' % (patom, self.protname)) for latom in saltb.positive_atoms: cmd.select('PosCharge-L', 'PosCharge-L or (id %i & %s)' % (latom, self.ligname)) for sbgroup in [['ps-sbp-1-%i' % i, 'Chargecenter-P', saltb.negative_center], ['ps-sbp-2-%i' % i, 'Chargecenter-L', saltb.positive_center]]: cmd.pseudoatom(sbgroup[0], pos=sbgroup[2]) cmd.pseudoatom(sbgroup[1], pos=sbgroup[2]) cmd.distance('Saltbridges', 'ps-sbp-1-%i' % i, 'ps-sbp-2-%i' % i) if self.object_exists('Saltbridges'): cmd.set('dash_color', 'yellow', 'Saltbridges') cmd.set('dash_gap', 0.5, 'Saltbridges')
python
{ "resource": "" }
q4744
PyMOLVisualizer.show_wbridges
train
def show_wbridges(self): """Visualize water bridges.""" for bridge in self.plcomplex.waterbridges: if bridge.protisdon: cmd.select('HBondDonor-P', 'HBondDonor-P or (id %i & %s)' % (bridge.don_id, self.protname)) cmd.select('HBondAccept-L', 'HBondAccept-L or (id %i & %s)' % (bridge.acc_id, self.ligname)) cmd.select('tmp_don', 'id %i & %s' % (bridge.don_id, self.protname)) cmd.select('tmp_acc', 'id %i & %s' % (bridge.acc_id, self.ligname)) else: cmd.select('HBondDonor-L', 'HBondDonor-L or (id %i & %s)' % (bridge.don_id, self.ligname)) cmd.select('HBondAccept-P', 'HBondAccept-P or (id %i & %s)' % (bridge.acc_id, self.protname)) cmd.select('tmp_don', 'id %i & %s' % (bridge.don_id, self.ligname)) cmd.select('tmp_acc', 'id %i & %s' % (bridge.acc_id, self.protname)) cmd.select('Water', 'Water or (id %i & resn HOH)' % bridge.water_id) cmd.select('tmp_water', 'id %i & resn HOH' % bridge.water_id) cmd.distance('WaterBridges', 'tmp_acc', 'tmp_water') cmd.distance('WaterBridges', 'tmp_don', 'tmp_water') if self.object_exists('WaterBridges'): cmd.set('dash_color', 'lightblue', 'WaterBridges') cmd.delete('tmp_water or tmp_acc or tmp_don') cmd.color('lightblue', 'Water') cmd.show('spheres', 'Water')
python
{ "resource": "" }
q4745
PyMOLVisualizer.show_metal
train
def show_metal(self): """Visualize metal coordination.""" metal_complexes = self.plcomplex.metal_complexes if not len(metal_complexes) == 0: self.select_by_ids('Metal-M', self.metal_ids) for metal_complex in metal_complexes: cmd.select('tmp_m', 'id %i' % metal_complex.metal_id) cmd.select('tmp_t', 'id %i' % metal_complex.target_id) if metal_complex.location == 'water': cmd.select('Metal-W', 'Metal-W or id %s' % metal_complex.target_id) if metal_complex.location.startswith('protein'): cmd.select('tmp_t', 'tmp_t & %s' % self.protname) cmd.select('Metal-P', 'Metal-P or (id %s & %s)' % (metal_complex.target_id, self.protname)) if metal_complex.location == 'ligand': cmd.select('tmp_t', 'tmp_t & %s' % self.ligname) cmd.select('Metal-L', 'Metal-L or (id %s & %s)' % (metal_complex.target_id, self.ligname)) cmd.distance('MetalComplexes', 'tmp_m', 'tmp_t') cmd.delete('tmp_m or tmp_t') if self.object_exists('MetalComplexes'): cmd.set('dash_color', 'violetpurple', 'MetalComplexes') cmd.set('dash_gap', 0.5, 'MetalComplexes') # Show water molecules for metal complexes cmd.show('spheres', 'Metal-W') cmd.color('lightblue', 'Metal-W')
python
{ "resource": "" }
q4746
PyMOLVisualizer.selections_cleanup
train
def selections_cleanup(self): """Cleans up non-used selections""" if not len(self.plcomplex.unpaired_hba_idx) == 0: self.select_by_ids('Unpaired-HBA', self.plcomplex.unpaired_hba_idx, selection_exists=True) if not len(self.plcomplex.unpaired_hbd_idx) == 0: self.select_by_ids('Unpaired-HBD', self.plcomplex.unpaired_hbd_idx, selection_exists=True) if not len(self.plcomplex.unpaired_hal_idx) == 0: self.select_by_ids('Unpaired-HAL', self.plcomplex.unpaired_hal_idx, selection_exists=True) selections = cmd.get_names("selections") for selection in selections: try: empty = len(cmd.get_model(selection).atom) == 0 except: empty = True if empty: cmd.delete(selection) cmd.deselect() cmd.delete('tmp*') cmd.delete('ps-*')
python
{ "resource": "" }
q4747
PyMOLVisualizer.selections_group
train
def selections_group(self): """Group all selections""" cmd.group('Structures', '%s %s %sCartoon' % (self.protname, self.ligname, self.protname)) cmd.group('Interactions', 'Hydrophobic HBonds HalogenBonds WaterBridges PiCation PiStackingP PiStackingT ' 'Saltbridges MetalComplexes') cmd.group('Atoms', '') cmd.group('Atoms.Protein', 'Hydrophobic-P HBondAccept-P HBondDonor-P HalogenAccept Centroids-P PiCatRing-P ' 'StackRings-P PosCharge-P NegCharge-P AllBSRes Chargecenter-P Metal-P') cmd.group('Atoms.Ligand', 'Hydrophobic-L HBondAccept-L HBondDonor-L HalogenDonor Centroids-L NegCharge-L ' 'PosCharge-L NegCharge-L ChargeCenter-L StackRings-L PiCatRing-L Metal-L Metal-M ' 'Unpaired-HBA Unpaired-HBD Unpaired-HAL Unpaired-RINGS') cmd.group('Atoms.Other', 'Water Metal-W') cmd.order('*', 'y')
python
{ "resource": "" }
q4748
PyMOLVisualizer.additional_cleanup
train
def additional_cleanup(self): """Cleanup of various representations""" cmd.remove('not alt ""+A') # Remove alternate conformations cmd.hide('labels', 'Interactions') # Hide labels of lines cmd.disable('%sCartoon' % self.protname) cmd.hide('everything', 'hydrogens')
python
{ "resource": "" }
q4749
PyMOLVisualizer.zoom_to_ligand
train
def zoom_to_ligand(self): """Zoom in too ligand and its interactions.""" cmd.center(self.ligname) cmd.orient(self.ligname) cmd.turn('x', 110) # If the ligand is aligned with the longest axis, aromatic rings are hidden if 'AllBSRes' in cmd.get_names("selections"): cmd.zoom('%s or AllBSRes' % self.ligname, 3) else: if self.object_exists(self.ligname): cmd.zoom(self.ligname, 3) cmd.origin(self.ligname)
python
{ "resource": "" }
q4750
PyMOLVisualizer.save_session
train
def save_session(self, outfolder, override=None): """Saves a PyMOL session file.""" filename = '%s_%s' % (self.protname.upper(), "_".join( [self.hetid, self.plcomplex.chain, self.plcomplex.position])) if override is not None: filename = override cmd.save("/".join([outfolder, "%s.pse" % filename]))
python
{ "resource": "" }
q4751
PyMOLVisualizer.save_picture
train
def save_picture(self, outfolder, filename): """Saves a picture""" self.set_fancy_ray() self.png_workaround("/".join([outfolder, filename]))
python
{ "resource": "" }
q4752
PyMOLVisualizer.set_fancy_ray
train
def set_fancy_ray(self): """Give the molecule a flat, modern look.""" cmd.set('light_count', 6) cmd.set('spec_count', 1.5) cmd.set('shininess', 4) cmd.set('specular', 0.3) cmd.set('reflect', 1.6) cmd.set('ambient', 0) cmd.set('direct', 0) cmd.set('ray_shadow', 0) # Gives the molecules a flat, modern look cmd.set('ambient_occlusion_mode', 1) cmd.set('ray_opaque_background', 0)
python
{ "resource": "" }
q4753
PyMOLVisualizer.adapt_for_peptides
train
def adapt_for_peptides(self): """Adapt visualization for peptide ligands and interchain contacts""" cmd.hide('sticks', self.ligname) cmd.set('cartoon_color', 'lightorange', self.ligname) cmd.show('cartoon', self.ligname) cmd.show('sticks', "byres *-L") cmd.util.cnc(self.ligname) cmd.remove('%sCartoon and chain %s' % (self.protname, self.plcomplex.chain)) cmd.set('cartoon_side_chain_helper', 0)
python
{ "resource": "" }
q4754
PyMOLVisualizer.refinements
train
def refinements(self): """Refinements for the visualization""" # Show sticks for all residues interacing with the ligand cmd.select('AllBSRes', 'byres (Hydrophobic-P or HBondDonor-P or HBondAccept-P or PosCharge-P or NegCharge-P or ' 'StackRings-P or PiCatRing-P or HalogenAcc or Metal-P)') cmd.show('sticks', 'AllBSRes') # Show spheres for the ring centroids cmd.hide('everything', 'centroids*') cmd.show('nb_spheres', 'centroids*') # Show spheres for centers of charge if self.object_exists('Chargecenter-P') or self.object_exists('Chargecenter-L'): cmd.hide('nonbonded', 'chargecenter*') cmd.show('spheres', 'chargecenter*') cmd.set('sphere_scale', 0.4, 'chargecenter*') cmd.color('yellow', 'chargecenter*') cmd.set('valence', 1) # Show bond valency (e.g. double bonds) # Optional cartoon representation of the protein cmd.copy('%sCartoon' % self.protname, self.protname) cmd.show('cartoon', '%sCartoon' % self.protname) cmd.show('sticks', '%sCartoon' % self.protname) cmd.set('stick_transparency', 1, '%sCartoon' % self.protname) # Resize water molecules. Sometimes they are not heteroatoms HOH, but part of the protein cmd.set('sphere_scale', 0.2, 'resn HOH or Water') # Needs to be done here because of the copy made cmd.set('sphere_transparency', 0.4, '!(resn HOH or Water)') if 'Centroids*' in cmd.get_names("selections"): cmd.color('grey80', 'Centroids*') cmd.hide('spheres', '%sCartoon' % self.protname) cmd.hide('cartoon', '%sCartoon and resn DA+DG+DC+DU+DT+A+G+C+U+T' % self.protname) # Hide DNA/RNA Cartoon if self.ligname == 'SF4': # Special case for iron-sulfur clusters, can't be visualized with sticks cmd.show('spheres', '%s' % self.ligname) cmd.hide('everything', 'resn HOH &!Water') # Hide all non-interacting water molecules cmd.hide('sticks', '%s and !%s and !AllBSRes' % (self.protname, self.ligname)) # Hide all non-interacting residues if self.ligandtype in ['PEPTIDE', 'INTRA']: self.adapt_for_peptides() if self.ligandtype == 'INTRA': self.adapt_for_intra()
python
{ "resource": "" }
q4755
get_cached_object
train
def get_cached_object(model, timeout=CACHE_TIMEOUT, **kwargs): """ Return a cached object. If the object does not exist in the cache, create it. Params: model - ContentType instance representing the model's class or the model class itself timeout - TTL for the item in cache, defaults to CACHE_TIMEOUT **kwargs - lookup parameters for content_type.get_object_for_this_type and for key creation Throws: model.DoesNotExist is propagated from content_type.get_object_for_this_type """ if not isinstance(model, ContentType): model_ct = ContentType.objects.get_for_model(model) else: model_ct = model key = _get_key(KEY_PREFIX, model_ct, **kwargs) obj = cache.get(key) if obj is None: # if we are looking for a publishable, fetch just the actual content # type and then fetch the actual object if model_ct.app_label == 'core' and model_ct.model == 'publishable': actual_ct_id = model_ct.model_class()._default_manager.values('content_type_id').get(**kwargs)['content_type_id'] model_ct = ContentType.objects.get_for_id(actual_ct_id) # fetch the actual object we want obj = model_ct.model_class()._default_manager.get(**kwargs) # since 99% of lookups are done via PK make sure we set the cache for # that lookup even if we retrieved it using a different one. if 'pk' in kwargs: cache.set(key, obj, timeout) elif not isinstance(cache, DummyCache): cache.set_many({key: obj, _get_key(KEY_PREFIX, model_ct, pk=obj.pk): obj}, timeout=timeout) return obj
python
{ "resource": "" }
q4756
get_cached_objects
train
def get_cached_objects(pks, model=None, timeout=CACHE_TIMEOUT, missing=RAISE): """ Return a list of objects with given PKs using cache. Params: pks - list of Primary Key values to look up or list of content_type_id, pk tuples model - ContentType instance representing the model's class or the model class itself timeout - TTL for the items in cache, defaults to CACHE_TIMEOUT Throws: model.DoesNotExist is propagated from content_type.get_object_for_this_type """ if model is not None: if not isinstance(model, ContentType): model = ContentType.objects.get_for_model(model) pks = [(model, pk) for pk in pks] else: pks = [(ContentType.objects.get_for_id(ct_id), pk) for (ct_id, pk) in pks] keys = [_get_key(KEY_PREFIX, model, pk=pk) for (model, pk) in pks] cached = cache.get_many(keys) # keys not in cache keys_to_set = set(keys) - set(cached.keys()) if keys_to_set: # build lookup to get model and pks from the key lookup = dict(zip(keys, pks)) to_get = {} # group lookups by CT so we can do in_bulk for k in keys_to_set: ct, pk = lookup[k] to_get.setdefault(ct, {})[int(pk)] = k # take out all the publishables publishable_ct = ContentType.objects.get_for_model(get_model('core', 'publishable')) if publishable_ct in to_get: publishable_keys = to_get.pop(publishable_ct) models = publishable_ct.model_class()._default_manager.values('content_type_id', 'id').filter(id__in=publishable_keys.keys()) for m in models: ct = ContentType.objects.get_for_id(m['content_type_id']) pk = m['id'] # and put them back as their native content_type to_get.setdefault(ct, {})[pk] = publishable_keys[pk] to_set = {} # retrieve all the models from DB for ct, vals in to_get.items(): models = ct.model_class()._default_manager.in_bulk(vals.keys()) for pk, m in models.items(): k = vals[pk] cached[k] = to_set[k] = m if not isinstance(cache, DummyCache): # write them into cache cache.set_many(to_set, timeout=timeout) out = [] for k in keys: try: out.append(cached[k]) except KeyError: if missing == NONE: out.append(None) elif missing == SKIP: pass elif missing == RAISE: ct = ContentType.objects.get_for_id(int(k.split(':')[1])) raise ct.model_class().DoesNotExist( '%s matching query does not exist.' % ct.model_class()._meta.object_name) return out
python
{ "resource": "" }
q4757
get_cached_object_or_404
train
def get_cached_object_or_404(model, timeout=CACHE_TIMEOUT, **kwargs): """ Shortcut that will raise Http404 if there is no object matching the query see get_cached_object for params description """ try: return get_cached_object(model, timeout=timeout, **kwargs) except ObjectDoesNotExist, e: raise Http404('Reason: %s' % str(e))
python
{ "resource": "" }
q4758
tmpfile
train
def tmpfile(prefix, direc): """Returns the path to a newly created temporary file.""" return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc)
python
{ "resource": "" }
q4759
extract_pdbid
train
def extract_pdbid(string): """Use regular expressions to get a PDB ID from a string""" p = re.compile("[0-9][0-9a-z]{3}") m = p.search(string.lower()) try: return m.group() except AttributeError: return "UnknownProtein"
python
{ "resource": "" }
q4760
whichrestype
train
def whichrestype(atom): """Returns the residue name of an Pybel or OpenBabel atom.""" atom = atom if not isinstance(atom, Atom) else atom.OBAtom # Convert to OpenBabel Atom return atom.GetResidue().GetName() if atom.GetResidue() is not None else None
python
{ "resource": "" }
q4761
whichchain
train
def whichchain(atom): """Returns the residue number of an PyBel or OpenBabel atom.""" atom = atom if not isinstance(atom, Atom) else atom.OBAtom # Convert to OpenBabel Atom return atom.GetResidue().GetChain() if atom.GetResidue() is not None else None
python
{ "resource": "" }
q4762
euclidean3d
train
def euclidean3d(v1, v2): """Faster implementation of euclidean distance for the 3D case.""" if not len(v1) == 3 and len(v2) == 3: print("Vectors are not in 3D space. Returning None.") return None return np.sqrt((v1[0] - v2[0]) ** 2 + (v1[1] - v2[1]) ** 2 + (v1[2] - v2[2]) ** 2)
python
{ "resource": "" }
q4763
create_folder_if_not_exists
train
def create_folder_if_not_exists(folder_path): """Creates a folder if it does not exists.""" folder_path = tilde_expansion(folder_path) folder_path = "".join([folder_path, '/']) if not folder_path[-1] == '/' else folder_path direc = os.path.dirname(folder_path) if not folder_exists(direc): os.makedirs(direc)
python
{ "resource": "" }
q4764
start_pymol
train
def start_pymol(quiet=False, options='-p', run=False): """Starts up PyMOL and sets general options. Quiet mode suppresses all PyMOL output. Command line options can be passed as the second argument.""" import pymol pymol.pymol_argv = ['pymol', '%s' % options] + sys.argv[1:] if run: initialize_pymol(options) if quiet: pymol.cmd.feedback('disable', 'all', 'everything')
python
{ "resource": "" }
q4765
ring_is_planar
train
def ring_is_planar(ring, r_atoms): """Given a set of ring atoms, check if the ring is sufficiently planar to be considered aromatic""" normals = [] for a in r_atoms: adj = pybel.ob.OBAtomAtomIter(a.OBAtom) # Check for neighboring atoms in the ring n_coords = [pybel.Atom(neigh).coords for neigh in adj if ring.IsMember(neigh)] vec1, vec2 = vector(a.coords, n_coords[0]), vector(a.coords, n_coords[1]) normals.append(np.cross(vec1, vec2)) # Given all normals of ring atoms and their neighbors, the angle between any has to be 5.0 deg or less for n1, n2 in itertools.product(normals, repeat=2): arom_angle = vecangle(n1, n2) if all([arom_angle > config.AROMATIC_PLANARITY, arom_angle < 180.0 - config.AROMATIC_PLANARITY]): return False return True
python
{ "resource": "" }
q4766
get_isomorphisms
train
def get_isomorphisms(reference, lig): """Get all isomorphisms of the ligand.""" query = pybel.ob.CompileMoleculeQuery(reference.OBMol) mappr = pybel.ob.OBIsomorphismMapper.GetInstance(query) if all: isomorphs = pybel.ob.vvpairUIntUInt() mappr.MapAll(lig.OBMol, isomorphs) else: isomorphs = pybel.ob.vpairUIntUInt() mappr.MapFirst(lig.OBMol, isomorphs) isomorphs = [isomorphs] write_message("Number of isomorphisms: %i\n" % len(isomorphs), mtype='debug') # #@todo Check which isomorphism to take return isomorphs
python
{ "resource": "" }
q4767
canonicalize
train
def canonicalize(lig, preserve_bond_order=False): """Get the canonical atom order for the ligand.""" atomorder = None # Get canonical atom order lig = pybel.ob.OBMol(lig.OBMol) if not preserve_bond_order: for bond in pybel.ob.OBMolBondIter(lig): if bond.GetBondOrder() != 1: bond.SetBondOrder(1) lig.DeleteData(pybel.ob.StereoData) lig = pybel.Molecule(lig) testcan = lig.write(format='can') try: pybel.readstring('can', testcan) reference = pybel.readstring('can', testcan) except IOError: testcan, reference = '', '' if testcan != '': reference.removeh() isomorphs = get_isomorphisms(reference, lig) # isomorphs now holds all isomorphisms within the molecule if not len(isomorphs) == 0: smi_dict = {} smi_to_can = isomorphs[0] for x in smi_to_can: smi_dict[int(x[1]) + 1] = int(x[0]) + 1 atomorder = [smi_dict[x + 1] for x in range(len(lig.atoms))] else: atomorder = None return atomorder
python
{ "resource": "" }
q4768
read_pdb
train
def read_pdb(pdbfname, as_string=False): """Reads a given PDB file and returns a Pybel Molecule.""" pybel.ob.obErrorLog.StopLogging() # Suppress all OpenBabel warnings if os.name != 'nt': # Resource module not available for Windows maxsize = resource.getrlimit(resource.RLIMIT_STACK)[-1] resource.setrlimit(resource.RLIMIT_STACK, (min(2 ** 28, maxsize), maxsize)) sys.setrecursionlimit(10 ** 5) # increase Python recoursion limit return readmol(pdbfname, as_string=as_string)
python
{ "resource": "" }
q4769
read
train
def read(fil): """Returns a file handler and detects gzipped files.""" if os.path.splitext(fil)[-1] == '.gz': return gzip.open(fil, 'rb') elif os.path.splitext(fil)[-1] == '.zip': zf = zipfile.ZipFile(fil, 'r') return zf.open(zf.infolist()[0].filename) else: return open(fil, 'r')
python
{ "resource": "" }
q4770
readmol
train
def readmol(path, as_string=False): """Reads the given molecule file and returns the corresponding Pybel molecule as well as the input file type. In contrast to the standard Pybel implementation, the file is closed properly.""" supported_formats = ['pdb'] # Fix for Windows-generated files: Remove carriage return characters if "\r" in path and as_string: path = path.replace('\r', '') for sformat in supported_formats: obc = pybel.ob.OBConversion() obc.SetInFormat(sformat) write_message("Detected {} as format. Trying to read file with OpenBabel...\n".format(sformat), mtype='debug') # Read molecules with single bond information if as_string: try: mymol = pybel.readstring(sformat, path) except IOError: sysexit(4, 'No valid file format provided.') else: read_file = pybel.readfile(format=sformat, filename=path, opt={"s": None}) try: mymol = next(read_file) except StopIteration: sysexit(4, 'File contains no valid molecules.\n') write_message("Molecule successfully read.\n", mtype='debug') # Assign multiple bonds mymol.OBMol.PerceiveBondOrders() return mymol, sformat sysexit(4, 'No valid file format provided.')
python
{ "resource": "" }
q4771
colorlog
train
def colorlog(msg, color, bold=False, blink=False): """Colors messages on non-Windows systems supporting ANSI escape.""" # ANSI Escape Codes PINK_COL = '\x1b[35m' GREEN_COL = '\x1b[32m' RED_COL = '\x1b[31m' YELLOW_COL = '\x1b[33m' BLINK = '\x1b[5m' RESET = '\x1b[0m' if platform.system() != 'Windows': if blink: msg = BLINK + msg + RESET if color == 'yellow': msg = YELLOW_COL + msg + RESET if color == 'red': msg = RED_COL + msg + RESET if color == 'green': msg = GREEN_COL + msg + RESET if color == 'pink': msg = PINK_COL + msg + RESET return msg
python
{ "resource": "" }
q4772
write_message
train
def write_message(msg, indent=False, mtype='standard', caption=False): """Writes message if verbose mode is set.""" if (mtype == 'debug' and config.DEBUG) or (mtype != 'debug' and config.VERBOSE) or mtype == 'error': message(msg, indent=indent, mtype=mtype, caption=caption)
python
{ "resource": "" }
q4773
message
train
def message(msg, indent=False, mtype='standard', caption=False): """Writes messages in verbose mode""" if caption: msg = '\n' + msg + '\n' + '-'*len(msg) + '\n' if mtype == 'warning': msg = colorlog('Warning: ' + msg, 'yellow') if mtype == 'error': msg = colorlog('Error: ' + msg, 'red') if mtype == 'debug': msg = colorlog('Debug: ' + msg, 'pink') if mtype == 'info': msg = colorlog('Info: ' + msg, 'green') if indent: msg = ' ' + msg sys.stderr.write(msg)
python
{ "resource": "" }
q4774
do_related
train
def do_related(parser, token): """ Get N related models into a context variable optionally specifying a named related finder. **Usage**:: {% related <limit>[ query_type] [app.model, ...] for <object> as <result> %} **Parameters**:: ================================== ================================================ Option Description ================================== ================================================ ``limit`` Number of objects to retrieve. ``query_type`` Named finder to resolve the related objects, falls back to ``settings.DEFAULT_RELATED_FINDER`` when not specified. ``app.model``, ... List of allowed models, all if omitted. ``object`` Object to get the related for. ``result`` Store the resulting list in context under given name. ================================== ================================================ **Examples**:: {% related 10 for object as related_list %} {% related 10 directly articles.article, galleries.gallery for object as related_list %} """ bits = token.split_contents() obj_var, count, var_name, mods, finder = parse_related_tag(bits) return RelatedNode(obj_var, count, var_name, mods, finder)
python
{ "resource": "" }
q4775
PublishableBox
train
def PublishableBox(publishable, box_type, nodelist, model=None): "add some content type info of self.target" if not model: model = publishable.content_type.model_class() box_class = model.box_class if box_class == PublishableBox: box_class = Box return box_class(publishable, box_type, nodelist, model=model)
python
{ "resource": "" }
q4776
ListingBox
train
def ListingBox(listing, *args, **kwargs): " Delegate the boxing to the target's Box class. " obj = listing.publishable return obj.box_class(obj, *args, **kwargs)
python
{ "resource": "" }
q4777
Publishable.get_absolute_url
train
def get_absolute_url(self, domain=False): " Get object's URL. " category = self.category kwargs = { 'slug': self.slug, } if self.static: kwargs['id'] = self.pk if category.tree_parent_id: kwargs['category'] = category.tree_path url = reverse('static_detail', kwargs=kwargs) else: url = reverse('home_static_detail', kwargs=kwargs) else: publish_from = localize(self.publish_from) kwargs.update({ 'year': publish_from.year, 'month': publish_from.month, 'day': publish_from.day, }) if category.tree_parent_id: kwargs['category'] = category.tree_path url = reverse('object_detail', kwargs=kwargs) else: url = reverse('home_object_detail', kwargs=kwargs) if category.site_id != settings.SITE_ID or domain: return 'http://' + category.site.domain + url return url
python
{ "resource": "" }
q4778
Publishable.is_published
train
def is_published(self): "Return True if the Publishable is currently active." cur_time = now() return self.published and cur_time > self.publish_from and \ (self.publish_to is None or cur_time < self.publish_to)
python
{ "resource": "" }
q4779
Box.resolve_params
train
def resolve_params(self, text): " Parse the parameters into a dict. " params = MultiValueDict() for line in text.split('\n'): pair = line.split(':', 1) if len(pair) == 2: params.appendlist(pair[0].strip(), pair[1].strip()) return params
python
{ "resource": "" }
q4780
Box.prepare
train
def prepare(self, context): """ Do the pre-processing - render and parse the parameters and store them for further use in self.params. """ self.params = {} # no params, not even a newline if not self.nodelist: return # just static text, no vars, assume one TextNode if not self.nodelist.contains_nontext: text = self.nodelist[0].s.strip() # vars in params, we have to render else: context.push() context['object'] = self.obj text = self.nodelist.render(context) context.pop() if text: self.params = self.resolve_params(text) # override the default template from the parameters if 'template_name' in self.params: self.template_name = self.params['template_name']
python
{ "resource": "" }
q4781
Box.get_context
train
def get_context(self): " Get context to render the template. " return { 'content_type_name' : str(self.name), 'content_type_verbose_name' : self.verbose_name, 'content_type_verbose_name_plural' : self.verbose_name_plural, 'object' : self.obj, 'box' : self, }
python
{ "resource": "" }
q4782
Box._render
train
def _render(self, context): " The main function that takes care of the rendering. " if self.template_name: t = loader.get_template(self.template_name) else: t_list = self._get_template_list() t = loader.select_template(t_list) context.update(self.get_context()) resp = t.render(context) context.pop() return resp
python
{ "resource": "" }
q4783
Box.get_cache_key
train
def get_cache_key(self): " Return a cache key constructed from the box's parameters. " if not self.is_model: return None pars = '' if self.params: pars = ','.join(':'.join((smart_str(key), smart_str(self.params[key]))) for key in sorted(self.params.keys())) return normalize_key('%s:box:%d:%s:%s' % ( _get_key(KEY_PREFIX, self.ct, pk=self.obj.pk), settings.SITE_ID, str(self.box_type), pars ))
python
{ "resource": "" }
q4784
Category.get_absolute_url
train
def get_absolute_url(self): """ Returns absolute URL for the category. """ if not self.tree_parent_id: url = reverse('root_homepage') else: url = reverse('category_detail', kwargs={'category' : self.tree_path}) if self.site_id != settings.SITE_ID: # prepend the domain if it doesn't match current Site return 'http://' + self.site.domain + url return url
python
{ "resource": "" }
q4785
listing
train
def listing(parser, token): """ Tag that will obtain listing of top objects for a given category and store them in context under given name. Usage:: {% listing <limit>[ from <offset>][of <app.model>[, <app.model>[, ...]]][ for <category> ] [with children|descendents] [using listing_handler] as <result> %} Parameters: ================================== ================================================ Option Description ================================== ================================================ ``limit`` Number of objects to retrieve. ``offset`` Starting with number (1-based), starts from first if no offset specified. ``app.model``, ... List of allowed models, all if omitted. ``category`` Category of the listing, all categories if not specified. Can be either string (tree path), or variable containing a Category object. ``children`` Include items from direct subcategories. ``descendents`` Include items from all descend subcategories. ``exclude`` Variable including a ``Publishable`` to omit. ``using`` Name of Listing Handler ro use ``result`` Store the resulting list in context under given name. ================================== ================================================ Examples:: {% listing 10 of articles.article for "home_page" as obj_list %} {% listing 10 of articles.article for category as obj_list %} {% listing 10 of articles.article for category with children as obj_list %} {% listing 10 of articles.article for category with descendents as obj_list %} {% listing 10 from 10 of articles.article as obj_list %} {% listing 10 of articles.article, photos.photo as obj_list %} """ var_name, parameters = listing_parse(token.split_contents()) return ListingNode(var_name, parameters)
python
{ "resource": "" }
q4786
do_render
train
def do_render(parser, token): """ Renders a rich-text field using defined markup. Example:: {% render some_var %} """ bits = token.split_contents() if len(bits) != 2: raise template.TemplateSyntaxError() return RenderNode(bits[1])
python
{ "resource": "" }
q4787
ipblur
train
def ipblur(text): # brutalizer ;-) """ blurs IP address """ import re m = re.match(r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.)\d{1,3}.*', text) if not m: return text return '%sxxx' % m.group(1)
python
{ "resource": "" }
q4788
register
train
def register(app_name, modules): """ simple module registering for later usage we don't want to import admin.py in models.py """ global INSTALLED_APPS_REGISTER mod_list = INSTALLED_APPS_REGISTER.get(app_name, []) if isinstance(modules, basestring): mod_list.append(modules) elif is_iterable(modules): mod_list.extend(modules) INSTALLED_APPS_REGISTER[app_name] = mod_list
python
{ "resource": "" }
q4789
related_by_category
train
def related_by_category(obj, count, collected_so_far, mods=[], only_from_same_site=True): """ Returns other Publishable objects related to ``obj`` by using the same category principle. Returns up to ``count`` objects. """ related = [] # top objects in given category if count > 0: from ella.core.models import Listing cat = obj.category listings = Listing.objects.get_queryset_wrapper( category=cat, content_types=[ContentType.objects.get_for_model(m) for m in mods] ) for l in listings[0:count + len(related)]: t = l.publishable if t != obj and t not in collected_so_far and t not in related: related.append(t) count -= 1 if count <= 0: return related return related
python
{ "resource": "" }
q4790
directly_related
train
def directly_related(obj, count, collected_so_far, mods=[], only_from_same_site=True): """ Returns objects related to ``obj`` up to ``count`` by searching ``Related`` instances for the ``obj``. """ # manually entered dependencies qset = Related.objects.filter(publishable=obj) if mods: qset = qset.filter(related_ct__in=[ ContentType.objects.get_for_model(m).pk for m in mods]) return get_cached_objects(qset.values_list('related_ct', 'related_id')[:count], missing=SKIP)
python
{ "resource": "" }
q4791
StructureReport.construct_xml_tree
train
def construct_xml_tree(self): """Construct the basic XML tree""" report = et.Element('report') plipversion = et.SubElement(report, 'plipversion') plipversion.text = __version__ date_of_creation = et.SubElement(report, 'date_of_creation') date_of_creation.text = time.strftime("%Y/%m/%d") citation_information = et.SubElement(report, 'citation_information') citation_information.text = "Salentin,S. et al. PLIP: fully automated protein-ligand interaction profiler. " \ "Nucl. Acids Res. (1 July 2015) 43 (W1): W443-W447. doi: 10.1093/nar/gkv315" mode = et.SubElement(report, 'mode') if config.DNARECEPTOR: mode.text = 'dna_receptor' else: mode.text = 'default' pdbid = et.SubElement(report, 'pdbid') pdbid.text = self.mol.pymol_name.upper() filetype = et.SubElement(report, 'filetype') filetype.text = self.mol.filetype.upper() pdbfile = et.SubElement(report, 'pdbfile') pdbfile.text = self.mol.sourcefiles['pdbcomplex'] pdbfixes = et.SubElement(report, 'pdbfixes') pdbfixes.text = str(self.mol.information['pdbfixes']) filename = et.SubElement(report, 'filename') filename.text = str(self.mol.sourcefiles.get('filename') or None) exligs = et.SubElement(report, 'excluded_ligands') for i, exlig in enumerate(self.excluded): e = et.SubElement(exligs, 'excluded_ligand', id=str(i + 1)) e.text = exlig covalent = et.SubElement(report, 'covlinkages') for i, covlinkage in enumerate(self.mol.covalent): e = et.SubElement(covalent, 'covlinkage', id=str(i + 1)) f1 = et.SubElement(e, 'res1') f2 = et.SubElement(e, 'res2') f1.text = ":".join([covlinkage.id1, covlinkage.chain1, str(covlinkage.pos1)]) f2.text = ":".join([covlinkage.id2, covlinkage.chain2, str(covlinkage.pos2)]) return report
python
{ "resource": "" }
q4792
StructureReport.construct_txt_file
train
def construct_txt_file(self): """Construct the header of the txt file""" textlines = ['Prediction of noncovalent interactions for PDB structure %s' % self.mol.pymol_name.upper(), ] textlines.append("=" * len(textlines[0])) textlines.append('Created on %s using PLIP v%s\n' % (time.strftime("%Y/%m/%d"), __version__)) textlines.append('If you are using PLIP in your work, please cite:') textlines.append('Salentin,S. et al. PLIP: fully automated protein-ligand interaction profiler.') textlines.append('Nucl. Acids Res. (1 July 2015) 43 (W1): W443-W447. doi: 10.1093/nar/gkv315\n') if len(self.excluded) != 0: textlines.append('Excluded molecules as ligands: %s\n' % ','.join([lig for lig in self.excluded])) if config.DNARECEPTOR: textlines.append('DNA/RNA in structure was chosen as the receptor part.\n') return textlines
python
{ "resource": "" }
q4793
StructureReport.get_bindingsite_data
train
def get_bindingsite_data(self): """Get the additional data for the binding sites""" for i, site in enumerate(sorted(self.mol.interaction_sets)): s = self.mol.interaction_sets[site] bindingsite = BindingSiteReport(s).generate_xml() bindingsite.set('id', str(i + 1)) bindingsite.set('has_interactions', 'False') self.xmlreport.insert(i + 1, bindingsite) for itype in BindingSiteReport(s).generate_txt(): self.txtreport.append(itype) if not s.no_interactions: bindingsite.set('has_interactions', 'True') else: self.txtreport.append('No interactions detected.') sys.stdout = sys.__stdout__
python
{ "resource": "" }
q4794
StructureReport.write_xml
train
def write_xml(self, as_string=False): """Write the XML report""" if not as_string: et.ElementTree(self.xmlreport).write('{}/{}.xml'.format(self.outpath, self.outputprefix), pretty_print=True, xml_declaration=True) else: output = et.tostring(self.xmlreport, pretty_print=True) if config.RAWSTRING: output = repr(output) print(output)
python
{ "resource": "" }
q4795
StructureReport.write_txt
train
def write_txt(self, as_string=False): """Write the TXT report""" if not as_string: with open('{}/{}.txt'.format(self.outpath, self.outputprefix), 'w') as f: [f.write(textline + '\n') for textline in self.txtreport] else: output = '\n'.join(self.txtreport) if config.RAWSTRING: output = repr(output) print(output)
python
{ "resource": "" }
q4796
BindingSiteReport.rst_table
train
def rst_table(self, array): """Given an array, the function formats and returns and table in rST format.""" # Determine cell width for each column cell_dict = {} for i, row in enumerate(array): for j, val in enumerate(row): if j not in cell_dict: cell_dict[j] = [] cell_dict[j].append(val) for item in cell_dict: cell_dict[item] = max([len(x) for x in cell_dict[item]]) + 1 # Contains adapted width for each column # Format top line num_cols = len(array[0]) form = '+' for col in range(num_cols): form += (cell_dict[col] + 1) * '-' form += '+' form += '\n' # Format values for i, row in enumerate(array): form += '| ' for j, val in enumerate(row): cell_width = cell_dict[j] form += str(val) + (cell_width - len(val)) * ' ' + '| ' form.rstrip() form += '\n' # Seperation lines form += '+' if i == 0: sign = '=' else: sign = '-' for col in range(num_cols): form += (cell_dict[col] + 1) * sign form += '+' form += '\n' return form
python
{ "resource": "" }
q4797
BindingSiteReport.generate_txt
train
def generate_txt(self): """Generates an flat text report for a single binding site""" txt = [] titletext = '%s (%s) - %s' % (self.bsid, self.longname, self.ligtype) txt.append(titletext) for i, member in enumerate(self.lig_members[1:]): txt.append(' + %s' % ":".join(str(element) for element in member)) txt.append("-" * len(titletext)) txt.append("Interacting chain(s): %s\n" % ','.join([chain for chain in self.interacting_chains])) for section in [['Hydrophobic Interactions', self.hydrophobic_features, self.hydrophobic_info], ['Hydrogen Bonds', self.hbond_features, self.hbond_info], ['Water Bridges', self.waterbridge_features, self.waterbridge_info], ['Salt Bridges', self.saltbridge_features, self.saltbridge_info], ['pi-Stacking', self.pistacking_features, self.pistacking_info], ['pi-Cation Interactions', self.pication_features, self.pication_info], ['Halogen Bonds', self.halogen_features, self.halogen_info], ['Metal Complexes', self.metal_features, self.metal_info]]: iname, features, interaction_information = section # Sort results first by res number, then by distance and finally ligand coordinates to get a unique order interaction_information = sorted(interaction_information, key=itemgetter(0, 2, -2)) if not len(interaction_information) == 0: txt.append('\n**%s**' % iname) table = [features, ] for single_contact in interaction_information: values = [] for x in single_contact: if type(x) == str: values.append(x) elif type(x) == tuple and len(x) == 3: # Coordinates values.append("%.3f, %.3f, %.3f" % x) else: values.append(str(x)) table.append(values) txt.append(self.rst_table(table)) txt.append('\n') return txt
python
{ "resource": "" }
q4798
pool_args
train
def pool_args(function, sequence, kwargs): """Return a single iterator of n elements of lists of length 3, given a sequence of len n.""" return zip(itertools.repeat(function), sequence, itertools.repeat(kwargs))
python
{ "resource": "" }
q4799
parallel_fn
train
def parallel_fn(f): """Simple wrapper function, returning a parallel version of the given function f. The function f must have one argument and may have an arbitray number of keyword arguments. """ def simple_parallel(func, sequence, **args): """ f takes an element of sequence as input and the keyword args in **args""" if 'processes' in args: processes = args.get('processes') del args['processes'] else: processes = multiprocessing.cpu_count() pool = multiprocessing.Pool(processes) # depends on available cores result = pool.map_async(universal_worker, pool_args(func, sequence, args)) pool.close() pool.join() cleaned = [x for x in result.get() if x is not None] # getting results cleaned = asarray(cleaned) return cleaned return partial(simple_parallel, f)
python
{ "resource": "" }