code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
f = urlopen("http://projects.biotec.tu-dresden.de/plip-rest/pdb/%s?format=xml" % pdbid.lower())
self.doc = etree.parse(f)
|
def load_data(self, pdbid)
|
Loads and parses an XML resource and saves it as a tree if successful
| 8.068703 | 7.347231 | 1.098196 |
"Write your forwards methods here."
for a in orm.Article.objects.all():
if a.updated:
a.last_updated = a.updated
a.save(force_update=True)
|
def forwards(self, orm)
|
Write your forwards methods here.
| 6.892205 | 5.726133 | 1.20364 |
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()]
|
def check_pdb_status(pdbid)
|
Returns the status and up-to-date entry in the PDB for a given PDB ID
| 4.438442 | 4.226874 | 1.050053 |
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]
|
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.
| 4.697468 | 4.518673 | 1.039568 |
" Delegate the boxing. "
obj = position.target
return getattr(position.target, 'box_class', Box)(obj, *args, **kwargs)
|
def PositionBox(position, *args, **kwargs)
|
Delegate the boxing.
| 15.182552 | 10.456577 | 1.451962 |
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
|
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
| 4.03601 | 4.103551 | 0.983541 |
" 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)
|
def render(self, context, nodelist, box_type)
|
Render the position.
| 5.301482 | 5.083361 | 1.042909 |
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)
|
def set_initial_representations(self)
|
General settings for PyMOL
| 10.648356 | 9.307961 | 1.144005 |
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()
|
def standard_settings(self)
|
Sets up standard settings for a nice visualization.
| 5.576202 | 5.278683 | 1.056362 |
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]')
|
def set_custom_colorset(self)
|
Defines a colorset with matching colors. Provided by Joachim.
| 2.675197 | 2.606722 | 1.026269 |
hydroph = self.plcomplex.hydrophobic_contacts
if not len(hydroph.bs_ids) == 0:
self.select_by_ids('Hydrophobic-P', hydroph.bs_ids, restrict=self.protname)
self.select_by_ids('Hydrophobic-L', hydroph.lig_ids, restrict=self.ligname)
for i in hydroph.pairs_ids:
cmd.select('tmp_bs', 'id %i & %s' % (i[0], self.protname))
cmd.select('tmp_lig', 'id %i & %s' % (i[1], self.ligname))
cmd.distance('Hydrophobic', 'tmp_bs', 'tmp_lig')
if self.object_exists('Hydrophobic'):
cmd.set('dash_gap', 0.5, 'Hydrophobic')
cmd.set('dash_color', 'grey50', 'Hydrophobic')
else:
cmd.select('Hydrophobic-P', 'None')
|
def show_hydrophobic(self)
|
Visualizes hydrophobic contacts.
| 3.54053 | 3.419345 | 1.035441 |
hbonds = self.plcomplex.hbonds
for group in [['HBondDonor-P', hbonds.prot_don_id],
['HBondAccept-P', hbonds.prot_acc_id]]:
if not len(group[1]) == 0:
self.select_by_ids(group[0], group[1], restrict=self.protname)
for group in [['HBondDonor-L', hbonds.lig_don_id],
['HBondAccept-L', hbonds.lig_acc_id]]:
if not len(group[1]) == 0:
self.select_by_ids(group[0], group[1], restrict=self.ligname)
for i in hbonds.ldon_id:
cmd.select('tmp_bs', 'id %i & %s' % (i[0], self.protname))
cmd.select('tmp_lig', 'id %i & %s' % (i[1], self.ligname))
cmd.distance('HBonds', 'tmp_bs', 'tmp_lig')
for i in hbonds.pdon_id:
cmd.select('tmp_bs', 'id %i & %s' % (i[1], self.protname))
cmd.select('tmp_lig', 'id %i & %s' % (i[0], self.ligname))
cmd.distance('HBonds', 'tmp_bs', 'tmp_lig')
if self.object_exists('HBonds'):
cmd.set('dash_color', 'blue', 'HBonds')
|
def show_hbonds(self)
|
Visualizes hydrogen bonds.
| 2.471569 | 2.449718 | 1.00892 |
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')
|
def show_halogen(self)
|
Visualize halogen bonds.
| 3.682363 | 3.621171 | 1.016899 |
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')
|
def show_stacking(self)
|
Visualize pi-stacking interactions.
| 2.598896 | 2.498405 | 1.040222 |
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')
|
def show_cationpi(self)
|
Visualize cation-pi interactions.
| 2.851665 | 2.808971 | 1.015199 |
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')
|
def show_sbridges(self)
|
Visualize salt bridges.
| 2.347747 | 2.268114 | 1.035109 |
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')
|
def show_wbridges(self)
|
Visualize water bridges.
| 2.254894 | 2.18889 | 1.030154 |
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')
|
def show_metal(self)
|
Visualize metal coordination.
| 3.005844 | 2.961511 | 1.01497 |
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-*')
|
def selections_cleanup(self)
|
Cleans up non-used selections
| 2.69161 | 2.643983 | 1.018013 |
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')
|
def selections_group(self)
|
Group all selections
| 7.886041 | 7.727473 | 1.02052 |
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')
|
def additional_cleanup(self)
|
Cleanup of various representations
| 22.301136 | 18.509573 | 1.204843 |
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)
|
def zoom_to_ligand(self)
|
Zoom in too ligand and its interactions.
| 6.390563 | 6.154906 | 1.038288 |
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]))
|
def save_session(self, outfolder, override=None)
|
Saves a PyMOL session file.
| 8.277981 | 6.763787 | 1.223868 |
sys.stdout = sys.__stdout__
cmd.feedback('disable', 'movie', 'everything')
cmd.viewport(width, height)
cmd.zoom('visible', 1.5) # Adapt the zoom to the viewport
cmd.set('ray_trace_frames', 1) # Frames are raytraced before saving an image.
cmd.mpng(filepath, 1, 1) # Use batch png mode with 1 frame only
cmd.mplay() # cmd.mpng needs the animation to 'run'
cmd.refresh()
originalfile = "".join([filepath, '0001.png'])
newfile = "".join([filepath, '.png'])
#################################################
# Wait for file for max. 1 second and rename it #
#################################################
attempts = 0
while not os.path.isfile(originalfile) and attempts <= 10:
sleep(0.1)
attempts += 1
if os.name == 'nt': # In Windows, make sure there is no file of the same name, cannot be overwritten as in Unix
if os.path.isfile(newfile):
os.remove(newfile)
os.rename(originalfile, newfile) # Remove frame number in filename
# Check if imagemagick is available and crop + resize the images
if subprocess.call("type convert", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0:
attempts, ecode = 0, 1
# Check if file is truncated and wait if that's the case
while ecode != 0 and attempts <= 10:
ecode = subprocess.call(['convert', newfile, '/dev/null'], stdout=open('/dev/null', 'w'),
stderr=subprocess.STDOUT)
sleep(0.1)
attempts += 1
trim = 'convert -trim ' + newfile + ' -bordercolor White -border 20x20 ' + newfile + ';' # Trim the image
os.system(trim)
getwidth = 'w=`convert ' + newfile + ' -ping -format "%w" info:`;' # Get the width of the new image
getheight = 'h=`convert ' + newfile + ' -ping -format "%h" info:`;' # Get the hight of the new image
newres = 'if [ "$w" -gt "$h" ]; then newr="${w%.*}x$w"; else newr="${h%.*}x$h"; fi;' # Set quadratic ratio
quadratic = 'convert ' + newfile + ' -gravity center -extent "$newr" ' + newfile # Fill with whitespace
os.system(getwidth + getheight + newres + quadratic)
else:
sys.stderr.write('Imagemagick not available. Images will not be resized or cropped.')
|
def png_workaround(self, filepath, width=1200, height=800)
|
Workaround for (a) severe bug(s) in PyMOL preventing ray-traced images to be produced in command-line mode.
Use this function in case neither cmd.ray() or cmd.png() work.
| 4.800377 | 4.657982 | 1.03057 |
self.set_fancy_ray()
self.png_workaround("/".join([outfolder, filename]))
|
def save_picture(self, outfolder, filename)
|
Saves a picture
| 26.414923 | 29.443037 | 0.897153 |
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)
|
def set_fancy_ray(self)
|
Give the molecule a flat, modern look.
| 4.579589 | 3.583268 | 1.278048 |
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)
|
def adapt_for_peptides(self)
|
Adapt visualization for peptide ligands and interchain contacts
| 6.755741 | 5.979421 | 1.129832 |
# 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()
|
def refinements(self)
|
Refinements for the visualization
| 5.153779 | 5.082148 | 1.014095 |
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
|
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
| 3.238363 | 3.325813 | 0.973706 |
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
|
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
| 2.572093 | 2.582253 | 0.996066 |
try:
return get_cached_object(model, timeout=timeout, **kwargs)
except ObjectDoesNotExist, e:
raise Http404('Reason: %s' % str(e))
|
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
| 3.090898 | 2.821947 | 1.095307 |
return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc)
|
def tmpfile(prefix, direc)
|
Returns the path to a newly created temporary file.
| 4.09255 | 3.963167 | 1.032646 |
p = re.compile("[0-9][0-9a-z]{3}")
m = p.search(string.lower())
try:
return m.group()
except AttributeError:
return "UnknownProtein"
|
def extract_pdbid(string)
|
Use regular expressions to get a PDB ID from a string
| 3.794184 | 3.800384 | 0.998369 |
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
|
def whichrestype(atom)
|
Returns the residue name of an Pybel or OpenBabel atom.
| 4.877939 | 3.042887 | 1.603062 |
atom = atom if not isinstance(atom, Atom) else atom.OBAtom # Convert to OpenBabel Atom
return atom.GetResidue().GetNum() if atom.GetResidue() is not None else None
|
def whichresnumber(atom)
|
Returns the residue number of an Pybel or OpenBabel atom (numbering as in original PDB file).
| 4.595992 | 3.244417 | 1.416585 |
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
|
def whichchain(atom)
|
Returns the residue number of an PyBel or OpenBabel atom.
| 4.607178 | 3.636487 | 1.266931 |
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)
|
def euclidean3d(v1, v2)
|
Faster implementation of euclidean distance for the 3D case.
| 1.894291 | 1.76815 | 1.071341 |
return None if len(p1) != len(p2) else np.array([p2[i] - p1[i] for i in range(len(p1))])
|
def vector(p1, p2)
|
Vector from p1 to p2.
:param p1: coordinates of point p1
:param p2: coordinates of point p2
:returns : numpy array with vector coordinates
| 2.33703 | 2.875709 | 0.81268 |
if np.array_equal(v1, v2):
return 0.0
dm = np.dot(v1, v2)
cm = np.linalg.norm(v1) * np.linalg.norm(v2)
angle = np.arccos(round(dm / cm, 10)) # Round here to prevent floating point errors
return np.degrees([angle, ])[0] if deg else angle
|
def vecangle(v1, v2, deg=True)
|
Calculate the angle between two vectors
:param v1: coordinates of vector v1
:param v2: coordinates of vector v2
:returns : angle in degree or rad
| 3.13121 | 3.591776 | 0.871772 |
norm = np.linalg.norm(v)
return v/norm if not norm == 0 else v
|
def normalize_vector(v)
|
Take a vector and return the normalized vector
:param v: a vector v
:returns : normalized vector v
| 3.621024 | 4.198097 | 0.862539 |
return list(map(np.mean, (([c[0] for c in coo]), ([c[1] for c in coo]), ([c[2] for c in coo]))))
|
def centroid(coo)
|
Calculates the centroid from a 3D point cloud and returns the coordinates
:param coo: Array of coordinate arrays
:returns : centroid coordinates as list
| 3.282466 | 3.5806 | 0.916736 |
location = {} # hashtable of which cluster each element is in
clusters = []
# Go through each double
for t in double_list:
a, b = t[0], t[1]
# If they both are already in different clusters, merge the clusters
if a in location and b in location:
if location[a] != location[b]:
if location[a] < location[b]:
clusters[location[a]] = clusters[location[a]].union(clusters[location[b]]) # Merge clusters
clusters = clusters[:location[b]] + clusters[location[b]+1:]
else:
clusters[location[b]] = clusters[location[b]].union(clusters[location[a]]) # Merge clusters
clusters = clusters[:location[a]] + clusters[location[a]+1:]
# Rebuild index of locations for each element as they have changed now
location = {}
for i, cluster in enumerate(clusters):
for c in cluster:
location[c] = i
else:
# If a is already in a cluster, add b to that cluster
if a in location:
clusters[location[a]].add(b)
location[b] = location[a]
# If b is already in a cluster, add a to that cluster
if b in location:
clusters[location[b]].add(a)
location[a] = location[b]
# If neither a nor b is in any cluster, create a new one with a and b
if not (b in location and a in location):
clusters.append(set(t))
location[a] = len(clusters) - 1
location[b] = len(clusters) - 1
return map(tuple, clusters)
|
def cluster_doubles(double_list)
|
Given a list of doubles, they are clustered if they share one element
:param double_list: list of doubles
:returns : list of clusters (tuples)
| 2.246291 | 2.285788 | 0.982721 |
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)
|
def create_folder_if_not_exists(folder_path)
|
Creates a folder if it does not exists.
| 3.145183 | 2.97047 | 1.058817 |
import pymol
# Pass standard arguments of function to prevent PyMOL from printing out PDB headers (workaround)
pymol.finish_launching(args=['pymol', options, '-K'])
pymol.cmd.reinitialize()
|
def initialize_pymol(options)
|
Initializes PyMOL
| 10.59988 | 10.929196 | 0.969868 |
import pymol
pymol.pymol_argv = ['pymol', '%s' % options] + sys.argv[1:]
if run:
initialize_pymol(options)
if quiet:
pymol.cmd.feedback('disable', 'all', 'everything')
|
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.
| 3.914599 | 4.427754 | 0.884105 |
nuc_covalent = []
#######################################
# Basic support for RNA/DNA as ligand #
#######################################
nucleotides = ['A', 'C', 'T', 'G', 'U', 'DA', 'DC', 'DT', 'DG', 'DU']
dna_rna = {} # Dictionary of DNA/RNA residues by chain
covlinkage = namedtuple("covlinkage", "id1 chain1 pos1 conf1 id2 chain2 pos2 conf2")
# Create missing covlinkage entries for DNA/RNA
for ligand in residues:
resname, chain, pos = ligand
if resname in nucleotides:
if chain not in dna_rna:
dna_rna[chain] = [(resname, pos), ]
else:
dna_rna[chain].append((resname, pos))
for chain in dna_rna:
nuc_list = dna_rna[chain]
for i, nucleotide in enumerate(nuc_list):
if not i == len(nuc_list) - 1:
name, pos = nucleotide
nextnucleotide = nuc_list[i + 1]
nextname, nextpos = nextnucleotide
newlink = covlinkage(id1=name, chain1=chain, pos1=pos, conf1='',
id2=nextname, chain2=chain, pos2=nextpos, conf2='')
nuc_covalent.append(newlink)
return nuc_covalent
|
def nucleotide_linkage(residues)
|
Support for DNA/RNA ligands by finding missing covalent linkages to stitch DNA/RNA together.
| 2.859063 | 2.648831 | 1.079368 |
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
|
def ring_is_planar(ring, r_atoms)
|
Given a set of ring atoms, check if the ring is sufficiently planar
to be considered aromatic
| 4.053741 | 3.932186 | 1.030913 |
if len(names) > 3: # Polymer
if len(set(config.RNA).intersection(set(names))) != 0:
ligtype = 'RNA'
elif len(set(config.DNA).intersection(set(names))) != 0:
ligtype = 'DNA'
else:
ligtype = "POLYMER"
else:
ligtype = 'SMALLMOLECULE'
for name in names:
if name in config.METAL_IONS:
if len(names) == 1:
ligtype = 'ION'
else:
if "ION" not in ligtype:
ligtype += '+ION'
return ligtype
|
def classify_by_name(names)
|
Classify a (composite) ligand by the HETID(s)
| 3.497292 | 3.327803 | 1.050931 |
main = [x for x in members if x[0] not in config.METAL_IONS]
ion = [x for x in members if x[0] in config.METAL_IONS]
sorted_main = sorted(main, key=lambda x: (x[1], x[2]))
sorted_main = sorted(main, key=lambda x: (x[1], x[2]))
sorted_ion = sorted(ion, key=lambda x: (x[1], x[2]))
return sorted_main + sorted_ion
|
def sort_members_by_importance(members)
|
Sort the members of a composite ligand according to two criteria:
1. Split up in main and ion group. Ion groups are located behind the main group.
2. Within each group, sort by chain and position.
| 2.339442 | 2.033025 | 1.15072 |
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
|
def get_isomorphisms(reference, lig)
|
Get all isomorphisms of the ligand.
| 5.076545 | 4.794132 | 1.058908 |
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
|
def canonicalize(lig, preserve_bond_order=False)
|
Get the canonical atom order for the ligand.
| 3.489999 | 3.363304 | 1.03767 |
dct = {}
if int32 == 4294967295: # Special case in some structures (note, this is just a workaround)
return -1
for i in range(-1000, -1):
dct[np.uint32(i)] = i
if int32 in dct:
return dct[int32]
else:
return int32
|
def int32_to_negative(int32)
|
Checks if a suspicious number (e.g. ligand position) is in fact a negative number represented as a
32 bit integer and returns the actual number.
| 4.043468 | 3.71039 | 1.089769 |
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)
|
def read_pdb(pdbfname, as_string=False)
|
Reads a given PDB file and returns a Pybel Molecule.
| 4.889194 | 4.626408 | 1.056801 |
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')
|
def read(fil)
|
Returns a file handler and detects gzipped files.
| 1.793573 | 1.668548 | 1.07493 |
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.')
|
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.
| 4.750866 | 4.635437 | 1.024901 |
# 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
|
def colorlog(msg, color, bold=False, blink=False)
|
Colors messages on non-Windows systems supporting ANSI escape.
| 1.792547 | 1.750901 | 1.023785 |
if (mtype == 'debug' and config.DEBUG) or (mtype != 'debug' and config.VERBOSE) or mtype == 'error':
message(msg, indent=indent, mtype=mtype, caption=caption)
|
def write_message(msg, indent=False, mtype='standard', caption=False)
|
Writes message if verbose mode is set.
| 3.15766 | 3.042979 | 1.037687 |
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)
|
def message(msg, indent=False, mtype='standard', caption=False)
|
Writes messages in verbose mode
| 1.952711 | 1.961165 | 0.995689 |
bits = token.split_contents()
obj_var, count, var_name, mods, finder = parse_related_tag(bits)
return RelatedNode(obj_var, count, var_name, mods, finder)
|
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 %}
| 5.005498 | 7.430182 | 0.673671 |
"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)
|
def PublishableBox(publishable, box_type, nodelist, model=None)
|
add some content type info of self.target
| 5.46488 | 2.966569 | 1.842155 |
" Delegate the boxing to the target's Box class. "
obj = listing.publishable
return obj.box_class(obj, *args, **kwargs)
|
def ListingBox(listing, *args, **kwargs)
|
Delegate the boxing to the target's Box class.
| 15.123206 | 7.420099 | 2.038141 |
" 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
|
def get_absolute_url(self, domain=False)
|
Get object's URL.
| 2.917336 | 2.830529 | 1.030668 |
"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)
|
def is_published(self)
|
Return True if the Publishable is currently active.
| 5.701272 | 4.247252 | 1.342344 |
" 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
|
def resolve_params(self, text)
|
Parse the parameters into a dict.
| 3.538936 | 3.05549 | 1.158222 |
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']
|
def prepare(self, context)
|
Do the pre-processing - render and parse the parameters and
store them for further use in self.params.
| 5.606721 | 5.211858 | 1.075763 |
" 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,
}
|
def get_context(self)
|
Get context to render the template.
| 3.909336 | 3.588416 | 1.089432 |
self.prepare(context)
" Cached wrapper around self._render(). "
if getattr(settings, 'DOUBLE_RENDER', False) and self.can_double_render:
if 'SECOND_RENDER' not in context:
return self.double_render()
key = self.get_cache_key()
if key:
rend = cache.get(key)
if rend is None:
rend = self._render(context)
cache.set(key, rend, core_settings.CACHE_TIMEOUT)
else:
rend = self._render(context)
return rend
|
def render(self, context)
|
Cached wrapper around self._render().
| 4.222693 | 3.579582 | 1.179661 |
" Get the hierarchy of templates belonging to the object/box_type given. "
t_list = []
if hasattr(self.obj, 'category_id') and self.obj.category_id:
cat = self.obj.category
base_path = 'box/category/%s/content_type/%s/' % (cat.path, self.name)
if hasattr(self.obj, 'slug'):
t_list.append(base_path + '%s/%s.html' % (self.obj.slug, self.box_type,))
t_list.append(base_path + '%s.html' % (self.box_type,))
t_list.append(base_path + 'box.html')
base_path = 'box/content_type/%s/' % self.name
if hasattr(self.obj, 'slug'):
t_list.append(base_path + '%s/%s.html' % (self.obj.slug, self.box_type,))
t_list.append(base_path + '%s.html' % (self.box_type,))
t_list.append(base_path + 'box.html')
t_list.append('box/%s.html' % self.box_type)
t_list.append('box/box.html')
return t_list
|
def _get_template_list(self)
|
Get the hierarchy of templates belonging to the object/box_type given.
| 2.411965 | 2.026831 | 1.190018 |
" 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
|
def _render(self, context)
|
The main function that takes care of the rendering.
| 3.515968 | 2.981313 | 1.179336 |
" 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
))
|
def get_cache_key(self)
|
Return a cache key constructed from the box's parameters.
| 7.03121 | 5.711725 | 1.231013 |
"Override save() to construct tree_path based on the category's parent."
old_tree_path = self.tree_path
if self.tree_parent:
if self.tree_parent.tree_path:
self.tree_path = '%s/%s' % (self.tree_parent.tree_path, self.slug)
else:
self.tree_path = self.slug
else:
self.tree_path = ''
Category.objects.clear_cache()
super(Category, self).save(**kwargs)
if old_tree_path != self.tree_path:
# the tree_path has changed, update children
children = Category.objects.filter(tree_parent=self)
for child in children:
child.save(force_update=True)
|
def save(self, **kwargs)
|
Override save() to construct tree_path based on the category's parent.
| 2.849672 | 2.083506 | 1.367729 |
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
|
def get_absolute_url(self)
|
Returns absolute URL for the category.
| 5.096025 | 4.494264 | 1.133895 |
var_name, parameters = listing_parse(token.split_contents())
return ListingNode(var_name, parameters)
|
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 %}
| 5.597157 | 12.818094 | 0.436661 |
bits = token.split_contents()
nodelist = parser.parse(('end' + bits[0],))
parser.delete_first_token()
return _parse_box(nodelist, bits)
|
def do_box(parser, token)
|
Tag Node representing our idea of a reusable box. It can handle multiple
parameters in its body which will then be accessible via ``{{ box.params
}}`` in the template being rendered.
.. note::
The inside of the box will be rendered only when redering the box in
current context and the ``object`` template variable will be present
and set to the target of the box.
Author of any ``Model`` can specify it's own ``box_class`` which enables
custom handling of some content types (boxes for polls for example need
some extra information to render properly).
Boxes, same as :ref:`core-views`, look for most specific template for a given
object an only fall back to more generic template if the more specific one
doesn't exist. The list of templates it looks for:
* ``box/category/<tree_path>/content_type/<app>.<model>/<slug>/<box_name>.html``
* ``box/category/<tree_path>/content_type/<app>.<model>/<box_name>.html``
* ``box/category/<tree_path>/content_type/<app>.<model>/box.html``
* ``box/content_type/<app>.<model>/<slug>/<box_name>.html``
* ``box/content_type/<app>.<model>/<box_name>.html``
* ``box/content_type/<app>.<model>/box.html``
* ``box/<box_name>.html``
* ``box/box.html``
.. note::
Since boxes work for all models (and not just ``Publishable`` subclasses),
some template names don't exist for some model classes, for example
``Photo`` model doesn't have a link to ``Category`` so that cannot be used.
Boxes are always rendered in current context with added variables:
* ``object`` - object being represented
* ``box`` - instance of ``ella.core.box.Box``
Usage::
{% box <boxtype> for <app.model> with <field> <value> %}
param_name: value
param_name_2: {{ some_var }}
{% endbox %}
{% box <boxtype> for <var_name> %}
...
{% endbox %}
Parameters:
================================== ================================================
Option Description
================================== ================================================
``boxtype`` Name of the box to use
``app.model`` Model class to use
``field`` Field on which to do DB lookup
``value`` Value for DB lookup
``var_name`` Template variable to get the instance from
================================== ================================================
Examples::
{% box home_listing for articles.article with slug "some-slug" %}{% endbox %}
{% box home_listing for articles.article with pk object_id %}
template_name : {{object.get_box_template}}
{% endbox %}
{% box home_listing for article %}{% endbox %}
| 3.001352 | 5.255298 | 0.57111 |
bits = token.split_contents()
if len(bits) != 2:
raise template.TemplateSyntaxError()
return RenderNode(bits[1])
|
def do_render(parser, token)
|
Renders a rich-text field using defined markup.
Example::
{% render some_var %}
| 2.684043 | 5.490298 | 0.48887 |
return text
return '%sxxx' % m.group(1)
|
def ipblur(text): # brutalizer ;-)
import re
m = re.match(r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.)\d{1,3}.*', text)
if not m
|
blurs IP address
| 11.162762 | 9.698962 | 1.150923 |
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
|
def register(app_name, modules)
|
simple module registering for later usage
we don't want to import admin.py in models.py
| 2.461436 | 2.527344 | 0.973922 |
for app in settings.INSTALLED_APPS:
modules = set(auto_discover)
if app in INSTALLED_APPS_REGISTER:
modules.update(INSTALLED_APPS_REGISTER[app])
for module in modules:
mod = import_module(app)
try:
import_module('%s.%s' % (app, module))
inst = getattr(mod, '__install__', lambda: None)
inst()
except:
if module_has_submodule(mod, module):
raise
app_modules_loaded.send(sender=None)
|
def call_modules(auto_discover=())
|
this is called in project urls.py
for registering desired modules (eg.: admin.py)
| 3.545628 | 3.439775 | 1.030773 |
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
|
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.
| 4.740594 | 4.612127 | 1.027854 |
# 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)
|
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``.
| 6.384448 | 6.155228 | 1.03724 |
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
|
def construct_xml_tree(self)
|
Construct the basic XML tree
| 2.860882 | 2.849778 | 1.003896 |
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
|
def construct_txt_file(self)
|
Construct the header of the txt file
| 6.227614 | 6.101932 | 1.020597 |
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__
|
def get_bindingsite_data(self)
|
Get the additional data for the binding sites
| 4.448379 | 4.302264 | 1.033962 |
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)
|
def write_xml(self, as_string=False)
|
Write the XML report
| 4.073793 | 3.754067 | 1.085168 |
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)
|
def write_txt(self, as_string=False)
|
Write the TXT report
| 4.293231 | 3.898379 | 1.101286 |
if not len(info) == 0:
f.write('\n\n### %s ###\n' % name)
f.write('%s\n' % '\t'.join(features))
for line in info:
f.write('%s\n' % '\t'.join(map(str, line)))
|
def write_section(self, name, features, info, f)
|
Provides formatting for one section (e.g. hydrogen bonds)
| 2.606894 | 2.528591 | 1.030967 |
# 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
|
def rst_table(self, array)
|
Given an array, the function formats and returns and table in rST format.
| 2.451727 | 2.412378 | 1.016311 |
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
|
def generate_txt(self)
|
Generates an flat text report for a single binding site
| 3.286023 | 3.219848 | 1.020552 |
return zip(itertools.repeat(function), sequence, itertools.repeat(kwargs))
|
def pool_args(function, sequence, kwargs)
|
Return a single iterator of n elements of lists of length 3, given a sequence of len n.
| 4.436876 | 3.843724 | 1.154317 |
def simple_parallel(func, sequence, **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)
|
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.
| 4.299459 | 4.368594 | 0.984174 |
if self.as_string:
fil = self.pdbpath.rstrip('\n').split('\n') # Removing trailing newline character
else:
f = read(self.pdbpath)
fil = f.readlines()
f.close()
corrected_lines = []
i, j = 0, 0 # idx and PDB numbering
d = {}
modres = set()
covalent = []
alt = []
previous_ter = False
# Standard without fixing
if not config.NOFIX:
if not config.PLUGIN_MODE:
lastnum = 0 # Atom numbering (has to be consecutive)
other_models = False
for line in fil:
if not other_models: # Only consider the first model in an NRM structure
corrected_line, newnum = self.fix_pdbline(line, lastnum)
if corrected_line is not None:
if corrected_line.startswith('MODEL'):
try: # Get number of MODEL (1,2,3)
model_num = int(corrected_line[10:14])
if model_num > 1: # MODEL 2,3,4 etc.
other_models = True
except ValueError:
write_message("Ignoring invalid MODEL entry: %s\n" % corrected_line, mtype='debug')
corrected_lines.append(corrected_line)
lastnum = newnum
corrected_pdb = ''.join(corrected_lines)
else:
corrected_pdb = self.pdbpath
corrected_lines = fil
else:
corrected_pdb = self.pdbpath
corrected_lines = fil
for line in corrected_lines:
if line.startswith(("ATOM", "HETATM")):
# Retrieve alternate conformations
atomid, location = int(line[6:11]), line[16]
location = 'A' if location == ' ' else location
if location != 'A':
alt.append(atomid)
if not previous_ter:
i += 1
j += 1
else:
i += 1
j += 2
d[i] = j
previous_ter = False
# Numbering Changes at TER records
if line.startswith("TER"):
previous_ter = True
# Get modified residues
if line.startswith("MODRES"):
modres.add(line[12:15].strip())
# Get covalent linkages between ligands
if line.startswith("LINK"):
covalent.append(self.get_linkage(line))
return d, modres, covalent, alt, corrected_pdb
|
def parse_pdb(self)
|
Extracts additional information from PDB files.
I. When reading in a PDB file, OpenBabel numbers ATOMS and HETATOMS continously.
In PDB files, TER records are also counted, leading to a different numbering system.
This functions reads in a PDB file and provides a mapping as a dictionary.
II. Additionally, it returns a list of modified residues.
III. Furthermore, covalent linkages between ligands and protein residues/other ligands are identified
IV. Alternative conformations
| 4.472701 | 4.188336 | 1.067894 |
conf1, id1, chain1, pos1 = line[16].strip(), line[17:20].strip(), line[21].strip(), int(line[22:26])
conf2, id2, chain2, pos2 = line[46].strip(), line[47:50].strip(), line[51].strip(), int(line[52:56])
return self.covlinkage(id1=id1, chain1=chain1, pos1=pos1, conf1=conf1,
id2=id2, chain2=chain2, pos2=pos2, conf2=conf2)
|
def get_linkage(self, line)
|
Get the linkage information from a LINK entry PDB line.
| 2.186912 | 2.017919 | 1.083746 |
all_from_chain = [o for o in pybel.ob.OBResidueIter(
self.proteincomplex.OBMol) if o.GetChain() == chain] # All residues from chain
if len(all_from_chain) == 0:
return None
else:
non_water = [o for o in all_from_chain if not o.GetResidueProperty(9)]
ligand = self.extract_ligand(non_water)
return ligand
|
def getpeptides(self, chain)
|
If peptide ligand chains are defined via the command line options,
try to extract the underlying ligand formed by all residues in the
given chain without water
| 4.324294 | 3.896327 | 1.109838 |
if config.PEPTIDES == [] and config.INTRA is None:
# Extract small molecule ligands (default)
ligands = []
# Filter for ligands using lists
ligand_residues, self.lignames_all, self.water = self.filter_for_ligands()
all_res_dict = {(a.GetName(), a.GetChain(), a.GetNum()): a for a in ligand_residues}
self.lignames_kept = list(set([a.GetName() for a in ligand_residues]))
if not config.BREAKCOMPOSITE:
# Update register of covalent links with those between DNA/RNA subunits
self.covalent += nucleotide_linkage(all_res_dict)
# Find fragment linked by covalent bonds
res_kmers = self.identify_kmers(all_res_dict)
else:
res_kmers = [[a, ] for a in ligand_residues]
write_message("{} ligand kmer(s) detected for closer inspection.\n".format(len(res_kmers)), mtype='debug')
for kmer in res_kmers: # iterate over all ligands and extract molecules + information
if len(kmer) > config.MAX_COMPOSITE_LENGTH:
write_message("Ligand kmer(s) filtered out with a length of {} fragments ({} allowed).\n".format(
len(kmer), config.MAX_COMPOSITE_LENGTH), mtype='debug')
else:
ligands.append(self.extract_ligand(kmer))
else:
# Extract peptides from given chains
self.water = [o for o in pybel.ob.OBResidueIter(self.proteincomplex.OBMol) if o.GetResidueProperty(9)]
if config.PEPTIDES != []:
peptide_ligands = [self.getpeptides(chain) for chain in config.PEPTIDES]
elif config.INTRA is not None:
peptide_ligands = [self.getpeptides(config.INTRA), ]
ligands = [p for p in peptide_ligands if p is not None]
self.covalent, self.lignames_kept, self.lignames_all = [], [], set()
return [lig for lig in ligands if len(lig.mol.atoms) != 0]
|
def getligs(self)
|
Get all ligands from a PDB file and prepare them for analysis.
Returns all non-empty ligands.
| 5.27162 | 5.257302 | 1.002723 |
if not obres.GetResidueProperty(0):
# If the residue is NOT amino (0)
# It can be amino_nucleo, coenzme, ion, nucleo, protein, purine, pyrimidine, solvent
# In these cases, it is a ligand candidate
return True
else:
# Here, the residue is classified as amino
# Amino acids can still be ligands, so we check for HETATM entries
# Only residues with at least one HETATM entry are processed as ligands
het_atoms = []
for atm in pybel.ob.OBResidueAtomIter(obres):
het_atoms.append(obres.IsHetAtom(atm))
if True in het_atoms:
return True
return False
|
def is_het_residue(self, obres)
|
Given an OBResidue, determines if the residue is indeed a possible ligand
in the PDB file
| 6.739906 | 6.526641 | 1.032676 |
candidates1 = [o for o in pybel.ob.OBResidueIter(
self.proteincomplex.OBMol) if not o.GetResidueProperty(9) and self.is_het_residue(o)]
if config.DNARECEPTOR: # If DNA is the receptor, don't consider DNA as a ligand
candidates1 = [res for res in candidates1 if res.GetName() not in config.DNA+config.RNA]
all_lignames = set([a.GetName() for a in candidates1])
water = [o for o in pybel.ob.OBResidueIter(self.proteincomplex.OBMol) if o.GetResidueProperty(9)]
# Filter out non-ligands
if not config.KEEPMOD: # Keep modified residues as ligands
candidates2 = [a for a in candidates1 if is_lig(a.GetName()) and a.GetName() not in self.modresidues]
else:
candidates2 = [a for a in candidates1 if is_lig(a.GetName())]
write_message("%i ligand(s) after first filtering step.\n" % len(candidates2), mtype='debug')
############################################
# Filtering by counting and artifacts list #
############################################
artifacts = []
unique_ligs = set(a.GetName() for a in candidates2)
for ulig in unique_ligs:
# Discard if appearing 15 times or more and is possible artifact
if ulig in config.biolip_list and [a.GetName() for a in candidates2].count(ulig) >= 15:
artifacts.append(ulig)
selected_ligands = [a for a in candidates2 if a.GetName() not in artifacts]
return selected_ligands, all_lignames, water
|
def filter_for_ligands(self)
|
Given an OpenBabel Molecule, get all ligands, their names, and water
| 4.920717 | 4.832036 | 1.018353 |
# Remove all those not considered by ligands and pairings including alternate conformations
ligdoubles = [[(link.id1, link.chain1, link.pos1),
(link.id2, link.chain2, link.pos2)] for link in
[c for c in self.covalent if c.id1 in self.lignames_kept and c.id2 in self.lignames_kept
and c.conf1 in ['A', ''] and c.conf2 in ['A', '']
and (c.id1, c.chain1, c.pos1) in residues
and (c.id2, c.chain2, c.pos2) in residues]]
kmers = cluster_doubles(ligdoubles)
if not kmers: # No ligand kmers, just normal independent ligands
return [[residues[res]] for res in residues]
else:
# res_kmers contains clusters of covalently bound ligand residues (kmer ligands)
res_kmers = [[residues[res] for res in kmer] for kmer in kmers]
# In this case, add other ligands which are not part of a kmer
in_kmer = []
for res_kmer in res_kmers:
for res in res_kmer:
in_kmer.append((res.GetName(), res.GetChain(), res.GetNum()))
for res in residues:
if res not in in_kmer:
newres = [residues[res], ]
res_kmers.append(newres)
return res_kmers
|
def identify_kmers(self, residues)
|
Using the covalent linkage information, find out which fragments/subunits form a ligand.
| 4.139615 | 4.012419 | 1.031701 |
mapped_idx = self.mapid(idx, 'reversed')
return pybel.Atom(self.original_structure.GetAtom(mapped_idx))
|
def id_to_atom(self, idx)
|
Returns the atom for a given original ligand ID.
To do this, the ID is mapped to the protein first and then the atom returned.
| 12.610376 | 8.775669 | 1.43697 |
atom_set = []
data = namedtuple('hydrophobic', 'atom orig_atom orig_idx')
atm = [a for a in all_atoms if a.atomicnum == 6 and set([natom.GetAtomicNum() for natom
in pybel.ob.OBAtomAtomIter(a.OBAtom)]).issubset(
{1, 6})]
for atom in atm:
orig_idx = self.Mapper.mapid(atom.idx, mtype=self.mtype, bsid=self.bsid)
orig_atom = self.Mapper.id_to_atom(orig_idx)
if atom.idx not in self.altconf:
atom_set.append(data(atom=atom, orig_atom=orig_atom, orig_idx=orig_idx))
return atom_set
|
def hydrophobic_atoms(self, all_atoms)
|
Select all carbon atoms which have only carbons and/or hydrogens as direct neighbors.
| 4.311481 | 4.114625 | 1.047843 |
data = namedtuple('hbondacceptor', 'a a_orig_atom a_orig_idx type')
a_set = []
for atom in filter(lambda at: at.OBAtom.IsHbondAcceptor(), all_atoms):
if atom.atomicnum not in [9, 17, 35, 53] and atom.idx not in self.altconf: # Exclude halogen atoms
a_orig_idx = self.Mapper.mapid(atom.idx, mtype=self.mtype, bsid=self.bsid)
a_orig_atom = self.Mapper.id_to_atom(a_orig_idx)
a_set.append(data(a=atom, a_orig_atom=a_orig_atom, a_orig_idx=a_orig_idx, type='regular'))
return a_set
|
def find_hba(self, all_atoms)
|
Find all possible hydrogen bond acceptors
| 4.124291 | 3.961205 | 1.041171 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.