repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
ssalentin/plip | plip/modules/pymolplip.py | PyMOLVisualizer.show_sbridges | 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 | 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') | Visualize salt bridges. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L193-L219 |
ssalentin/plip | plip/modules/pymolplip.py | PyMOLVisualizer.show_wbridges | 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 | 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') | Visualize water bridges. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L221-L242 |
ssalentin/plip | plip/modules/pymolplip.py | PyMOLVisualizer.show_metal | 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 | 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') | Visualize metal coordination. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L244-L267 |
ssalentin/plip | plip/modules/pymolplip.py | PyMOLVisualizer.selections_cleanup | 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 | 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-*') | Cleans up non-used selections | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L269-L289 |
ssalentin/plip | plip/modules/pymolplip.py | PyMOLVisualizer.selections_group | 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 | 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') | Group all selections | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L291-L303 |
ssalentin/plip | plip/modules/pymolplip.py | PyMOLVisualizer.additional_cleanup | 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 | 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') | Cleanup of various representations | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L305-L311 |
ssalentin/plip | plip/modules/pymolplip.py | PyMOLVisualizer.zoom_to_ligand | 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 | 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) | Zoom in too ligand and its interactions. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L313-L323 |
ssalentin/plip | plip/modules/pymolplip.py | PyMOLVisualizer.save_session | 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 | 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])) | Saves a PyMOL session file. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L325-L331 |
ssalentin/plip | plip/modules/pymolplip.py | PyMOLVisualizer.png_workaround | 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.
"""
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.') | python | 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.
"""
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.') | 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. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L333-L378 |
ssalentin/plip | plip/modules/pymolplip.py | PyMOLVisualizer.save_picture | def save_picture(self, outfolder, filename):
"""Saves a picture"""
self.set_fancy_ray()
self.png_workaround("/".join([outfolder, filename])) | python | def save_picture(self, outfolder, filename):
"""Saves a picture"""
self.set_fancy_ray()
self.png_workaround("/".join([outfolder, filename])) | Saves a picture | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L380-L383 |
ssalentin/plip | plip/modules/pymolplip.py | PyMOLVisualizer.set_fancy_ray | 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 | 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) | Give the molecule a flat, modern look. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L385-L396 |
ssalentin/plip | plip/modules/pymolplip.py | PyMOLVisualizer.adapt_for_peptides | 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 | 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) | Adapt visualization for peptide ligands and interchain contacts | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L398-L406 |
ssalentin/plip | plip/modules/pymolplip.py | PyMOLVisualizer.refinements | 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 | 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() | Refinements for the visualization | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L411-L454 |
ella/ella | ella/core/cache/utils.py | get_cached_object | 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 | 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 | 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 | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/cache/utils.py#L70-L107 |
ella/ella | ella/core/cache/utils.py | get_cached_objects | 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 | 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 | 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 | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/cache/utils.py#L113-L184 |
ella/ella | ella/core/cache/utils.py | get_cached_object_or_404 | 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 | 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)) | Shortcut that will raise Http404 if there is no object matching the query
see get_cached_object for params description | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/cache/utils.py#L187-L196 |
ssalentin/plip | plip/modules/supplemental.py | tmpfile | def tmpfile(prefix, direc):
"""Returns the path to a newly created temporary file."""
return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc) | python | def tmpfile(prefix, direc):
"""Returns the path to a newly created temporary file."""
return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc) | Returns the path to a newly created temporary file. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L41-L43 |
ssalentin/plip | plip/modules/supplemental.py | extract_pdbid | 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 | 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" | Use regular expressions to get a PDB ID from a string | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L52-L59 |
ssalentin/plip | plip/modules/supplemental.py | whichrestype | 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 | 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 | Returns the residue name of an Pybel or OpenBabel atom. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L62-L65 |
ssalentin/plip | plip/modules/supplemental.py | whichresnumber | def whichresnumber(atom):
"""Returns the residue number of an Pybel or OpenBabel atom (numbering as in original PDB file)."""
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 | python | def whichresnumber(atom):
"""Returns the residue number of an Pybel or OpenBabel atom (numbering as in original PDB file)."""
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 | Returns the residue number of an Pybel or OpenBabel atom (numbering as in original PDB file). | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L68-L71 |
ssalentin/plip | plip/modules/supplemental.py | whichchain | 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 | 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 | Returns the residue number of an PyBel or OpenBabel atom. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L74-L77 |
ssalentin/plip | plip/modules/supplemental.py | euclidean3d | 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 | 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) | Faster implementation of euclidean distance for the 3D case. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L84-L89 |
ssalentin/plip | plip/modules/supplemental.py | vector | 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
"""
return None if len(p1) != len(p2) else np.array([p2[i] - p1[i] for i in range(len(p1))]) | python | 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
"""
return None if len(p1) != len(p2) else np.array([p2[i] - p1[i] for i in range(len(p1))]) | Vector from p1 to p2.
:param p1: coordinates of point p1
:param p2: coordinates of point p2
:returns : numpy array with vector coordinates | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L92-L98 |
ssalentin/plip | plip/modules/supplemental.py | vecangle | 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
"""
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 | python | 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
"""
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 | Calculate the angle between two vectors
:param v1: coordinates of vector v1
:param v2: coordinates of vector v2
:returns : angle in degree or rad | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L101-L112 |
ssalentin/plip | plip/modules/supplemental.py | normalize_vector | def normalize_vector(v):
"""Take a vector and return the normalized vector
:param v: a vector v
:returns : normalized vector v
"""
norm = np.linalg.norm(v)
return v/norm if not norm == 0 else v | python | def normalize_vector(v):
"""Take a vector and return the normalized vector
:param v: a vector v
:returns : normalized vector v
"""
norm = np.linalg.norm(v)
return v/norm if not norm == 0 else v | Take a vector and return the normalized vector
:param v: a vector v
:returns : normalized vector v | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L115-L121 |
ssalentin/plip | plip/modules/supplemental.py | centroid | 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
"""
return list(map(np.mean, (([c[0] for c in coo]), ([c[1] for c in coo]), ([c[2] for c in coo])))) | python | 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
"""
return list(map(np.mean, (([c[0] for c in coo]), ([c[1] for c in coo]), ([c[2] for c in coo])))) | Calculates the centroid from a 3D point cloud and returns the coordinates
:param coo: Array of coordinate arrays
:returns : centroid coordinates as list | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L124-L129 |
ssalentin/plip | plip/modules/supplemental.py | cluster_doubles | 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)
"""
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) | python | 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)
"""
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) | Given a list of doubles, they are clustered if they share one element
:param double_list: list of doubles
:returns : list of clusters (tuples) | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L151-L189 |
ssalentin/plip | plip/modules/supplemental.py | create_folder_if_not_exists | 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 | 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) | Creates a folder if it does not exists. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L206-L212 |
ssalentin/plip | plip/modules/supplemental.py | initialize_pymol | def initialize_pymol(options):
"""Initializes PyMOL"""
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() | python | def initialize_pymol(options):
"""Initializes PyMOL"""
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() | Initializes PyMOL | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L223-L228 |
ssalentin/plip | plip/modules/supplemental.py | start_pymol | 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 | 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') | Starts up PyMOL and sets general options. Quiet mode suppresses all PyMOL output.
Command line options can be passed as the second argument. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L231-L239 |
ssalentin/plip | plip/modules/supplemental.py | nucleotide_linkage | def nucleotide_linkage(residues):
"""Support for DNA/RNA ligands by finding missing covalent linkages to stitch DNA/RNA together."""
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 | python | def nucleotide_linkage(residues):
"""Support for DNA/RNA ligands by finding missing covalent linkages to stitch DNA/RNA together."""
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 | Support for DNA/RNA ligands by finding missing covalent linkages to stitch DNA/RNA together. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L242-L271 |
ssalentin/plip | plip/modules/supplemental.py | ring_is_planar | 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 | 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 | Given a set of ring atoms, check if the ring is sufficiently planar
to be considered aromatic | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L274-L289 |
ssalentin/plip | plip/modules/supplemental.py | classify_by_name | def classify_by_name(names):
"""Classify a (composite) ligand by the HETID(s)"""
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 | python | def classify_by_name(names):
"""Classify a (composite) ligand by the HETID(s)"""
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 | Classify a (composite) ligand by the HETID(s) | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L292-L311 |
ssalentin/plip | plip/modules/supplemental.py | sort_members_by_importance | 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."""
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 | python | 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."""
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 | 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. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L314-L323 |
ssalentin/plip | plip/modules/supplemental.py | get_isomorphisms | 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 | 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 | Get all isomorphisms of the ligand. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L326-L339 |
ssalentin/plip | plip/modules/supplemental.py | canonicalize | 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 | 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 | Get the canonical atom order for the ligand. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L342-L371 |
ssalentin/plip | plip/modules/supplemental.py | int32_to_negative | 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.
"""
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 | python | 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.
"""
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 | 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. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L374-L386 |
ssalentin/plip | plip/modules/supplemental.py | read_pdb | 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 | 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) | Reads a given PDB file and returns a Pybel Molecule. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L389-L396 |
ssalentin/plip | plip/modules/supplemental.py | read | 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 | 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') | Returns a file handler and detects gzipped files. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L399-L407 |
ssalentin/plip | plip/modules/supplemental.py | readmol | 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 | 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.') | 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. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L410-L442 |
ssalentin/plip | plip/modules/supplemental.py | colorlog | 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 | 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 | Colors messages on non-Windows systems supporting ANSI escape. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L455-L477 |
ssalentin/plip | plip/modules/supplemental.py | write_message | 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 | 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) | Writes message if verbose mode is set. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L480-L483 |
ssalentin/plip | plip/modules/supplemental.py | message | 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 | 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) | Writes messages in verbose mode | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L486-L500 |
ella/ella | ella/core/templatetags/related.py | do_related | 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 | 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) | 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 %} | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/templatetags/related.py#L68-L98 |
ella/ella | ella/core/models/publishable.py | PublishableBox | 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 | 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) | add some content type info of self.target | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/models/publishable.py#L23-L31 |
ella/ella | ella/core/models/publishable.py | ListingBox | 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 | def ListingBox(listing, *args, **kwargs):
" Delegate the boxing to the target's Box class. "
obj = listing.publishable
return obj.box_class(obj, *args, **kwargs) | Delegate the boxing to the target's Box class. | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/models/publishable.py#L225-L228 |
ella/ella | ella/core/models/publishable.py | Publishable.get_absolute_url | 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 | 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 | Get object's URL. | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/models/publishable.py#L90-L120 |
ella/ella | ella/core/models/publishable.py | Publishable.is_published | 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 | 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) | Return True if the Publishable is currently active. | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/models/publishable.py#L218-L222 |
ella/ella | ella/core/box.py | Box.resolve_params | 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 | 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 | Parse the parameters into a dict. | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/box.py#L49-L56 |
ella/ella | ella/core/box.py | Box.prepare | 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 | 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'] | Do the pre-processing - render and parse the parameters and
store them for further use in self.params. | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/box.py#L58-L85 |
ella/ella | ella/core/box.py | Box.get_context | 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 | 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,
} | Get context to render the template. | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/box.py#L87-L95 |
ella/ella | ella/core/box.py | Box.render | def render(self, context):
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 | python | def render(self, context):
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 | Cached wrapper around self._render(). | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/box.py#L97-L111 |
ella/ella | ella/core/box.py | Box._get_template_list | def _get_template_list(self):
" 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 | python | def _get_template_list(self):
" 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 | Get the hierarchy of templates belonging to the object/box_type given. | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/box.py#L121-L141 |
ella/ella | ella/core/box.py | Box._render | 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 | 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 | The main function that takes care of the rendering. | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/box.py#L143-L154 |
ella/ella | ella/core/box.py | Box.get_cache_key | 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 | 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
)) | Return a cache key constructed from the box's parameters. | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/box.py#L156-L167 |
ella/ella | ella/core/models/main.py | Category.save | def save(self, **kwargs):
"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) | python | def save(self, **kwargs):
"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) | Override save() to construct tree_path based on the category's parent. | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/models/main.py#L129-L145 |
ella/ella | ella/core/models/main.py | Category.get_absolute_url | 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 | 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 | Returns absolute URL for the category. | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/models/main.py#L169-L180 |
ella/ella | ella/core/templatetags/core.py | listing | 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 | 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) | 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 %} | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/templatetags/core.py#L50-L88 |
ella/ella | ella/core/templatetags/core.py | do_box | 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 %}
"""
bits = token.split_contents()
nodelist = parser.parse(('end' + bits[0],))
parser.delete_first_token()
return _parse_box(nodelist, bits) | python | 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 %}
"""
bits = token.split_contents()
nodelist = parser.parse(('end' + bits[0],))
parser.delete_first_token()
return _parse_box(nodelist, bits) | 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 %} | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/templatetags/core.py#L221-L296 |
ella/ella | ella/core/templatetags/core.py | do_render | 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 | 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]) | Renders a rich-text field using defined markup.
Example::
{% render some_var %} | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/templatetags/core.py#L332-L345 |
ella/ella | ella/core/templatetags/core.py | ipblur | 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 | 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) | blurs IP address | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/templatetags/core.py#L349-L355 |
ella/ella | ella/utils/installedapps.py | register | 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 | 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 | simple module registering for later usage
we don't want to import admin.py in models.py | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/utils/installedapps.py#L11-L24 |
ella/ella | ella/utils/installedapps.py | call_modules | def call_modules(auto_discover=()):
"""
this is called in project urls.py
for registering desired modules (eg.: admin.py)
"""
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) | python | def call_modules(auto_discover=()):
"""
this is called in project urls.py
for registering desired modules (eg.: admin.py)
"""
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) | this is called in project urls.py
for registering desired modules (eg.: admin.py) | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/utils/installedapps.py#L27-L45 |
ella/ella | ella/core/related_finders.py | related_by_category | 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 | 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 | Returns other Publishable objects related to ``obj`` by using the same
category principle. Returns up to ``count`` objects. | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/related_finders.py#L7-L29 |
ella/ella | ella/core/related_finders.py | directly_related | 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 | 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) | Returns objects related to ``obj`` up to ``count`` by searching
``Related`` instances for the ``obj``. | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/related_finders.py#L32-L44 |
ssalentin/plip | plip/modules/report.py | StructureReport.construct_xml_tree | 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 | 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 | Construct the basic XML tree | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L37-L73 |
ssalentin/plip | plip/modules/report.py | StructureReport.construct_txt_file | 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 | 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 | Construct the header of the txt file | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L75-L87 |
ssalentin/plip | plip/modules/report.py | StructureReport.get_bindingsite_data | 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 | 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__ | Get the additional data for the binding sites | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L89-L103 |
ssalentin/plip | plip/modules/report.py | StructureReport.write_xml | 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 | 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) | Write the XML report | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L105-L113 |
ssalentin/plip | plip/modules/report.py | StructureReport.write_txt | 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 | 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) | Write the TXT report | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L115-L124 |
ssalentin/plip | plip/modules/report.py | BindingSiteReport.write_section | def write_section(self, name, features, info, f):
"""Provides formatting for one section (e.g. hydrogen bonds)"""
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))) | python | def write_section(self, name, features, info, f):
"""Provides formatting for one section (e.g. hydrogen bonds)"""
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))) | Provides formatting for one section (e.g. hydrogen bonds) | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L275-L281 |
ssalentin/plip | plip/modules/report.py | BindingSiteReport.rst_table | 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 | 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 | Given an array, the function formats and returns and table in rST format. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L283-L322 |
ssalentin/plip | plip/modules/report.py | BindingSiteReport.generate_txt | 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 | 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 | Generates an flat text report for a single binding site | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L324-L361 |
ssalentin/plip | plip/modules/report.py | BindingSiteReport.generate_xml | def generate_xml(self):
"""Generates an XML-formatted report for a single binding site"""
report = et.Element('bindingsite')
identifiers = et.SubElement(report, 'identifiers')
longname = et.SubElement(identifiers, 'longname')
ligtype = et.SubElement(identifiers, 'ligtype')
hetid = et.SubElement(identifiers, 'hetid')
chain = et.SubElement(identifiers, 'chain')
position = et.SubElement(identifiers, 'position')
composite = et.SubElement(identifiers, 'composite')
members = et.SubElement(identifiers, 'members')
smiles = et.SubElement(identifiers, 'smiles')
inchikey = et.SubElement(identifiers, 'inchikey')
# Ligand properties. Number of (unpaired) functional atoms and rings.
lig_properties = et.SubElement(report, 'lig_properties')
num_heavy_atoms = et.SubElement(lig_properties, 'num_heavy_atoms')
num_hbd = et.SubElement(lig_properties, 'num_hbd')
num_hbd.text = str(self.ligand.num_hbd)
num_unpaired_hbd = et.SubElement(lig_properties, 'num_unpaired_hbd')
num_unpaired_hbd.text = str(self.complex.num_unpaired_hbd)
num_hba = et.SubElement(lig_properties, 'num_hba')
num_hba.text = str(self.ligand.num_hba)
num_unpaired_hba = et.SubElement(lig_properties, 'num_unpaired_hba')
num_unpaired_hba.text = str(self.complex.num_unpaired_hba)
num_hal = et.SubElement(lig_properties, 'num_hal')
num_hal.text = str(self.ligand.num_hal)
num_unpaired_hal = et.SubElement(lig_properties, 'num_unpaired_hal')
num_unpaired_hal.text = str(self.complex.num_unpaired_hal)
num_aromatic_rings = et.SubElement(lig_properties, 'num_aromatic_rings')
num_aromatic_rings.text = str(self.ligand.num_rings)
num_rot_bonds = et.SubElement(lig_properties, 'num_rotatable_bonds')
num_rot_bonds.text = str(self.ligand.num_rot_bonds)
molweight = et.SubElement(lig_properties, 'molweight')
molweight.text = str(self.ligand.molweight)
logp = et.SubElement(lig_properties, 'logp')
logp.text = str(self.ligand.logp)
ichains = et.SubElement(report, 'interacting_chains')
bsresidues = et.SubElement(report, 'bs_residues')
for i, ichain in enumerate(self.interacting_chains):
c = et.SubElement(ichains, 'interacting_chain', id=str(i + 1))
c.text = ichain
for i, bsres in enumerate(self.bs_res):
contact = 'True' if bsres in self.bs_res_interacting else 'False'
distance = '%.1f' % self.min_dist[bsres][0]
aatype = self.min_dist[bsres][1]
c = et.SubElement(bsresidues, 'bs_residue', id=str(i + 1), contact=contact, min_dist=distance, aa=aatype)
c.text = bsres
hetid.text, chain.text, position.text = self.ligand.hetid, self.ligand.chain, str(self.ligand.position)
composite.text = 'True' if len(self.lig_members) > 1 else 'False'
longname.text = self.longname
ligtype.text = self.ligtype
smiles.text = self.ligand.smiles
inchikey.text = self.ligand.inchikey
num_heavy_atoms.text = str(self.ligand.heavy_atoms) # Number of heavy atoms in ligand
for i, member in enumerate(self.lig_members):
bsid = ":".join(str(element) for element in member)
m = et.SubElement(members, 'member', id=str(i + 1))
m.text = bsid
interactions = et.SubElement(report, 'interactions')
def format_interactions(element_name, features, interaction_information):
"""Returns a formatted element with interaction information."""
interaction = et.Element(element_name)
# 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))
for j, single_contact in enumerate(interaction_information):
if not element_name == 'metal_complexes':
new_contact = et.SubElement(interaction, element_name[:-1], id=str(j + 1))
else: # Metal Complex[es]
new_contact = et.SubElement(interaction, element_name[:-2], id=str(j + 1))
for i, feature in enumerate(single_contact):
# Just assign the value unless it's an atom list, use subelements in this case
if features[i] == 'LIG_IDX_LIST':
feat = et.SubElement(new_contact, features[i].lower())
for k, atm_idx in enumerate(feature.split(',')):
idx = et.SubElement(feat, 'idx', id=str(k + 1))
idx.text = str(atm_idx)
elif features[i].endswith('COO'):
feat = et.SubElement(new_contact, features[i].lower())
xc, yc, zc = feature
xcoo = et.SubElement(feat, 'x')
xcoo.text = '%.3f' % xc
ycoo = et.SubElement(feat, 'y')
ycoo.text = '%.3f' % yc
zcoo = et.SubElement(feat, 'z')
zcoo.text = '%.3f' % zc
else:
feat = et.SubElement(new_contact, features[i].lower())
feat.text = str(feature)
return interaction
interactions.append(format_interactions('hydrophobic_interactions', self.hydrophobic_features,
self.hydrophobic_info))
interactions.append(format_interactions('hydrogen_bonds', self.hbond_features, self.hbond_info))
interactions.append(format_interactions('water_bridges', self.waterbridge_features, self.waterbridge_info))
interactions.append(format_interactions('salt_bridges', self.saltbridge_features, self.saltbridge_info))
interactions.append(format_interactions('pi_stacks', self.pistacking_features, self.pistacking_info))
interactions.append(format_interactions('pi_cation_interactions', self.pication_features, self.pication_info))
interactions.append(format_interactions('halogen_bonds', self.halogen_features, self.halogen_info))
interactions.append(format_interactions('metal_complexes', self.metal_features, self.metal_info))
# Mappings
mappings = et.SubElement(report, 'mappings')
smiles_to_pdb = et.SubElement(mappings, 'smiles_to_pdb') # SMILES numbering to PDB file numbering (atoms)
bsid = ':'.join([self.ligand.hetid, self.ligand.chain, str(self.ligand.position)])
if self.ligand.atomorder is not None:
smiles_to_pdb_map = [(key, self.ligand.Mapper.mapid(self.ligand.can_to_pdb[key],
mtype='protein', bsid=bsid)) for key in self.ligand.can_to_pdb]
smiles_to_pdb.text = ','.join([str(mapping[0])+':'+str(mapping[1]) for mapping in smiles_to_pdb_map])
else:
smiles_to_pdb.text = ''
return report | python | def generate_xml(self):
"""Generates an XML-formatted report for a single binding site"""
report = et.Element('bindingsite')
identifiers = et.SubElement(report, 'identifiers')
longname = et.SubElement(identifiers, 'longname')
ligtype = et.SubElement(identifiers, 'ligtype')
hetid = et.SubElement(identifiers, 'hetid')
chain = et.SubElement(identifiers, 'chain')
position = et.SubElement(identifiers, 'position')
composite = et.SubElement(identifiers, 'composite')
members = et.SubElement(identifiers, 'members')
smiles = et.SubElement(identifiers, 'smiles')
inchikey = et.SubElement(identifiers, 'inchikey')
# Ligand properties. Number of (unpaired) functional atoms and rings.
lig_properties = et.SubElement(report, 'lig_properties')
num_heavy_atoms = et.SubElement(lig_properties, 'num_heavy_atoms')
num_hbd = et.SubElement(lig_properties, 'num_hbd')
num_hbd.text = str(self.ligand.num_hbd)
num_unpaired_hbd = et.SubElement(lig_properties, 'num_unpaired_hbd')
num_unpaired_hbd.text = str(self.complex.num_unpaired_hbd)
num_hba = et.SubElement(lig_properties, 'num_hba')
num_hba.text = str(self.ligand.num_hba)
num_unpaired_hba = et.SubElement(lig_properties, 'num_unpaired_hba')
num_unpaired_hba.text = str(self.complex.num_unpaired_hba)
num_hal = et.SubElement(lig_properties, 'num_hal')
num_hal.text = str(self.ligand.num_hal)
num_unpaired_hal = et.SubElement(lig_properties, 'num_unpaired_hal')
num_unpaired_hal.text = str(self.complex.num_unpaired_hal)
num_aromatic_rings = et.SubElement(lig_properties, 'num_aromatic_rings')
num_aromatic_rings.text = str(self.ligand.num_rings)
num_rot_bonds = et.SubElement(lig_properties, 'num_rotatable_bonds')
num_rot_bonds.text = str(self.ligand.num_rot_bonds)
molweight = et.SubElement(lig_properties, 'molweight')
molweight.text = str(self.ligand.molweight)
logp = et.SubElement(lig_properties, 'logp')
logp.text = str(self.ligand.logp)
ichains = et.SubElement(report, 'interacting_chains')
bsresidues = et.SubElement(report, 'bs_residues')
for i, ichain in enumerate(self.interacting_chains):
c = et.SubElement(ichains, 'interacting_chain', id=str(i + 1))
c.text = ichain
for i, bsres in enumerate(self.bs_res):
contact = 'True' if bsres in self.bs_res_interacting else 'False'
distance = '%.1f' % self.min_dist[bsres][0]
aatype = self.min_dist[bsres][1]
c = et.SubElement(bsresidues, 'bs_residue', id=str(i + 1), contact=contact, min_dist=distance, aa=aatype)
c.text = bsres
hetid.text, chain.text, position.text = self.ligand.hetid, self.ligand.chain, str(self.ligand.position)
composite.text = 'True' if len(self.lig_members) > 1 else 'False'
longname.text = self.longname
ligtype.text = self.ligtype
smiles.text = self.ligand.smiles
inchikey.text = self.ligand.inchikey
num_heavy_atoms.text = str(self.ligand.heavy_atoms) # Number of heavy atoms in ligand
for i, member in enumerate(self.lig_members):
bsid = ":".join(str(element) for element in member)
m = et.SubElement(members, 'member', id=str(i + 1))
m.text = bsid
interactions = et.SubElement(report, 'interactions')
def format_interactions(element_name, features, interaction_information):
"""Returns a formatted element with interaction information."""
interaction = et.Element(element_name)
# 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))
for j, single_contact in enumerate(interaction_information):
if not element_name == 'metal_complexes':
new_contact = et.SubElement(interaction, element_name[:-1], id=str(j + 1))
else: # Metal Complex[es]
new_contact = et.SubElement(interaction, element_name[:-2], id=str(j + 1))
for i, feature in enumerate(single_contact):
# Just assign the value unless it's an atom list, use subelements in this case
if features[i] == 'LIG_IDX_LIST':
feat = et.SubElement(new_contact, features[i].lower())
for k, atm_idx in enumerate(feature.split(',')):
idx = et.SubElement(feat, 'idx', id=str(k + 1))
idx.text = str(atm_idx)
elif features[i].endswith('COO'):
feat = et.SubElement(new_contact, features[i].lower())
xc, yc, zc = feature
xcoo = et.SubElement(feat, 'x')
xcoo.text = '%.3f' % xc
ycoo = et.SubElement(feat, 'y')
ycoo.text = '%.3f' % yc
zcoo = et.SubElement(feat, 'z')
zcoo.text = '%.3f' % zc
else:
feat = et.SubElement(new_contact, features[i].lower())
feat.text = str(feature)
return interaction
interactions.append(format_interactions('hydrophobic_interactions', self.hydrophobic_features,
self.hydrophobic_info))
interactions.append(format_interactions('hydrogen_bonds', self.hbond_features, self.hbond_info))
interactions.append(format_interactions('water_bridges', self.waterbridge_features, self.waterbridge_info))
interactions.append(format_interactions('salt_bridges', self.saltbridge_features, self.saltbridge_info))
interactions.append(format_interactions('pi_stacks', self.pistacking_features, self.pistacking_info))
interactions.append(format_interactions('pi_cation_interactions', self.pication_features, self.pication_info))
interactions.append(format_interactions('halogen_bonds', self.halogen_features, self.halogen_info))
interactions.append(format_interactions('metal_complexes', self.metal_features, self.metal_info))
# Mappings
mappings = et.SubElement(report, 'mappings')
smiles_to_pdb = et.SubElement(mappings, 'smiles_to_pdb') # SMILES numbering to PDB file numbering (atoms)
bsid = ':'.join([self.ligand.hetid, self.ligand.chain, str(self.ligand.position)])
if self.ligand.atomorder is not None:
smiles_to_pdb_map = [(key, self.ligand.Mapper.mapid(self.ligand.can_to_pdb[key],
mtype='protein', bsid=bsid)) for key in self.ligand.can_to_pdb]
smiles_to_pdb.text = ','.join([str(mapping[0])+':'+str(mapping[1]) for mapping in smiles_to_pdb_map])
else:
smiles_to_pdb.text = ''
return report | Generates an XML-formatted report for a single binding site | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L363-L477 |
ssalentin/plip | plip/modules/mp.py | pool_args | 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 | 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)) | Return a single iterator of n elements of lists of length 3, given a sequence of len n. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/mp.py#L30-L32 |
ssalentin/plip | plip/modules/mp.py | parallel_fn | 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 | 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) | 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. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/mp.py#L35-L56 |
ssalentin/plip | plip/modules/preparation.py | PDBParser.parse_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
"""
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 | python | 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
"""
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 | 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 | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L43-L117 |
ssalentin/plip | plip/modules/preparation.py | PDBParser.fix_pdbline | def fix_pdbline(self, pdbline, lastnum):
"""Fix a PDB line if information is missing."""
pdbqt_conversion = {
"HD": "H", "HS": "H", "NA": "N",
"NS": "N", "OA": "O", "OS": "O", "SA": "S"}
fixed = False
newnum = 0
forbidden_characters = "[^a-zA-Z0-9_]"
pdbline = pdbline.strip('\n')
# Some MD / Docking tools produce empty lines, leading to segfaults
if len(pdbline.strip()) == 0:
self.num_fixed_lines += 1
return None, lastnum
if len(pdbline) > 100: # Should be 80 long
self.num_fixed_lines += 1
return None, lastnum
# TER Entries also have continuing numbering, consider them as well
if pdbline.startswith('TER'):
newnum = lastnum + 1
if pdbline.startswith('ATOM'):
newnum = lastnum + 1
currentnum = int(pdbline[6:11])
resnum = pdbline[22:27].strip()
resname = pdbline[17:21].strip()
# Invalid residue number
try:
int(resnum)
except ValueError:
pdbline = pdbline[:22] + ' 0 ' + pdbline[27:]
fixed = True
# Invalid characters in residue name
if re.match(forbidden_characters, resname.strip()):
pdbline = pdbline[:17] + 'UNK ' + pdbline[21:]
fixed = True
if lastnum + 1 != currentnum:
pdbline = pdbline[:6] + (5 - len(str(newnum))) * ' ' + str(newnum) + ' ' + pdbline[12:]
fixed = True
# No chain assigned
if pdbline[21] == ' ':
pdbline = pdbline[:21] + 'A' + pdbline[22:]
fixed = True
if pdbline.endswith('H'):
self.num_fixed_lines += 1
return None, lastnum
# Sometimes, converted PDB structures contain PDBQT atom types. Fix that.
for pdbqttype in pdbqt_conversion:
if pdbline.strip().endswith(pdbqttype):
pdbline = pdbline.strip()[:-2] + ' ' + pdbqt_conversion[pdbqttype] + '\n'
self.num_fixed_lines += 1
if pdbline.startswith('HETATM'):
newnum = lastnum + 1
try:
currentnum = int(pdbline[6:11])
except ValueError:
currentnum = None
write_message("Invalid HETATM entry: %s\n" % pdbline, mtype='debug')
if lastnum + 1 != currentnum:
pdbline = pdbline[:6] + (5 - len(str(newnum))) * ' ' + str(newnum) + ' ' + pdbline[12:]
fixed = True
# No chain assigned or number assigned as chain
if pdbline[21] == ' ':
pdbline = pdbline[:21] + 'Z' + pdbline[22:]
fixed = True
# No residue number assigned
if pdbline[23:26] == ' ':
pdbline = pdbline[:23] + '999' + pdbline[26:]
fixed = True
# Non-standard Ligand Names
ligname = pdbline[17:21].strip()
if len(ligname) > 3:
pdbline = pdbline[:17] + ligname[:3] + ' ' + pdbline[21:]
fixed = True
if re.match(forbidden_characters, ligname.strip()):
pdbline = pdbline[:17] + 'LIG ' + pdbline[21:]
fixed = True
if len(ligname.strip()) == 0:
pdbline = pdbline[:17] + 'LIG ' + pdbline[21:]
fixed = True
if pdbline.endswith('H'):
self.num_fixed_lines += 1
return None, lastnum
# Sometimes, converted PDB structures contain PDBQT atom types. Fix that.
for pdbqttype in pdbqt_conversion:
if pdbline.strip().endswith(pdbqttype):
pdbline = pdbline.strip()[:-2] + ' ' + pdbqt_conversion[pdbqttype] + ' '
self.num_fixed_lines += 1
self.num_fixed_lines += 1 if fixed else 0
return pdbline + '\n', max(newnum, lastnum) | python | def fix_pdbline(self, pdbline, lastnum):
"""Fix a PDB line if information is missing."""
pdbqt_conversion = {
"HD": "H", "HS": "H", "NA": "N",
"NS": "N", "OA": "O", "OS": "O", "SA": "S"}
fixed = False
newnum = 0
forbidden_characters = "[^a-zA-Z0-9_]"
pdbline = pdbline.strip('\n')
# Some MD / Docking tools produce empty lines, leading to segfaults
if len(pdbline.strip()) == 0:
self.num_fixed_lines += 1
return None, lastnum
if len(pdbline) > 100: # Should be 80 long
self.num_fixed_lines += 1
return None, lastnum
# TER Entries also have continuing numbering, consider them as well
if pdbline.startswith('TER'):
newnum = lastnum + 1
if pdbline.startswith('ATOM'):
newnum = lastnum + 1
currentnum = int(pdbline[6:11])
resnum = pdbline[22:27].strip()
resname = pdbline[17:21].strip()
# Invalid residue number
try:
int(resnum)
except ValueError:
pdbline = pdbline[:22] + ' 0 ' + pdbline[27:]
fixed = True
# Invalid characters in residue name
if re.match(forbidden_characters, resname.strip()):
pdbline = pdbline[:17] + 'UNK ' + pdbline[21:]
fixed = True
if lastnum + 1 != currentnum:
pdbline = pdbline[:6] + (5 - len(str(newnum))) * ' ' + str(newnum) + ' ' + pdbline[12:]
fixed = True
# No chain assigned
if pdbline[21] == ' ':
pdbline = pdbline[:21] + 'A' + pdbline[22:]
fixed = True
if pdbline.endswith('H'):
self.num_fixed_lines += 1
return None, lastnum
# Sometimes, converted PDB structures contain PDBQT atom types. Fix that.
for pdbqttype in pdbqt_conversion:
if pdbline.strip().endswith(pdbqttype):
pdbline = pdbline.strip()[:-2] + ' ' + pdbqt_conversion[pdbqttype] + '\n'
self.num_fixed_lines += 1
if pdbline.startswith('HETATM'):
newnum = lastnum + 1
try:
currentnum = int(pdbline[6:11])
except ValueError:
currentnum = None
write_message("Invalid HETATM entry: %s\n" % pdbline, mtype='debug')
if lastnum + 1 != currentnum:
pdbline = pdbline[:6] + (5 - len(str(newnum))) * ' ' + str(newnum) + ' ' + pdbline[12:]
fixed = True
# No chain assigned or number assigned as chain
if pdbline[21] == ' ':
pdbline = pdbline[:21] + 'Z' + pdbline[22:]
fixed = True
# No residue number assigned
if pdbline[23:26] == ' ':
pdbline = pdbline[:23] + '999' + pdbline[26:]
fixed = True
# Non-standard Ligand Names
ligname = pdbline[17:21].strip()
if len(ligname) > 3:
pdbline = pdbline[:17] + ligname[:3] + ' ' + pdbline[21:]
fixed = True
if re.match(forbidden_characters, ligname.strip()):
pdbline = pdbline[:17] + 'LIG ' + pdbline[21:]
fixed = True
if len(ligname.strip()) == 0:
pdbline = pdbline[:17] + 'LIG ' + pdbline[21:]
fixed = True
if pdbline.endswith('H'):
self.num_fixed_lines += 1
return None, lastnum
# Sometimes, converted PDB structures contain PDBQT atom types. Fix that.
for pdbqttype in pdbqt_conversion:
if pdbline.strip().endswith(pdbqttype):
pdbline = pdbline.strip()[:-2] + ' ' + pdbqt_conversion[pdbqttype] + ' '
self.num_fixed_lines += 1
self.num_fixed_lines += 1 if fixed else 0
return pdbline + '\n', max(newnum, lastnum) | Fix a PDB line if information is missing. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L119-L206 |
ssalentin/plip | plip/modules/preparation.py | PDBParser.get_linkage | def get_linkage(self, line):
"""Get the linkage information from a LINK entry PDB line."""
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) | python | def get_linkage(self, line):
"""Get the linkage information from a LINK entry PDB line."""
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) | Get the linkage information from a LINK entry PDB line. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L208-L213 |
ssalentin/plip | plip/modules/preparation.py | LigandFinder.getpeptides | 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
"""
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 | python | 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
"""
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 | 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 | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L229-L241 |
ssalentin/plip | plip/modules/preparation.py | LigandFinder.getligs | def getligs(self):
"""Get all ligands from a PDB file and prepare them for analysis.
Returns all non-empty ligands.
"""
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] | python | def getligs(self):
"""Get all ligands from a PDB file and prepare them for analysis.
Returns all non-empty ligands.
"""
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] | Get all ligands from a PDB file and prepare them for analysis.
Returns all non-empty ligands. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L243-L284 |
ssalentin/plip | plip/modules/preparation.py | LigandFinder.extract_ligand | def extract_ligand(self, kmer):
"""Extract the ligand by copying atoms and bonds and assign all information necessary for later steps."""
data = namedtuple('ligand', 'mol hetid chain position water members longname type atomorder can_to_pdb')
members = [(res.GetName(), res.GetChain(), int32_to_negative(res.GetNum())) for res in kmer]
members = sort_members_by_importance(members)
rname, rchain, rnum = members[0]
write_message("Finalizing extraction for ligand %s:%s:%s with %i elements\n" %
(rname, rchain, rnum, len(kmer)), mtype='debug')
names = [x[0] for x in members]
longname = '-'.join([x[0] for x in members])
if config.PEPTIDES != []:
ligtype = 'PEPTIDE'
elif config.INTRA is not None:
ligtype = 'INTRA'
else:
# Classify a ligand by its HETID(s)
ligtype = classify_by_name(names)
write_message("Ligand classified as {}\n".format(ligtype), mtype='debug')
hetatoms = set()
for obresidue in kmer:
hetatoms_res = set([(obatom.GetIdx(), obatom) for obatom in pybel.ob.OBResidueAtomIter(obresidue)
if obatom.GetAtomicNum() != 1])
if not config.ALTLOC:
# Remove alternative conformations (standard -> True)
hetatoms_res = set([atm for atm in hetatoms_res
if not self.mapper.mapid(atm[0], mtype='protein',
to='internal') in self.altconformations])
hetatoms.update(hetatoms_res)
write_message("Hetero atoms determined (n={})\n".format(len(hetatoms)), mtype='debug')
hetatoms = dict(hetatoms) # make it a dict with idx as key and OBAtom as value
lig = pybel.ob.OBMol() # new ligand mol
neighbours = dict()
for obatom in hetatoms.values(): # iterate over atom objects
idx = obatom.GetIdx()
lig.AddAtom(obatom)
# ids of all neighbours of obatom
neighbours[idx] = set([neighbour_atom.GetIdx() for neighbour_atom
in pybel.ob.OBAtomAtomIter(obatom)]) & set(hetatoms.keys())
write_message("Atom neighbours mapped\n", mtype='debug')
##############################################################
# map the old atom idx of OBMol to the new idx of the ligand #
##############################################################
newidx = dict(zip(hetatoms.keys(), [obatom.GetIdx() for obatom in pybel.ob.OBMolAtomIter(lig)]))
mapold = dict(zip(newidx.values(), newidx))
# copy the bonds
for obatom in hetatoms:
for neighbour_atom in neighbours[obatom]:
bond = hetatoms[obatom].GetBond(hetatoms[neighbour_atom])
lig.AddBond(newidx[obatom], newidx[neighbour_atom], bond.GetBondOrder())
lig = pybel.Molecule(lig)
# For kmers, the representative ids are chosen (first residue of kmer)
lig.data.update({'Name': rname, 'Chain': rchain, 'ResNr': rnum})
# Check if a negative residue number is represented as a 32 bit integer
if rnum > 10 ** 5:
rnum = int32_to_negative(rnum)
lig.title = ':'.join((rname, rchain, str(rnum)))
self.mapper.ligandmaps[lig.title] = mapold
write_message("Renumerated molecule generated\n", mtype='debug')
if not config.NOPDBCANMAP:
atomorder = canonicalize(lig)
else:
atomorder = None
can_to_pdb = {}
if atomorder is not None:
can_to_pdb = {atomorder[key-1]: mapold[key] for key in mapold}
ligand = data(mol=lig, hetid=rname, chain=rchain, position=rnum, water=self.water,
members=members, longname=longname, type=ligtype, atomorder=atomorder,
can_to_pdb=can_to_pdb)
return ligand | python | def extract_ligand(self, kmer):
"""Extract the ligand by copying atoms and bonds and assign all information necessary for later steps."""
data = namedtuple('ligand', 'mol hetid chain position water members longname type atomorder can_to_pdb')
members = [(res.GetName(), res.GetChain(), int32_to_negative(res.GetNum())) for res in kmer]
members = sort_members_by_importance(members)
rname, rchain, rnum = members[0]
write_message("Finalizing extraction for ligand %s:%s:%s with %i elements\n" %
(rname, rchain, rnum, len(kmer)), mtype='debug')
names = [x[0] for x in members]
longname = '-'.join([x[0] for x in members])
if config.PEPTIDES != []:
ligtype = 'PEPTIDE'
elif config.INTRA is not None:
ligtype = 'INTRA'
else:
# Classify a ligand by its HETID(s)
ligtype = classify_by_name(names)
write_message("Ligand classified as {}\n".format(ligtype), mtype='debug')
hetatoms = set()
for obresidue in kmer:
hetatoms_res = set([(obatom.GetIdx(), obatom) for obatom in pybel.ob.OBResidueAtomIter(obresidue)
if obatom.GetAtomicNum() != 1])
if not config.ALTLOC:
# Remove alternative conformations (standard -> True)
hetatoms_res = set([atm for atm in hetatoms_res
if not self.mapper.mapid(atm[0], mtype='protein',
to='internal') in self.altconformations])
hetatoms.update(hetatoms_res)
write_message("Hetero atoms determined (n={})\n".format(len(hetatoms)), mtype='debug')
hetatoms = dict(hetatoms) # make it a dict with idx as key and OBAtom as value
lig = pybel.ob.OBMol() # new ligand mol
neighbours = dict()
for obatom in hetatoms.values(): # iterate over atom objects
idx = obatom.GetIdx()
lig.AddAtom(obatom)
# ids of all neighbours of obatom
neighbours[idx] = set([neighbour_atom.GetIdx() for neighbour_atom
in pybel.ob.OBAtomAtomIter(obatom)]) & set(hetatoms.keys())
write_message("Atom neighbours mapped\n", mtype='debug')
##############################################################
# map the old atom idx of OBMol to the new idx of the ligand #
##############################################################
newidx = dict(zip(hetatoms.keys(), [obatom.GetIdx() for obatom in pybel.ob.OBMolAtomIter(lig)]))
mapold = dict(zip(newidx.values(), newidx))
# copy the bonds
for obatom in hetatoms:
for neighbour_atom in neighbours[obatom]:
bond = hetatoms[obatom].GetBond(hetatoms[neighbour_atom])
lig.AddBond(newidx[obatom], newidx[neighbour_atom], bond.GetBondOrder())
lig = pybel.Molecule(lig)
# For kmers, the representative ids are chosen (first residue of kmer)
lig.data.update({'Name': rname, 'Chain': rchain, 'ResNr': rnum})
# Check if a negative residue number is represented as a 32 bit integer
if rnum > 10 ** 5:
rnum = int32_to_negative(rnum)
lig.title = ':'.join((rname, rchain, str(rnum)))
self.mapper.ligandmaps[lig.title] = mapold
write_message("Renumerated molecule generated\n", mtype='debug')
if not config.NOPDBCANMAP:
atomorder = canonicalize(lig)
else:
atomorder = None
can_to_pdb = {}
if atomorder is not None:
can_to_pdb = {atomorder[key-1]: mapold[key] for key in mapold}
ligand = data(mol=lig, hetid=rname, chain=rchain, position=rnum, water=self.water,
members=members, longname=longname, type=ligtype, atomorder=atomorder,
can_to_pdb=can_to_pdb)
return ligand | Extract the ligand by copying atoms and bonds and assign all information necessary for later steps. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L286-L367 |
ssalentin/plip | plip/modules/preparation.py | LigandFinder.is_het_residue | def is_het_residue(self, obres):
"""Given an OBResidue, determines if the residue is indeed a possible ligand
in the PDB file"""
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 | python | def is_het_residue(self, obres):
"""Given an OBResidue, determines if the residue is indeed a possible ligand
in the PDB file"""
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 | Given an OBResidue, determines if the residue is indeed a possible ligand
in the PDB file | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L369-L386 |
ssalentin/plip | plip/modules/preparation.py | LigandFinder.filter_for_ligands | def filter_for_ligands(self):
"""Given an OpenBabel Molecule, get all ligands, their names, and water"""
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 | python | def filter_for_ligands(self):
"""Given an OpenBabel Molecule, get all ligands, their names, and water"""
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 | Given an OpenBabel Molecule, get all ligands, their names, and water | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L388-L418 |
ssalentin/plip | plip/modules/preparation.py | LigandFinder.identify_kmers | def identify_kmers(self, residues):
"""Using the covalent linkage information, find out which fragments/subunits form a ligand."""
# 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 | python | def identify_kmers(self, residues):
"""Using the covalent linkage information, find out which fragments/subunits form a ligand."""
# 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 | Using the covalent linkage information, find out which fragments/subunits form a ligand. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L420-L447 |
ssalentin/plip | plip/modules/preparation.py | Mapper.id_to_atom | 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.
"""
mapped_idx = self.mapid(idx, 'reversed')
return pybel.Atom(self.original_structure.GetAtom(mapped_idx)) | python | 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.
"""
mapped_idx = self.mapid(idx, 'reversed')
return pybel.Atom(self.original_structure.GetAtom(mapped_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. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L469-L474 |
ssalentin/plip | plip/modules/preparation.py | Mol.hydrophobic_atoms | def hydrophobic_atoms(self, all_atoms):
"""Select all carbon atoms which have only carbons and/or hydrogens as direct neighbors."""
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 | python | def hydrophobic_atoms(self, all_atoms):
"""Select all carbon atoms which have only carbons and/or hydrogens as direct neighbors."""
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 | Select all carbon atoms which have only carbons and/or hydrogens as direct neighbors. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L489-L501 |
ssalentin/plip | plip/modules/preparation.py | Mol.find_hba | def find_hba(self, all_atoms):
"""Find all possible hydrogen bond acceptors"""
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 | python | def find_hba(self, all_atoms):
"""Find all possible hydrogen bond acceptors"""
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 | Find all possible hydrogen bond acceptors | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L503-L512 |
ssalentin/plip | plip/modules/preparation.py | Mol.find_hbd | def find_hbd(self, all_atoms, hydroph_atoms):
"""Find all possible strong and weak hydrogen bonds donors (all hydrophobic C-H pairings)"""
donor_pairs = []
data = namedtuple('hbonddonor', 'd d_orig_atom d_orig_idx h type')
for donor in [a for a in all_atoms if a.OBAtom.IsHbondDonor() and a.idx not in self.altconf]:
in_ring = False
if not in_ring:
for adj_atom in [a for a in pybel.ob.OBAtomAtomIter(donor.OBAtom) if a.IsHbondDonorH()]:
d_orig_idx = self.Mapper.mapid(donor.idx, mtype=self.mtype, bsid=self.bsid)
d_orig_atom = self.Mapper.id_to_atom(d_orig_idx)
donor_pairs.append(data(d=donor, d_orig_atom=d_orig_atom, d_orig_idx=d_orig_idx,
h=pybel.Atom(adj_atom), type='regular'))
for carbon in hydroph_atoms:
for adj_atom in [a for a in pybel.ob.OBAtomAtomIter(carbon.atom.OBAtom) if a.GetAtomicNum() == 1]:
d_orig_idx = self.Mapper.mapid(carbon.atom.idx, mtype=self.mtype, bsid=self.bsid)
d_orig_atom = self.Mapper.id_to_atom(d_orig_idx)
donor_pairs.append(data(d=carbon, d_orig_atom=d_orig_atom,
d_orig_idx=d_orig_idx, h=pybel.Atom(adj_atom), type='weak'))
return donor_pairs | python | def find_hbd(self, all_atoms, hydroph_atoms):
"""Find all possible strong and weak hydrogen bonds donors (all hydrophobic C-H pairings)"""
donor_pairs = []
data = namedtuple('hbonddonor', 'd d_orig_atom d_orig_idx h type')
for donor in [a for a in all_atoms if a.OBAtom.IsHbondDonor() and a.idx not in self.altconf]:
in_ring = False
if not in_ring:
for adj_atom in [a for a in pybel.ob.OBAtomAtomIter(donor.OBAtom) if a.IsHbondDonorH()]:
d_orig_idx = self.Mapper.mapid(donor.idx, mtype=self.mtype, bsid=self.bsid)
d_orig_atom = self.Mapper.id_to_atom(d_orig_idx)
donor_pairs.append(data(d=donor, d_orig_atom=d_orig_atom, d_orig_idx=d_orig_idx,
h=pybel.Atom(adj_atom), type='regular'))
for carbon in hydroph_atoms:
for adj_atom in [a for a in pybel.ob.OBAtomAtomIter(carbon.atom.OBAtom) if a.GetAtomicNum() == 1]:
d_orig_idx = self.Mapper.mapid(carbon.atom.idx, mtype=self.mtype, bsid=self.bsid)
d_orig_atom = self.Mapper.id_to_atom(d_orig_idx)
donor_pairs.append(data(d=carbon, d_orig_atom=d_orig_atom,
d_orig_idx=d_orig_idx, h=pybel.Atom(adj_atom), type='weak'))
return donor_pairs | Find all possible strong and weak hydrogen bonds donors (all hydrophobic C-H pairings) | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L514-L532 |
ssalentin/plip | plip/modules/preparation.py | Mol.find_rings | def find_rings(self, mol, all_atoms):
"""Find rings and return only aromatic.
Rings have to be sufficiently planar OR be detected by OpenBabel as aromatic."""
data = namedtuple('aromatic_ring', 'atoms orig_atoms atoms_orig_idx normal obj center type')
rings = []
aromatic_amino = ['TYR', 'TRP', 'HIS', 'PHE']
ring_candidates = mol.OBMol.GetSSSR()
write_message("Number of aromatic ring candidates: %i\n" % len(ring_candidates), mtype="debug")
# Check here first for ligand rings not being detected as aromatic by Babel and check for planarity
for ring in ring_candidates:
r_atoms = [a for a in all_atoms if ring.IsMember(a.OBAtom)]
if 4 < len(r_atoms) <= 6:
res = list(set([whichrestype(a) for a in r_atoms]))
if ring.IsAromatic() or res[0] in aromatic_amino or ring_is_planar(ring, r_atoms):
# Causes segfault with OpenBabel 2.3.2, so deactivated
# typ = ring.GetType() if not ring.GetType() == '' else 'unknown'
# Alternative typing
typ = '%s-membered' % len(r_atoms)
ring_atms = [r_atoms[a].coords for a in [0, 2, 4]] # Probe atoms for normals, assuming planarity
ringv1 = vector(ring_atms[0], ring_atms[1])
ringv2 = vector(ring_atms[2], ring_atms[0])
atoms_orig_idx = [self.Mapper.mapid(r_atom.idx, mtype=self.mtype,
bsid=self.bsid) for r_atom in r_atoms]
orig_atoms = [self.Mapper.id_to_atom(idx) for idx in atoms_orig_idx]
rings.append(data(atoms=r_atoms,
orig_atoms=orig_atoms,
atoms_orig_idx=atoms_orig_idx,
normal=normalize_vector(np.cross(ringv1, ringv2)),
obj=ring,
center=centroid([ra.coords for ra in r_atoms]),
type=typ))
return rings | python | def find_rings(self, mol, all_atoms):
"""Find rings and return only aromatic.
Rings have to be sufficiently planar OR be detected by OpenBabel as aromatic."""
data = namedtuple('aromatic_ring', 'atoms orig_atoms atoms_orig_idx normal obj center type')
rings = []
aromatic_amino = ['TYR', 'TRP', 'HIS', 'PHE']
ring_candidates = mol.OBMol.GetSSSR()
write_message("Number of aromatic ring candidates: %i\n" % len(ring_candidates), mtype="debug")
# Check here first for ligand rings not being detected as aromatic by Babel and check for planarity
for ring in ring_candidates:
r_atoms = [a for a in all_atoms if ring.IsMember(a.OBAtom)]
if 4 < len(r_atoms) <= 6:
res = list(set([whichrestype(a) for a in r_atoms]))
if ring.IsAromatic() or res[0] in aromatic_amino or ring_is_planar(ring, r_atoms):
# Causes segfault with OpenBabel 2.3.2, so deactivated
# typ = ring.GetType() if not ring.GetType() == '' else 'unknown'
# Alternative typing
typ = '%s-membered' % len(r_atoms)
ring_atms = [r_atoms[a].coords for a in [0, 2, 4]] # Probe atoms for normals, assuming planarity
ringv1 = vector(ring_atms[0], ring_atms[1])
ringv2 = vector(ring_atms[2], ring_atms[0])
atoms_orig_idx = [self.Mapper.mapid(r_atom.idx, mtype=self.mtype,
bsid=self.bsid) for r_atom in r_atoms]
orig_atoms = [self.Mapper.id_to_atom(idx) for idx in atoms_orig_idx]
rings.append(data(atoms=r_atoms,
orig_atoms=orig_atoms,
atoms_orig_idx=atoms_orig_idx,
normal=normalize_vector(np.cross(ringv1, ringv2)),
obj=ring,
center=centroid([ra.coords for ra in r_atoms]),
type=typ))
return rings | Find rings and return only aromatic.
Rings have to be sufficiently planar OR be detected by OpenBabel as aromatic. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L534-L565 |
ssalentin/plip | plip/modules/preparation.py | PLInteraction.find_unpaired_ligand | def find_unpaired_ligand(self):
"""Identify unpaired functional in groups in ligands, involving H-Bond donors, acceptors, halogen bond donors.
"""
unpaired_hba, unpaired_hbd, unpaired_hal = [], [], []
# Unpaired hydrogen bond acceptors/donors in ligand (not used for hydrogen bonds/water, salt bridges/mcomplex)
involved_atoms = [hbond.a.idx for hbond in self.hbonds_pdon] + [hbond.d.idx for hbond in self.hbonds_ldon]
[[involved_atoms.append(atom.idx) for atom in sb.negative.atoms] for sb in self.saltbridge_lneg]
[[involved_atoms.append(atom.idx) for atom in sb.positive.atoms] for sb in self.saltbridge_pneg]
[involved_atoms.append(wb.a.idx) for wb in self.water_bridges if wb.protisdon]
[involved_atoms.append(wb.d.idx) for wb in self.water_bridges if not wb.protisdon]
[involved_atoms.append(mcomplex.target.atom.idx) for mcomplex in self.metal_complexes
if mcomplex.location == 'ligand']
for atom in [hba.a for hba in self.ligand.get_hba()]:
if atom.idx not in involved_atoms:
unpaired_hba.append(atom)
for atom in [hbd.d for hbd in self.ligand.get_hbd()]:
if atom.idx not in involved_atoms:
unpaired_hbd.append(atom)
# unpaired halogen bond donors in ligand (not used for the previous + halogen bonds)
[involved_atoms.append(atom.don.x.idx) for atom in self.halogen_bonds]
for atom in [haldon.x for haldon in self.ligand.halogenbond_don]:
if atom.idx not in involved_atoms:
unpaired_hal.append(atom)
return unpaired_hba, unpaired_hbd, unpaired_hal | python | def find_unpaired_ligand(self):
"""Identify unpaired functional in groups in ligands, involving H-Bond donors, acceptors, halogen bond donors.
"""
unpaired_hba, unpaired_hbd, unpaired_hal = [], [], []
# Unpaired hydrogen bond acceptors/donors in ligand (not used for hydrogen bonds/water, salt bridges/mcomplex)
involved_atoms = [hbond.a.idx for hbond in self.hbonds_pdon] + [hbond.d.idx for hbond in self.hbonds_ldon]
[[involved_atoms.append(atom.idx) for atom in sb.negative.atoms] for sb in self.saltbridge_lneg]
[[involved_atoms.append(atom.idx) for atom in sb.positive.atoms] for sb in self.saltbridge_pneg]
[involved_atoms.append(wb.a.idx) for wb in self.water_bridges if wb.protisdon]
[involved_atoms.append(wb.d.idx) for wb in self.water_bridges if not wb.protisdon]
[involved_atoms.append(mcomplex.target.atom.idx) for mcomplex in self.metal_complexes
if mcomplex.location == 'ligand']
for atom in [hba.a for hba in self.ligand.get_hba()]:
if atom.idx not in involved_atoms:
unpaired_hba.append(atom)
for atom in [hbd.d for hbd in self.ligand.get_hbd()]:
if atom.idx not in involved_atoms:
unpaired_hbd.append(atom)
# unpaired halogen bond donors in ligand (not used for the previous + halogen bonds)
[involved_atoms.append(atom.don.x.idx) for atom in self.halogen_bonds]
for atom in [haldon.x for haldon in self.ligand.halogenbond_don]:
if atom.idx not in involved_atoms:
unpaired_hal.append(atom)
return unpaired_hba, unpaired_hbd, unpaired_hal | Identify unpaired functional in groups in ligands, involving H-Bond donors, acceptors, halogen bond donors. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L683-L708 |
ssalentin/plip | plip/modules/preparation.py | PLInteraction.refine_hydrophobic | def refine_hydrophobic(self, all_h, pistacks):
"""Apply several rules to reduce the number of hydrophobic interactions."""
sel = {}
# 1. Rings interacting via stacking can't have additional hydrophobic contacts between each other.
for pistack, h in itertools.product(pistacks, all_h):
h1, h2 = h.bsatom.idx, h.ligatom.idx
brs, lrs = [p1.idx for p1 in pistack.proteinring.atoms], [p2.idx for p2 in pistack.ligandring.atoms]
if h1 in brs and h2 in lrs:
sel[(h1, h2)] = "EXCLUDE"
hydroph = [h for h in all_h if not (h.bsatom.idx, h.ligatom.idx) in sel]
sel2 = {}
# 2. If a ligand atom interacts with several binding site atoms in the same residue,
# keep only the one with the closest distance
for h in hydroph:
if not (h.ligatom.idx, h.resnr) in sel2:
sel2[(h.ligatom.idx, h.resnr)] = h
else:
if sel2[(h.ligatom.idx, h.resnr)].distance > h.distance:
sel2[(h.ligatom.idx, h.resnr)] = h
hydroph = [h for h in sel2.values()]
hydroph_final = []
bsclust = {}
# 3. If a protein atom interacts with several neighboring ligand atoms, just keep the one with the closest dist
for h in hydroph:
if h.bsatom.idx not in bsclust:
bsclust[h.bsatom.idx] = [h, ]
else:
bsclust[h.bsatom.idx].append(h)
idx_to_h = {}
for bs in [a for a in bsclust if len(bsclust[a]) == 1]:
hydroph_final.append(bsclust[bs][0])
# A list of tuples with the idx of an atom and one of its neighbours is created
for bs in [a for a in bsclust if not len(bsclust[a]) == 1]:
tuples = []
all_idx = [i.ligatom.idx for i in bsclust[bs]]
for b in bsclust[bs]:
idx = b.ligatom.idx
neigh = [na for na in pybel.ob.OBAtomAtomIter(b.ligatom.OBAtom)]
for n in neigh:
n_idx = n.GetIdx()
if n_idx in all_idx:
if n_idx < idx:
tuples.append((n_idx, idx))
else:
tuples.append((idx, n_idx))
idx_to_h[idx] = b
tuples = list(set(tuples))
tuples = sorted(tuples, key=itemgetter(1))
clusters = cluster_doubles(tuples) # Cluster connected atoms (i.e. find hydrophobic patches)
for cluster in clusters:
min_dist = float('inf')
min_h = None
for atm_idx in cluster:
h = idx_to_h[atm_idx]
if h.distance < min_dist:
min_dist = h.distance
min_h = h
hydroph_final.append(min_h)
before, reduced = len(all_h), len(hydroph_final)
if not before == 0 and not before == reduced:
write_message('Reduced number of hydrophobic contacts from %i to %i.\n' % (before, reduced), indent=True)
return hydroph_final | python | def refine_hydrophobic(self, all_h, pistacks):
"""Apply several rules to reduce the number of hydrophobic interactions."""
sel = {}
# 1. Rings interacting via stacking can't have additional hydrophobic contacts between each other.
for pistack, h in itertools.product(pistacks, all_h):
h1, h2 = h.bsatom.idx, h.ligatom.idx
brs, lrs = [p1.idx for p1 in pistack.proteinring.atoms], [p2.idx for p2 in pistack.ligandring.atoms]
if h1 in brs and h2 in lrs:
sel[(h1, h2)] = "EXCLUDE"
hydroph = [h for h in all_h if not (h.bsatom.idx, h.ligatom.idx) in sel]
sel2 = {}
# 2. If a ligand atom interacts with several binding site atoms in the same residue,
# keep only the one with the closest distance
for h in hydroph:
if not (h.ligatom.idx, h.resnr) in sel2:
sel2[(h.ligatom.idx, h.resnr)] = h
else:
if sel2[(h.ligatom.idx, h.resnr)].distance > h.distance:
sel2[(h.ligatom.idx, h.resnr)] = h
hydroph = [h for h in sel2.values()]
hydroph_final = []
bsclust = {}
# 3. If a protein atom interacts with several neighboring ligand atoms, just keep the one with the closest dist
for h in hydroph:
if h.bsatom.idx not in bsclust:
bsclust[h.bsatom.idx] = [h, ]
else:
bsclust[h.bsatom.idx].append(h)
idx_to_h = {}
for bs in [a for a in bsclust if len(bsclust[a]) == 1]:
hydroph_final.append(bsclust[bs][0])
# A list of tuples with the idx of an atom and one of its neighbours is created
for bs in [a for a in bsclust if not len(bsclust[a]) == 1]:
tuples = []
all_idx = [i.ligatom.idx for i in bsclust[bs]]
for b in bsclust[bs]:
idx = b.ligatom.idx
neigh = [na for na in pybel.ob.OBAtomAtomIter(b.ligatom.OBAtom)]
for n in neigh:
n_idx = n.GetIdx()
if n_idx in all_idx:
if n_idx < idx:
tuples.append((n_idx, idx))
else:
tuples.append((idx, n_idx))
idx_to_h[idx] = b
tuples = list(set(tuples))
tuples = sorted(tuples, key=itemgetter(1))
clusters = cluster_doubles(tuples) # Cluster connected atoms (i.e. find hydrophobic patches)
for cluster in clusters:
min_dist = float('inf')
min_h = None
for atm_idx in cluster:
h = idx_to_h[atm_idx]
if h.distance < min_dist:
min_dist = h.distance
min_h = h
hydroph_final.append(min_h)
before, reduced = len(all_h), len(hydroph_final)
if not before == 0 and not before == reduced:
write_message('Reduced number of hydrophobic contacts from %i to %i.\n' % (before, reduced), indent=True)
return hydroph_final | Apply several rules to reduce the number of hydrophobic interactions. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L710-L775 |
ssalentin/plip | plip/modules/preparation.py | PLInteraction.refine_hbonds_ldon | def refine_hbonds_ldon(self, all_hbonds, salt_lneg, salt_pneg):
"""Refine selection of hydrogen bonds. Do not allow groups which already form salt bridges to form H-Bonds."""
i_set = {}
for hbond in all_hbonds:
i_set[hbond] = False
for salt in salt_pneg:
protidx, ligidx = [at.idx for at in salt.negative.atoms], [at.idx for at in salt.positive.atoms]
if hbond.d.idx in ligidx and hbond.a.idx in protidx:
i_set[hbond] = True
for salt in salt_lneg:
protidx, ligidx = [at.idx for at in salt.positive.atoms], [at.idx for at in salt.negative.atoms]
if hbond.d.idx in ligidx and hbond.a.idx in protidx:
i_set[hbond] = True
# Allow only one hydrogen bond per donor, select interaction with larger donor angle
second_set = {}
hbls = [k for k in i_set.keys() if not i_set[k]]
for hbl in hbls:
if hbl.d.idx not in second_set:
second_set[hbl.d.idx] = (hbl.angle, hbl)
else:
if second_set[hbl.d.idx][0] < hbl.angle:
second_set[hbl.d.idx] = (hbl.angle, hbl)
return [hb[1] for hb in second_set.values()] | python | def refine_hbonds_ldon(self, all_hbonds, salt_lneg, salt_pneg):
"""Refine selection of hydrogen bonds. Do not allow groups which already form salt bridges to form H-Bonds."""
i_set = {}
for hbond in all_hbonds:
i_set[hbond] = False
for salt in salt_pneg:
protidx, ligidx = [at.idx for at in salt.negative.atoms], [at.idx for at in salt.positive.atoms]
if hbond.d.idx in ligidx and hbond.a.idx in protidx:
i_set[hbond] = True
for salt in salt_lneg:
protidx, ligidx = [at.idx for at in salt.positive.atoms], [at.idx for at in salt.negative.atoms]
if hbond.d.idx in ligidx and hbond.a.idx in protidx:
i_set[hbond] = True
# Allow only one hydrogen bond per donor, select interaction with larger donor angle
second_set = {}
hbls = [k for k in i_set.keys() if not i_set[k]]
for hbl in hbls:
if hbl.d.idx not in second_set:
second_set[hbl.d.idx] = (hbl.angle, hbl)
else:
if second_set[hbl.d.idx][0] < hbl.angle:
second_set[hbl.d.idx] = (hbl.angle, hbl)
return [hb[1] for hb in second_set.values()] | Refine selection of hydrogen bonds. Do not allow groups which already form salt bridges to form H-Bonds. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L777-L800 |
ssalentin/plip | plip/modules/preparation.py | PLInteraction.refine_pi_cation_laro | def refine_pi_cation_laro(self, all_picat, stacks):
"""Just important for constellations with histidine involved. If the histidine ring is positioned in stacking
position to an aromatic ring in the ligand, there is in most cases stacking and pi-cation interaction reported
as histidine also carries a positive charge in the ring. For such cases, only report stacking.
"""
i_set = []
for picat in all_picat:
exclude = False
for stack in stacks:
if whichrestype(stack.proteinring.atoms[0]) == 'HIS' and picat.ring.obj == stack.ligandring.obj:
exclude = True
if not exclude:
i_set.append(picat)
return i_set | python | def refine_pi_cation_laro(self, all_picat, stacks):
"""Just important for constellations with histidine involved. If the histidine ring is positioned in stacking
position to an aromatic ring in the ligand, there is in most cases stacking and pi-cation interaction reported
as histidine also carries a positive charge in the ring. For such cases, only report stacking.
"""
i_set = []
for picat in all_picat:
exclude = False
for stack in stacks:
if whichrestype(stack.proteinring.atoms[0]) == 'HIS' and picat.ring.obj == stack.ligandring.obj:
exclude = True
if not exclude:
i_set.append(picat)
return i_set | Just important for constellations with histidine involved. If the histidine ring is positioned in stacking
position to an aromatic ring in the ligand, there is in most cases stacking and pi-cation interaction reported
as histidine also carries a positive charge in the ring. For such cases, only report stacking. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L829-L842 |
ssalentin/plip | plip/modules/preparation.py | PLInteraction.refine_water_bridges | def refine_water_bridges(self, wbridges, hbonds_ldon, hbonds_pdon):
"""A donor atom already forming a hydrogen bond is not allowed to form a water bridge. Each water molecule
can only be donor for two water bridges, selecting the constellation with the omega angle closest to 110 deg."""
donor_atoms_hbonds = [hb.d.idx for hb in hbonds_ldon + hbonds_pdon]
wb_dict = {}
wb_dict2 = {}
omega = 110.0
# Just one hydrogen bond per donor atom
for wbridge in [wb for wb in wbridges if wb.d.idx not in donor_atoms_hbonds]:
if (wbridge.water.idx, wbridge.a.idx) not in wb_dict:
wb_dict[(wbridge.water.idx, wbridge.a.idx)] = wbridge
else:
if abs(omega - wb_dict[(wbridge.water.idx, wbridge.a.idx)].w_angle) < abs(omega - wbridge.w_angle):
wb_dict[(wbridge.water.idx, wbridge.a.idx)] = wbridge
for wb_tuple in wb_dict:
water, acceptor = wb_tuple
if water not in wb_dict2:
wb_dict2[water] = [(abs(omega - wb_dict[wb_tuple].w_angle), wb_dict[wb_tuple]), ]
elif len(wb_dict2[water]) == 1:
wb_dict2[water].append((abs(omega - wb_dict[wb_tuple].w_angle), wb_dict[wb_tuple]))
wb_dict2[water] = sorted(wb_dict2[water])
else:
if wb_dict2[water][1][0] < abs(omega - wb_dict[wb_tuple].w_angle):
wb_dict2[water] = [wb_dict2[water][0], (wb_dict[wb_tuple].w_angle, wb_dict[wb_tuple])]
filtered_wb = []
for fwbridges in wb_dict2.values():
[filtered_wb.append(fwb[1]) for fwb in fwbridges]
return filtered_wb | python | def refine_water_bridges(self, wbridges, hbonds_ldon, hbonds_pdon):
"""A donor atom already forming a hydrogen bond is not allowed to form a water bridge. Each water molecule
can only be donor for two water bridges, selecting the constellation with the omega angle closest to 110 deg."""
donor_atoms_hbonds = [hb.d.idx for hb in hbonds_ldon + hbonds_pdon]
wb_dict = {}
wb_dict2 = {}
omega = 110.0
# Just one hydrogen bond per donor atom
for wbridge in [wb for wb in wbridges if wb.d.idx not in donor_atoms_hbonds]:
if (wbridge.water.idx, wbridge.a.idx) not in wb_dict:
wb_dict[(wbridge.water.idx, wbridge.a.idx)] = wbridge
else:
if abs(omega - wb_dict[(wbridge.water.idx, wbridge.a.idx)].w_angle) < abs(omega - wbridge.w_angle):
wb_dict[(wbridge.water.idx, wbridge.a.idx)] = wbridge
for wb_tuple in wb_dict:
water, acceptor = wb_tuple
if water not in wb_dict2:
wb_dict2[water] = [(abs(omega - wb_dict[wb_tuple].w_angle), wb_dict[wb_tuple]), ]
elif len(wb_dict2[water]) == 1:
wb_dict2[water].append((abs(omega - wb_dict[wb_tuple].w_angle), wb_dict[wb_tuple]))
wb_dict2[water] = sorted(wb_dict2[water])
else:
if wb_dict2[water][1][0] < abs(omega - wb_dict[wb_tuple].w_angle):
wb_dict2[water] = [wb_dict2[water][0], (wb_dict[wb_tuple].w_angle, wb_dict[wb_tuple])]
filtered_wb = []
for fwbridges in wb_dict2.values():
[filtered_wb.append(fwb[1]) for fwb in fwbridges]
return filtered_wb | A donor atom already forming a hydrogen bond is not allowed to form a water bridge. Each water molecule
can only be donor for two water bridges, selecting the constellation with the omega angle closest to 110 deg. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L844-L873 |
ssalentin/plip | plip/modules/preparation.py | BindingSite.find_hal | def find_hal(self, atoms):
"""Look for halogen bond acceptors (Y-{O|P|N|S}, with Y=C,P,S)"""
data = namedtuple('hal_acceptor', 'o o_orig_idx y y_orig_idx')
a_set = []
# All oxygens, nitrogen, sulfurs with neighboring carbon, phosphor, nitrogen or sulfur
for a in [at for at in atoms if at.atomicnum in [8, 7, 16]]:
n_atoms = [na for na in pybel.ob.OBAtomAtomIter(a.OBAtom) if na.GetAtomicNum() in [6, 7, 15, 16]]
if len(n_atoms) == 1: # Proximal atom
o_orig_idx = self.Mapper.mapid(a.idx, mtype=self.mtype, bsid=self.bsid)
y_orig_idx = self.Mapper.mapid(n_atoms[0].GetIdx(), mtype=self.mtype, bsid=self.bsid)
a_set.append(data(o=a, o_orig_idx=o_orig_idx, y=pybel.Atom(n_atoms[0]), y_orig_idx=y_orig_idx))
return a_set | python | def find_hal(self, atoms):
"""Look for halogen bond acceptors (Y-{O|P|N|S}, with Y=C,P,S)"""
data = namedtuple('hal_acceptor', 'o o_orig_idx y y_orig_idx')
a_set = []
# All oxygens, nitrogen, sulfurs with neighboring carbon, phosphor, nitrogen or sulfur
for a in [at for at in atoms if at.atomicnum in [8, 7, 16]]:
n_atoms = [na for na in pybel.ob.OBAtomAtomIter(a.OBAtom) if na.GetAtomicNum() in [6, 7, 15, 16]]
if len(n_atoms) == 1: # Proximal atom
o_orig_idx = self.Mapper.mapid(a.idx, mtype=self.mtype, bsid=self.bsid)
y_orig_idx = self.Mapper.mapid(n_atoms[0].GetIdx(), mtype=self.mtype, bsid=self.bsid)
a_set.append(data(o=a, o_orig_idx=o_orig_idx, y=pybel.Atom(n_atoms[0]), y_orig_idx=y_orig_idx))
return a_set | Look for halogen bond acceptors (Y-{O|P|N|S}, with Y=C,P,S) | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L893-L904 |
ssalentin/plip | plip/modules/preparation.py | BindingSite.find_charged | def find_charged(self, mol):
"""Looks for positive charges in arginine, histidine or lysine, for negative in aspartic and glutamic acid."""
data = namedtuple('pcharge', 'atoms atoms_orig_idx type center restype resnr reschain')
a_set = []
# Iterate through all residue, exclude those in chains defined as peptides
for res in [r for r in pybel.ob.OBResidueIter(mol.OBMol) if not r.GetChain() in config.PEPTIDES]:
if config.INTRA is not None:
if res.GetChain() != config.INTRA:
continue
a_contributing = []
a_contributing_orig_idx = []
if res.GetName() in ('ARG', 'HIS', 'LYS'): # Arginine, Histidine or Lysine have charged sidechains
for a in pybel.ob.OBResidueAtomIter(res):
if a.GetType().startswith('N') and res.GetAtomProperty(a, 8) \
and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf:
a_contributing.append(pybel.Atom(a))
a_contributing_orig_idx.append(self.Mapper.mapid(a.GetIdx(), mtype='protein'))
if not len(a_contributing) == 0:
a_set.append(data(atoms=a_contributing,
atoms_orig_idx=a_contributing_orig_idx,
type='positive',
center=centroid([ac.coords for ac in a_contributing]),
restype=res.GetName(),
resnr=res.GetNum(),
reschain=res.GetChain()))
if res.GetName() in ('GLU', 'ASP'): # Aspartic or Glutamic Acid
for a in pybel.ob.OBResidueAtomIter(res):
if a.GetType().startswith('O') and res.GetAtomProperty(a, 8) \
and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf:
a_contributing.append(pybel.Atom(a))
a_contributing_orig_idx.append(self.Mapper.mapid(a.GetIdx(), mtype='protein'))
if not len(a_contributing) == 0:
a_set.append(data(atoms=a_contributing,
atoms_orig_idx=a_contributing_orig_idx,
type='negative',
center=centroid([ac.coords for ac in a_contributing]),
restype=res.GetName(),
resnr=res.GetNum(),
reschain=res.GetChain()))
return a_set | python | def find_charged(self, mol):
"""Looks for positive charges in arginine, histidine or lysine, for negative in aspartic and glutamic acid."""
data = namedtuple('pcharge', 'atoms atoms_orig_idx type center restype resnr reschain')
a_set = []
# Iterate through all residue, exclude those in chains defined as peptides
for res in [r for r in pybel.ob.OBResidueIter(mol.OBMol) if not r.GetChain() in config.PEPTIDES]:
if config.INTRA is not None:
if res.GetChain() != config.INTRA:
continue
a_contributing = []
a_contributing_orig_idx = []
if res.GetName() in ('ARG', 'HIS', 'LYS'): # Arginine, Histidine or Lysine have charged sidechains
for a in pybel.ob.OBResidueAtomIter(res):
if a.GetType().startswith('N') and res.GetAtomProperty(a, 8) \
and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf:
a_contributing.append(pybel.Atom(a))
a_contributing_orig_idx.append(self.Mapper.mapid(a.GetIdx(), mtype='protein'))
if not len(a_contributing) == 0:
a_set.append(data(atoms=a_contributing,
atoms_orig_idx=a_contributing_orig_idx,
type='positive',
center=centroid([ac.coords for ac in a_contributing]),
restype=res.GetName(),
resnr=res.GetNum(),
reschain=res.GetChain()))
if res.GetName() in ('GLU', 'ASP'): # Aspartic or Glutamic Acid
for a in pybel.ob.OBResidueAtomIter(res):
if a.GetType().startswith('O') and res.GetAtomProperty(a, 8) \
and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf:
a_contributing.append(pybel.Atom(a))
a_contributing_orig_idx.append(self.Mapper.mapid(a.GetIdx(), mtype='protein'))
if not len(a_contributing) == 0:
a_set.append(data(atoms=a_contributing,
atoms_orig_idx=a_contributing_orig_idx,
type='negative',
center=centroid([ac.coords for ac in a_contributing]),
restype=res.GetName(),
resnr=res.GetNum(),
reschain=res.GetChain()))
return a_set | Looks for positive charges in arginine, histidine or lysine, for negative in aspartic and glutamic acid. | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L906-L945 |
ssalentin/plip | plip/modules/preparation.py | BindingSite.find_metal_binding | def find_metal_binding(self, mol):
"""Looks for atoms that could possibly be involved in chelating a metal ion.
This can be any main chain oxygen atom or oxygen, nitrogen and sulfur from specific amino acids"""
data = namedtuple('metal_binding', 'atom atom_orig_idx type restype resnr reschain location')
a_set = []
for res in pybel.ob.OBResidueIter(mol.OBMol):
restype, reschain, resnr = res.GetName().upper(), res.GetChain(), res.GetNum()
if restype in ['ASP', 'GLU', 'SER', 'THR', 'TYR']: # Look for oxygens here
for a in pybel.ob.OBResidueAtomIter(res):
if a.GetType().startswith('O') and res.GetAtomProperty(a, 8) \
and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf:
atom_orig_idx = self.Mapper.mapid(a.GetIdx(), mtype=self.mtype, bsid=self.bsid)
a_set.append(data(atom=pybel.Atom(a), atom_orig_idx=atom_orig_idx, type='O', restype=restype,
resnr=resnr, reschain=reschain,
location='protein.sidechain'))
if restype == 'HIS': # Look for nitrogen here
for a in pybel.ob.OBResidueAtomIter(res):
if a.GetType().startswith('N') and res.GetAtomProperty(a, 8) \
and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf:
atom_orig_idx = self.Mapper.mapid(a.GetIdx(), mtype=self.mtype, bsid=self.bsid)
a_set.append(data(atom=pybel.Atom(a), atom_orig_idx=atom_orig_idx, type='N', restype=restype,
resnr=resnr, reschain=reschain,
location='protein.sidechain'))
if restype == 'CYS': # Look for sulfur here
for a in pybel.ob.OBResidueAtomIter(res):
if a.GetType().startswith('S') and res.GetAtomProperty(a, 8) \
and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf:
atom_orig_idx = self.Mapper.mapid(a.GetIdx(), mtype=self.mtype, bsid=self.bsid)
a_set.append(data(atom=pybel.Atom(a), atom_orig_idx=atom_orig_idx, type='S', restype=restype,
resnr=resnr, reschain=reschain,
location='protein.sidechain'))
for a in pybel.ob.OBResidueAtomIter(res): # All main chain oxygens
if a.GetType().startswith('O') and res.GetAtomProperty(a, 2) \
and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf and restype != 'HOH':
atom_orig_idx = self.Mapper.mapid(a.GetIdx(), mtype=self.mtype, bsid=self.bsid)
a_set.append(data(atom=pybel.Atom(a), atom_orig_idx=atom_orig_idx, type='O', restype=res.GetName(),
resnr=res.GetNum(), reschain=res.GetChain(),
location='protein.mainchain'))
return a_set | python | def find_metal_binding(self, mol):
"""Looks for atoms that could possibly be involved in chelating a metal ion.
This can be any main chain oxygen atom or oxygen, nitrogen and sulfur from specific amino acids"""
data = namedtuple('metal_binding', 'atom atom_orig_idx type restype resnr reschain location')
a_set = []
for res in pybel.ob.OBResidueIter(mol.OBMol):
restype, reschain, resnr = res.GetName().upper(), res.GetChain(), res.GetNum()
if restype in ['ASP', 'GLU', 'SER', 'THR', 'TYR']: # Look for oxygens here
for a in pybel.ob.OBResidueAtomIter(res):
if a.GetType().startswith('O') and res.GetAtomProperty(a, 8) \
and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf:
atom_orig_idx = self.Mapper.mapid(a.GetIdx(), mtype=self.mtype, bsid=self.bsid)
a_set.append(data(atom=pybel.Atom(a), atom_orig_idx=atom_orig_idx, type='O', restype=restype,
resnr=resnr, reschain=reschain,
location='protein.sidechain'))
if restype == 'HIS': # Look for nitrogen here
for a in pybel.ob.OBResidueAtomIter(res):
if a.GetType().startswith('N') and res.GetAtomProperty(a, 8) \
and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf:
atom_orig_idx = self.Mapper.mapid(a.GetIdx(), mtype=self.mtype, bsid=self.bsid)
a_set.append(data(atom=pybel.Atom(a), atom_orig_idx=atom_orig_idx, type='N', restype=restype,
resnr=resnr, reschain=reschain,
location='protein.sidechain'))
if restype == 'CYS': # Look for sulfur here
for a in pybel.ob.OBResidueAtomIter(res):
if a.GetType().startswith('S') and res.GetAtomProperty(a, 8) \
and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf:
atom_orig_idx = self.Mapper.mapid(a.GetIdx(), mtype=self.mtype, bsid=self.bsid)
a_set.append(data(atom=pybel.Atom(a), atom_orig_idx=atom_orig_idx, type='S', restype=restype,
resnr=resnr, reschain=reschain,
location='protein.sidechain'))
for a in pybel.ob.OBResidueAtomIter(res): # All main chain oxygens
if a.GetType().startswith('O') and res.GetAtomProperty(a, 2) \
and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf and restype != 'HOH':
atom_orig_idx = self.Mapper.mapid(a.GetIdx(), mtype=self.mtype, bsid=self.bsid)
a_set.append(data(atom=pybel.Atom(a), atom_orig_idx=atom_orig_idx, type='O', restype=res.GetName(),
resnr=res.GetNum(), reschain=res.GetChain(),
location='protein.mainchain'))
return a_set | Looks for atoms that could possibly be involved in chelating a metal ion.
This can be any main chain oxygen atom or oxygen, nitrogen and sulfur from specific amino acids | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L947-L985 |
ssalentin/plip | plip/modules/preparation.py | Ligand.is_functional_group | def is_functional_group(self, atom, group):
"""Given a pybel atom, look up if it belongs to a function group"""
n_atoms = [a_neighbor.GetAtomicNum() for a_neighbor in pybel.ob.OBAtomAtomIter(atom.OBAtom)]
if group in ['quartamine', 'tertamine'] and atom.atomicnum == 7: # Nitrogen
# It's a nitrogen, so could be a protonated amine or quaternary ammonium
if '1' not in n_atoms and len(n_atoms) == 4:
return True if group == 'quartamine' else False # It's a quat. ammonium (N with 4 residues != H)
elif atom.OBAtom.GetHyb() == 3 and len(n_atoms) >= 3:
return True if group == 'tertamine' else False # It's sp3-hybridized, so could pick up an hydrogen
else:
return False
if group in ['sulfonium', 'sulfonicacid', 'sulfate'] and atom.atomicnum == 16: # Sulfur
if '1' not in n_atoms and len(n_atoms) == 3: # It's a sulfonium (S with 3 residues != H)
return True if group == 'sulfonium' else False
elif n_atoms.count(8) == 3: # It's a sulfonate or sulfonic acid
return True if group == 'sulfonicacid' else False
elif n_atoms.count(8) == 4: # It's a sulfate
return True if group == 'sulfate' else False
if group == 'phosphate' and atom.atomicnum == 15: # Phosphor
if set(n_atoms) == {8}: # It's a phosphate
return True
if group in ['carboxylate', 'guanidine'] and atom.atomicnum == 6: # It's a carbon atom
if n_atoms.count(8) == 2 and n_atoms.count(6) == 1: # It's a carboxylate group
return True if group == 'carboxylate' else False
elif n_atoms.count(7) == 3 and len(n_atoms) == 3: # It's a guanidine group
nitro_partners = []
for nitro in pybel.ob.OBAtomAtomIter(atom.OBAtom):
nitro_partners.append(len([b_neighbor for b_neighbor in pybel.ob.OBAtomAtomIter(nitro)]))
if min(nitro_partners) == 1: # One nitrogen is only connected to the carbon, can pick up a H
return True if group == 'guanidine' else False
if group == 'halocarbon' and atom.atomicnum in [9, 17, 35, 53]: # Halogen atoms
n_atoms = [na for na in pybel.ob.OBAtomAtomIter(atom.OBAtom) if na.GetAtomicNum() == 6]
if len(n_atoms) == 1: # Halocarbon
return True
else:
return False | python | def is_functional_group(self, atom, group):
"""Given a pybel atom, look up if it belongs to a function group"""
n_atoms = [a_neighbor.GetAtomicNum() for a_neighbor in pybel.ob.OBAtomAtomIter(atom.OBAtom)]
if group in ['quartamine', 'tertamine'] and atom.atomicnum == 7: # Nitrogen
# It's a nitrogen, so could be a protonated amine or quaternary ammonium
if '1' not in n_atoms and len(n_atoms) == 4:
return True if group == 'quartamine' else False # It's a quat. ammonium (N with 4 residues != H)
elif atom.OBAtom.GetHyb() == 3 and len(n_atoms) >= 3:
return True if group == 'tertamine' else False # It's sp3-hybridized, so could pick up an hydrogen
else:
return False
if group in ['sulfonium', 'sulfonicacid', 'sulfate'] and atom.atomicnum == 16: # Sulfur
if '1' not in n_atoms and len(n_atoms) == 3: # It's a sulfonium (S with 3 residues != H)
return True if group == 'sulfonium' else False
elif n_atoms.count(8) == 3: # It's a sulfonate or sulfonic acid
return True if group == 'sulfonicacid' else False
elif n_atoms.count(8) == 4: # It's a sulfate
return True if group == 'sulfate' else False
if group == 'phosphate' and atom.atomicnum == 15: # Phosphor
if set(n_atoms) == {8}: # It's a phosphate
return True
if group in ['carboxylate', 'guanidine'] and atom.atomicnum == 6: # It's a carbon atom
if n_atoms.count(8) == 2 and n_atoms.count(6) == 1: # It's a carboxylate group
return True if group == 'carboxylate' else False
elif n_atoms.count(7) == 3 and len(n_atoms) == 3: # It's a guanidine group
nitro_partners = []
for nitro in pybel.ob.OBAtomAtomIter(atom.OBAtom):
nitro_partners.append(len([b_neighbor for b_neighbor in pybel.ob.OBAtomAtomIter(nitro)]))
if min(nitro_partners) == 1: # One nitrogen is only connected to the carbon, can pick up a H
return True if group == 'guanidine' else False
if group == 'halocarbon' and atom.atomicnum in [9, 17, 35, 53]: # Halogen atoms
n_atoms = [na for na in pybel.ob.OBAtomAtomIter(atom.OBAtom) if na.GetAtomicNum() == 6]
if len(n_atoms) == 1: # Halocarbon
return True
else:
return False | Given a pybel atom, look up if it belongs to a function group | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L1073-L1113 |
ssalentin/plip | plip/modules/preparation.py | Ligand.find_hal | def find_hal(self, atoms):
"""Look for halogen bond donors (X-C, with X=F, Cl, Br, I)"""
data = namedtuple('hal_donor', 'x orig_x x_orig_idx c c_orig_idx')
a_set = []
for a in atoms:
if self.is_functional_group(a, 'halocarbon'):
n_atoms = [na for na in pybel.ob.OBAtomAtomIter(a.OBAtom) if na.GetAtomicNum() == 6]
x_orig_idx = self.Mapper.mapid(a.idx, mtype=self.mtype, bsid=self.bsid)
orig_x = self.Mapper.id_to_atom(x_orig_idx)
c_orig_idx = [self.Mapper.mapid(na.GetIdx(), mtype=self.mtype, bsid=self.bsid) for na in n_atoms]
a_set.append(data(x=a, orig_x=orig_x, x_orig_idx=x_orig_idx,
c=pybel.Atom(n_atoms[0]), c_orig_idx=c_orig_idx))
if len(a_set) != 0:
write_message('Ligand contains %i halogen atom(s).\n' % len(a_set), indent=True)
return a_set | python | def find_hal(self, atoms):
"""Look for halogen bond donors (X-C, with X=F, Cl, Br, I)"""
data = namedtuple('hal_donor', 'x orig_x x_orig_idx c c_orig_idx')
a_set = []
for a in atoms:
if self.is_functional_group(a, 'halocarbon'):
n_atoms = [na for na in pybel.ob.OBAtomAtomIter(a.OBAtom) if na.GetAtomicNum() == 6]
x_orig_idx = self.Mapper.mapid(a.idx, mtype=self.mtype, bsid=self.bsid)
orig_x = self.Mapper.id_to_atom(x_orig_idx)
c_orig_idx = [self.Mapper.mapid(na.GetIdx(), mtype=self.mtype, bsid=self.bsid) for na in n_atoms]
a_set.append(data(x=a, orig_x=orig_x, x_orig_idx=x_orig_idx,
c=pybel.Atom(n_atoms[0]), c_orig_idx=c_orig_idx))
if len(a_set) != 0:
write_message('Ligand contains %i halogen atom(s).\n' % len(a_set), indent=True)
return a_set | Look for halogen bond donors (X-C, with X=F, Cl, Br, I) | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L1115-L1129 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.