code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
f = urlopen("http://projects.biotec.tu-dresden.de/plip-rest/pdb/%s?format=xml" % pdbid.lower()) self.doc = etree.parse(f)
def load_data(self, pdbid)
Loads and parses an XML resource and saves it as a tree if successful
8.068703
7.347231
1.098196
"Write your forwards methods here." for a in orm.Article.objects.all(): if a.updated: a.last_updated = a.updated a.save(force_update=True)
def forwards(self, orm)
Write your forwards methods here.
6.892205
5.726133
1.20364
url = 'http://www.rcsb.org/pdb/rest/idStatus?structureId=%s' % pdbid xmlf = urlopen(url) xml = et.parse(xmlf) xmlf.close() status = None current_pdbid = pdbid for df in xml.xpath('//record'): status = df.attrib['status'] # Status of an entry can be either 'UNKWOWN', 'OBSOLETE',...
def check_pdb_status(pdbid)
Returns the status and up-to-date entry in the PDB for a given PDB ID
4.438442
4.226874
1.050053
pdbid = pdbid.lower() write_message('\nChecking status of PDB ID %s ... ' % pdbid) state, current_entry = check_pdb_status(pdbid) # Get state and current PDB ID if state == 'OBSOLETE': write_message('entry is obsolete, getting %s instead.\n' % current_entry) elif state == 'CURRENT': ...
def fetch_pdb(pdbid)
Get the newest entry from the RCSB server for the given PDB ID. Exits with '1' if PDB ID is invalid.
4.697468
4.518673
1.039568
" Delegate the boxing. " obj = position.target return getattr(position.target, 'box_class', Box)(obj, *args, **kwargs)
def PositionBox(position, *args, **kwargs)
Delegate the boxing.
15.182552
10.456577
1.451962
now = timezone.now() lookup = (Q(active_from__isnull=True) | Q(active_from__lte=now)) & \ (Q(active_till__isnull=True) | Q(active_till__gt=now)) while True: try: return self.get(lookup, category=category, name=name, disab...
def get_active_position(self, category, name, nofallback=False)
Get active position for given position name. params: category - Category model to look for name - name of the position nofallback - if True than do not fall back to parent category if active position is not found for category
4.03601
4.103551
0.983541
" Render the position. " if not self.target: if self.target_ct: # broken Generic FK: log.warning('Broken target for position with pk %r', self.pk) return '' try: return Template(self.text, name="position-%s" % self.n...
def render(self, context, nodelist, box_type)
Render the position.
5.301482
5.083361
1.042909
self.standard_settings() cmd.set('dash_gap', 0) # Show not dashes, but lines for the pliprofiler cmd.set('ray_shadow', 0) # Turn on ray shadows for clearer ray-traced images cmd.set('cartoon_color', 'mylightblue') # Set clipping planes for full view cmd.clip('...
def set_initial_representations(self)
General settings for PyMOL
10.648356
9.307961
1.144005
cmd.set('bg_rgb', [1.0, 1.0, 1.0]) # White background cmd.set('depth_cue', 0) # Turn off depth cueing (no fog) cmd.set('cartoon_side_chain_helper', 1) # Improve combined visualization of sticks and cartoon cmd.set('cartoon_fancy_helices', 1) # Nicer visualization of helices ...
def standard_settings(self)
Sets up standard settings for a nice visualization.
5.576202
5.278683
1.056362
cmd.set_color('myorange', '[253, 174, 97]') cmd.set_color('mygreen', '[171, 221, 164]') cmd.set_color('myred', '[215, 25, 28]') cmd.set_color('myblue', '[43, 131, 186]') cmd.set_color('mylightblue', '[158, 202, 225]') cmd.set_color('mylightgreen', '[229, 245, 224...
def set_custom_colorset(self)
Defines a colorset with matching colors. Provided by Joachim.
2.675197
2.606722
1.026269
hydroph = self.plcomplex.hydrophobic_contacts if not len(hydroph.bs_ids) == 0: self.select_by_ids('Hydrophobic-P', hydroph.bs_ids, restrict=self.protname) self.select_by_ids('Hydrophobic-L', hydroph.lig_ids, restrict=self.ligname) for i in hydroph.pairs_ids:...
def show_hydrophobic(self)
Visualizes hydrophobic contacts.
3.54053
3.419345
1.035441
hbonds = self.plcomplex.hbonds for group in [['HBondDonor-P', hbonds.prot_don_id], ['HBondAccept-P', hbonds.prot_acc_id]]: if not len(group[1]) == 0: self.select_by_ids(group[0], group[1], restrict=self.protname) for group in [['HBondDon...
def show_hbonds(self)
Visualizes hydrogen bonds.
2.471569
2.449718
1.00892
halogen = self.plcomplex.halogen_bonds all_don_x, all_acc_o = [], [] for h in halogen: all_don_x.append(h.don_id) all_acc_o.append(h.acc_id) cmd.select('tmp_bs', 'id %i & %s' % (h.acc_id, self.protname)) cmd.select('tmp_lig', 'id %i & %s' ...
def show_halogen(self)
Visualize halogen bonds.
3.682363
3.621171
1.016899
stacks = self.plcomplex.pistacking for i, stack in enumerate(stacks): pires_ids = '+'.join(map(str, stack.proteinring_atoms)) pilig_ids = '+'.join(map(str, stack.ligandring_atoms)) cmd.select('StackRings-P', 'StackRings-P or (id %s & %s)' % (pires_ids, self.p...
def show_stacking(self)
Visualize pi-stacking interactions.
2.598896
2.498405
1.040222
for i, p in enumerate(self.plcomplex.pication): cmd.pseudoatom('ps-picat-1-%i' % i, pos=p.ring_center) cmd.pseudoatom('ps-picat-2-%i' % i, pos=p.charge_center) if p.protcharged: cmd.pseudoatom('Chargecenter-P', pos=p.charge_center) cmd...
def show_cationpi(self)
Visualize cation-pi interactions.
2.851665
2.808971
1.015199
for i, saltb in enumerate(self.plcomplex.saltbridges): if saltb.protispos: for patom in saltb.positive_atoms: cmd.select('PosCharge-P', 'PosCharge-P or (id %i & %s)' % (patom, self.protname)) for latom in saltb.negative_atoms: ...
def show_sbridges(self)
Visualize salt bridges.
2.347747
2.268114
1.035109
for bridge in self.plcomplex.waterbridges: if bridge.protisdon: cmd.select('HBondDonor-P', 'HBondDonor-P or (id %i & %s)' % (bridge.don_id, self.protname)) cmd.select('HBondAccept-L', 'HBondAccept-L or (id %i & %s)' % (bridge.acc_id, self.ligname)) ...
def show_wbridges(self)
Visualize water bridges.
2.254894
2.18889
1.030154
metal_complexes = self.plcomplex.metal_complexes if not len(metal_complexes) == 0: self.select_by_ids('Metal-M', self.metal_ids) for metal_complex in metal_complexes: cmd.select('tmp_m', 'id %i' % metal_complex.metal_id) cmd.select('tmp_t'...
def show_metal(self)
Visualize metal coordination.
3.005844
2.961511
1.01497
if not len(self.plcomplex.unpaired_hba_idx) == 0: self.select_by_ids('Unpaired-HBA', self.plcomplex.unpaired_hba_idx, selection_exists=True) if not len(self.plcomplex.unpaired_hbd_idx) == 0: self.select_by_ids('Unpaired-HBD', self.plcomplex.unpaired_hbd_idx, selection_e...
def selections_cleanup(self)
Cleans up non-used selections
2.69161
2.643983
1.018013
cmd.group('Structures', '%s %s %sCartoon' % (self.protname, self.ligname, self.protname)) cmd.group('Interactions', 'Hydrophobic HBonds HalogenBonds WaterBridges PiCation PiStackingP PiStackingT ' 'Saltbridges MetalComplexes') cmd.group('Atoms', '') ...
def selections_group(self)
Group all selections
7.886041
7.727473
1.02052
cmd.remove('not alt ""+A') # Remove alternate conformations cmd.hide('labels', 'Interactions') # Hide labels of lines cmd.disable('%sCartoon' % self.protname) cmd.hide('everything', 'hydrogens')
def additional_cleanup(self)
Cleanup of various representations
22.301136
18.509573
1.204843
cmd.center(self.ligname) cmd.orient(self.ligname) cmd.turn('x', 110) # If the ligand is aligned with the longest axis, aromatic rings are hidden if 'AllBSRes' in cmd.get_names("selections"): cmd.zoom('%s or AllBSRes' % self.ligname, 3) else: if s...
def zoom_to_ligand(self)
Zoom in too ligand and its interactions.
6.390563
6.154906
1.038288
filename = '%s_%s' % (self.protname.upper(), "_".join( [self.hetid, self.plcomplex.chain, self.plcomplex.position])) if override is not None: filename = override cmd.save("/".join([outfolder, "%s.pse" % filename]))
def save_session(self, outfolder, override=None)
Saves a PyMOL session file.
8.277981
6.763787
1.223868
sys.stdout = sys.__stdout__ cmd.feedback('disable', 'movie', 'everything') cmd.viewport(width, height) cmd.zoom('visible', 1.5) # Adapt the zoom to the viewport cmd.set('ray_trace_frames', 1) # Frames are raytraced before saving an image. cmd.mpng(filepath, 1, ...
def png_workaround(self, filepath, width=1200, height=800)
Workaround for (a) severe bug(s) in PyMOL preventing ray-traced images to be produced in command-line mode. Use this function in case neither cmd.ray() or cmd.png() work.
4.800377
4.657982
1.03057
self.set_fancy_ray() self.png_workaround("/".join([outfolder, filename]))
def save_picture(self, outfolder, filename)
Saves a picture
26.414923
29.443037
0.897153
cmd.set('light_count', 6) cmd.set('spec_count', 1.5) cmd.set('shininess', 4) cmd.set('specular', 0.3) cmd.set('reflect', 1.6) cmd.set('ambient', 0) cmd.set('direct', 0) cmd.set('ray_shadow', 0) # Gives the molecules a flat, modern look cm...
def set_fancy_ray(self)
Give the molecule a flat, modern look.
4.579589
3.583268
1.278048
cmd.hide('sticks', self.ligname) cmd.set('cartoon_color', 'lightorange', self.ligname) cmd.show('cartoon', self.ligname) cmd.show('sticks', "byres *-L") cmd.util.cnc(self.ligname) cmd.remove('%sCartoon and chain %s' % (self.protname, self.plcomplex.chain)) ...
def adapt_for_peptides(self)
Adapt visualization for peptide ligands and interchain contacts
6.755741
5.979421
1.129832
# Show sticks for all residues interacing with the ligand cmd.select('AllBSRes', 'byres (Hydrophobic-P or HBondDonor-P or HBondAccept-P or PosCharge-P or NegCharge-P or ' 'StackRings-P or PiCatRing-P or HalogenAcc or Metal-P)') cmd.show('sticks', 'AllBSRe...
def refinements(self)
Refinements for the visualization
5.153779
5.082148
1.014095
if not isinstance(model, ContentType): model_ct = ContentType.objects.get_for_model(model) else: model_ct = model key = _get_key(KEY_PREFIX, model_ct, **kwargs) obj = cache.get(key) if obj is None: # if we are looking for a publishable, fetch just the actual content ...
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...
3.238363
3.325813
0.973706
if model is not None: if not isinstance(model, ContentType): model = ContentType.objects.get_for_model(model) pks = [(model, pk) for pk in pks] else: pks = [(ContentType.objects.get_for_id(ct_id), pk) for (ct_id, pk) in pks] keys = [_get_key(KEY_PREFIX, model, pk=pk...
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_TIMEOU...
2.572093
2.582253
0.996066
try: return get_cached_object(model, timeout=timeout, **kwargs) except ObjectDoesNotExist, e: raise Http404('Reason: %s' % str(e))
def get_cached_object_or_404(model, timeout=CACHE_TIMEOUT, **kwargs)
Shortcut that will raise Http404 if there is no object matching the query see get_cached_object for params description
3.090898
2.821947
1.095307
return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc)
def tmpfile(prefix, direc)
Returns the path to a newly created temporary file.
4.09255
3.963167
1.032646
p = re.compile("[0-9][0-9a-z]{3}") m = p.search(string.lower()) try: return m.group() except AttributeError: return "UnknownProtein"
def extract_pdbid(string)
Use regular expressions to get a PDB ID from a string
3.794184
3.800384
0.998369
atom = atom if not isinstance(atom, Atom) else atom.OBAtom # Convert to OpenBabel Atom return atom.GetResidue().GetName() if atom.GetResidue() is not None else None
def whichrestype(atom)
Returns the residue name of an Pybel or OpenBabel atom.
4.877939
3.042887
1.603062
atom = atom if not isinstance(atom, Atom) else atom.OBAtom # Convert to OpenBabel Atom return atom.GetResidue().GetNum() if atom.GetResidue() is not None else None
def whichresnumber(atom)
Returns the residue number of an Pybel or OpenBabel atom (numbering as in original PDB file).
4.595992
3.244417
1.416585
atom = atom if not isinstance(atom, Atom) else atom.OBAtom # Convert to OpenBabel Atom return atom.GetResidue().GetChain() if atom.GetResidue() is not None else None
def whichchain(atom)
Returns the residue number of an PyBel or OpenBabel atom.
4.607178
3.636487
1.266931
if not len(v1) == 3 and len(v2) == 3: print("Vectors are not in 3D space. Returning None.") return None return np.sqrt((v1[0] - v2[0]) ** 2 + (v1[1] - v2[1]) ** 2 + (v1[2] - v2[2]) ** 2)
def euclidean3d(v1, v2)
Faster implementation of euclidean distance for the 3D case.
1.894291
1.76815
1.071341
return None if len(p1) != len(p2) else np.array([p2[i] - p1[i] for i in range(len(p1))])
def vector(p1, p2)
Vector from p1 to p2. :param p1: coordinates of point p1 :param p2: coordinates of point p2 :returns : numpy array with vector coordinates
2.33703
2.875709
0.81268
if np.array_equal(v1, v2): return 0.0 dm = np.dot(v1, v2) cm = np.linalg.norm(v1) * np.linalg.norm(v2) angle = np.arccos(round(dm / cm, 10)) # Round here to prevent floating point errors return np.degrees([angle, ])[0] if deg else angle
def vecangle(v1, v2, deg=True)
Calculate the angle between two vectors :param v1: coordinates of vector v1 :param v2: coordinates of vector v2 :returns : angle in degree or rad
3.13121
3.591776
0.871772
norm = np.linalg.norm(v) return v/norm if not norm == 0 else v
def normalize_vector(v)
Take a vector and return the normalized vector :param v: a vector v :returns : normalized vector v
3.621024
4.198097
0.862539
return list(map(np.mean, (([c[0] for c in coo]), ([c[1] for c in coo]), ([c[2] for c in coo]))))
def centroid(coo)
Calculates the centroid from a 3D point cloud and returns the coordinates :param coo: Array of coordinate arrays :returns : centroid coordinates as list
3.282466
3.5806
0.916736
location = {} # hashtable of which cluster each element is in clusters = [] # Go through each double for t in double_list: a, b = t[0], t[1] # If they both are already in different clusters, merge the clusters if a in location and b in location: if location[a] !...
def cluster_doubles(double_list)
Given a list of doubles, they are clustered if they share one element :param double_list: list of doubles :returns : list of clusters (tuples)
2.246291
2.285788
0.982721
folder_path = tilde_expansion(folder_path) folder_path = "".join([folder_path, '/']) if not folder_path[-1] == '/' else folder_path direc = os.path.dirname(folder_path) if not folder_exists(direc): os.makedirs(direc)
def create_folder_if_not_exists(folder_path)
Creates a folder if it does not exists.
3.145183
2.97047
1.058817
import pymol # Pass standard arguments of function to prevent PyMOL from printing out PDB headers (workaround) pymol.finish_launching(args=['pymol', options, '-K']) pymol.cmd.reinitialize()
def initialize_pymol(options)
Initializes PyMOL
10.59988
10.929196
0.969868
import pymol pymol.pymol_argv = ['pymol', '%s' % options] + sys.argv[1:] if run: initialize_pymol(options) if quiet: pymol.cmd.feedback('disable', 'all', 'everything')
def start_pymol(quiet=False, options='-p', run=False)
Starts up PyMOL and sets general options. Quiet mode suppresses all PyMOL output. Command line options can be passed as the second argument.
3.914599
4.427754
0.884105
nuc_covalent = [] ####################################### # Basic support for RNA/DNA as ligand # ####################################### nucleotides = ['A', 'C', 'T', 'G', 'U', 'DA', 'DC', 'DT', 'DG', 'DU'] dna_rna = {} # Dictionary of DNA/RNA residues by chain covlinkage = namedtupl...
def nucleotide_linkage(residues)
Support for DNA/RNA ligands by finding missing covalent linkages to stitch DNA/RNA together.
2.859063
2.648831
1.079368
normals = [] for a in r_atoms: adj = pybel.ob.OBAtomAtomIter(a.OBAtom) # Check for neighboring atoms in the ring n_coords = [pybel.Atom(neigh).coords for neigh in adj if ring.IsMember(neigh)] vec1, vec2 = vector(a.coords, n_coords[0]), vector(a.coords, n_coords[1]) n...
def ring_is_planar(ring, r_atoms)
Given a set of ring atoms, check if the ring is sufficiently planar to be considered aromatic
4.053741
3.932186
1.030913
if len(names) > 3: # Polymer if len(set(config.RNA).intersection(set(names))) != 0: ligtype = 'RNA' elif len(set(config.DNA).intersection(set(names))) != 0: ligtype = 'DNA' else: ligtype = "POLYMER" else: ligtype = 'SMALLMOLECULE' fo...
def classify_by_name(names)
Classify a (composite) ligand by the HETID(s)
3.497292
3.327803
1.050931
main = [x for x in members if x[0] not in config.METAL_IONS] ion = [x for x in members if x[0] in config.METAL_IONS] sorted_main = sorted(main, key=lambda x: (x[1], x[2])) sorted_main = sorted(main, key=lambda x: (x[1], x[2])) sorted_ion = sorted(ion, key=lambda x: (x[1], x[2])) return sort...
def sort_members_by_importance(members)
Sort the members of a composite ligand according to two criteria: 1. Split up in main and ion group. Ion groups are located behind the main group. 2. Within each group, sort by chain and position.
2.339442
2.033025
1.15072
query = pybel.ob.CompileMoleculeQuery(reference.OBMol) mappr = pybel.ob.OBIsomorphismMapper.GetInstance(query) if all: isomorphs = pybel.ob.vvpairUIntUInt() mappr.MapAll(lig.OBMol, isomorphs) else: isomorphs = pybel.ob.vpairUIntUInt() mappr.MapFirst(lig.OBMol, isomor...
def get_isomorphisms(reference, lig)
Get all isomorphisms of the ligand.
5.076545
4.794132
1.058908
atomorder = None # Get canonical atom order lig = pybel.ob.OBMol(lig.OBMol) if not preserve_bond_order: for bond in pybel.ob.OBMolBondIter(lig): if bond.GetBondOrder() != 1: bond.SetBondOrder(1) lig.DeleteData(pybel.ob.StereoData) lig = pybel.Molecule(li...
def canonicalize(lig, preserve_bond_order=False)
Get the canonical atom order for the ligand.
3.489999
3.363304
1.03767
dct = {} if int32 == 4294967295: # Special case in some structures (note, this is just a workaround) return -1 for i in range(-1000, -1): dct[np.uint32(i)] = i if int32 in dct: return dct[int32] else: return int32
def int32_to_negative(int32)
Checks if a suspicious number (e.g. ligand position) is in fact a negative number represented as a 32 bit integer and returns the actual number.
4.043468
3.71039
1.089769
pybel.ob.obErrorLog.StopLogging() # Suppress all OpenBabel warnings if os.name != 'nt': # Resource module not available for Windows maxsize = resource.getrlimit(resource.RLIMIT_STACK)[-1] resource.setrlimit(resource.RLIMIT_STACK, (min(2 ** 28, maxsize), maxsize)) sys.setrecursionlimit...
def read_pdb(pdbfname, as_string=False)
Reads a given PDB file and returns a Pybel Molecule.
4.889194
4.626408
1.056801
if os.path.splitext(fil)[-1] == '.gz': return gzip.open(fil, 'rb') elif os.path.splitext(fil)[-1] == '.zip': zf = zipfile.ZipFile(fil, 'r') return zf.open(zf.infolist()[0].filename) else: return open(fil, 'r')
def read(fil)
Returns a file handler and detects gzipped files.
1.793573
1.668548
1.07493
supported_formats = ['pdb'] # Fix for Windows-generated files: Remove carriage return characters if "\r" in path and as_string: path = path.replace('\r', '') for sformat in supported_formats: obc = pybel.ob.OBConversion() obc.SetInFormat(sformat) write_message("Dete...
def readmol(path, as_string=False)
Reads the given molecule file and returns the corresponding Pybel molecule as well as the input file type. In contrast to the standard Pybel implementation, the file is closed properly.
4.750866
4.635437
1.024901
# ANSI Escape Codes PINK_COL = '\x1b[35m' GREEN_COL = '\x1b[32m' RED_COL = '\x1b[31m' YELLOW_COL = '\x1b[33m' BLINK = '\x1b[5m' RESET = '\x1b[0m' if platform.system() != 'Windows': if blink: msg = BLINK + msg + RESET if color == 'yellow': ms...
def colorlog(msg, color, bold=False, blink=False)
Colors messages on non-Windows systems supporting ANSI escape.
1.792547
1.750901
1.023785
if (mtype == 'debug' and config.DEBUG) or (mtype != 'debug' and config.VERBOSE) or mtype == 'error': message(msg, indent=indent, mtype=mtype, caption=caption)
def write_message(msg, indent=False, mtype='standard', caption=False)
Writes message if verbose mode is set.
3.15766
3.042979
1.037687
if caption: msg = '\n' + msg + '\n' + '-'*len(msg) + '\n' if mtype == 'warning': msg = colorlog('Warning: ' + msg, 'yellow') if mtype == 'error': msg = colorlog('Error: ' + msg, 'red') if mtype == 'debug': msg = colorlog('Debug: ' + msg, 'pink') if mtype == 'i...
def message(msg, indent=False, mtype='standard', caption=False)
Writes messages in verbose mode
1.952711
1.961165
0.995689
bits = token.split_contents() obj_var, count, var_name, mods, finder = parse_related_tag(bits) return RelatedNode(obj_var, count, var_name, mods, finder)
def do_related(parser, token)
Get N related models into a context variable optionally specifying a named related finder. **Usage**:: {% related <limit>[ query_type] [app.model, ...] for <object> as <result> %} **Parameters**:: ================================== ===========================================...
5.005498
7.430182
0.673671
"add some content type info of self.target" if not model: model = publishable.content_type.model_class() box_class = model.box_class if box_class == PublishableBox: box_class = Box return box_class(publishable, box_type, nodelist, model=model)
def PublishableBox(publishable, box_type, nodelist, model=None)
add some content type info of self.target
5.46488
2.966569
1.842155
" Delegate the boxing to the target's Box class. " obj = listing.publishable return obj.box_class(obj, *args, **kwargs)
def ListingBox(listing, *args, **kwargs)
Delegate the boxing to the target's Box class.
15.123206
7.420099
2.038141
" Get object's URL. " category = self.category kwargs = { 'slug': self.slug, } if self.static: kwargs['id'] = self.pk if category.tree_parent_id: kwargs['category'] = category.tree_path url = reverse('static_de...
def get_absolute_url(self, domain=False)
Get object's URL.
2.917336
2.830529
1.030668
"Return True if the Publishable is currently active." cur_time = now() return self.published and cur_time > self.publish_from and \ (self.publish_to is None or cur_time < self.publish_to)
def is_published(self)
Return True if the Publishable is currently active.
5.701272
4.247252
1.342344
" Parse the parameters into a dict. " params = MultiValueDict() for line in text.split('\n'): pair = line.split(':', 1) if len(pair) == 2: params.appendlist(pair[0].strip(), pair[1].strip()) return params
def resolve_params(self, text)
Parse the parameters into a dict.
3.538936
3.05549
1.158222
self.params = {} # no params, not even a newline if not self.nodelist: return # just static text, no vars, assume one TextNode if not self.nodelist.contains_nontext: text = self.nodelist[0].s.strip() # vars in params, we have to render ...
def prepare(self, context)
Do the pre-processing - render and parse the parameters and store them for further use in self.params.
5.606721
5.211858
1.075763
" Get context to render the template. " return { 'content_type_name' : str(self.name), 'content_type_verbose_name' : self.verbose_name, 'content_type_verbose_name_plural' : self.verbose_name_plural, 'object' : self.obj, 'box...
def get_context(self)
Get context to render the template.
3.909336
3.588416
1.089432
self.prepare(context) " Cached wrapper around self._render(). " if getattr(settings, 'DOUBLE_RENDER', False) and self.can_double_render: if 'SECOND_RENDER' not in context: return self.double_render() key = self.get_cache_key() if key: rend ...
def render(self, context)
Cached wrapper around self._render().
4.222693
3.579582
1.179661
" Get the hierarchy of templates belonging to the object/box_type given. " t_list = [] if hasattr(self.obj, 'category_id') and self.obj.category_id: cat = self.obj.category base_path = 'box/category/%s/content_type/%s/' % (cat.path, self.name) if hasattr(self....
def _get_template_list(self)
Get the hierarchy of templates belonging to the object/box_type given.
2.411965
2.026831
1.190018
" The main function that takes care of the rendering. " if self.template_name: t = loader.get_template(self.template_name) else: t_list = self._get_template_list() t = loader.select_template(t_list) context.update(self.get_context()) resp = t....
def _render(self, context)
The main function that takes care of the rendering.
3.515968
2.981313
1.179336
" Return a cache key constructed from the box's parameters. " if not self.is_model: return None pars = '' if self.params: pars = ','.join(':'.join((smart_str(key), smart_str(self.params[key]))) for key in sorted(self.params.keys())) return normalize_key(...
def get_cache_key(self)
Return a cache key constructed from the box's parameters.
7.03121
5.711725
1.231013
"Override save() to construct tree_path based on the category's parent." old_tree_path = self.tree_path if self.tree_parent: if self.tree_parent.tree_path: self.tree_path = '%s/%s' % (self.tree_parent.tree_path, self.slug) else: self.tree_p...
def save(self, **kwargs)
Override save() to construct tree_path based on the category's parent.
2.849672
2.083506
1.367729
if not self.tree_parent_id: url = reverse('root_homepage') else: url = reverse('category_detail', kwargs={'category' : self.tree_path}) if self.site_id != settings.SITE_ID: # prepend the domain if it doesn't match current Site return 'http...
def get_absolute_url(self)
Returns absolute URL for the category.
5.096025
4.494264
1.133895
var_name, parameters = listing_parse(token.split_contents()) return ListingNode(var_name, parameters)
def listing(parser, token)
Tag that will obtain listing of top objects for a given category and store them in context under given name. Usage:: {% listing <limit>[ from <offset>][of <app.model>[, <app.model>[, ...]]][ for <category> ] [with children|descendents] [using listing_handler] as <result> %} Parameters: ======...
5.597157
12.818094
0.436661
bits = token.split_contents() nodelist = parser.parse(('end' + bits[0],)) parser.delete_first_token() return _parse_box(nodelist, bits)
def do_box(parser, token)
Tag Node representing our idea of a reusable box. It can handle multiple parameters in its body which will then be accessible via ``{{ box.params }}`` in the template being rendered. .. note:: The inside of the box will be rendered only when redering the box in current context and the ``obj...
3.001352
5.255298
0.57111
bits = token.split_contents() if len(bits) != 2: raise template.TemplateSyntaxError() return RenderNode(bits[1])
def do_render(parser, token)
Renders a rich-text field using defined markup. Example:: {% render some_var %}
2.684043
5.490298
0.48887
return text return '%sxxx' % m.group(1)
def ipblur(text): # brutalizer ;-) import re m = re.match(r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.)\d{1,3}.*', text) if not m
blurs IP address
11.162762
9.698962
1.150923
global INSTALLED_APPS_REGISTER mod_list = INSTALLED_APPS_REGISTER.get(app_name, []) if isinstance(modules, basestring): mod_list.append(modules) elif is_iterable(modules): mod_list.extend(modules) INSTALLED_APPS_REGISTER[app_name] = mod_list
def register(app_name, modules)
simple module registering for later usage we don't want to import admin.py in models.py
2.461436
2.527344
0.973922
for app in settings.INSTALLED_APPS: modules = set(auto_discover) if app in INSTALLED_APPS_REGISTER: modules.update(INSTALLED_APPS_REGISTER[app]) for module in modules: mod = import_module(app) try: import_module('%s.%s' % (app, module)...
def call_modules(auto_discover=())
this is called in project urls.py for registering desired modules (eg.: admin.py)
3.545628
3.439775
1.030773
related = [] # top objects in given category if count > 0: from ella.core.models import Listing cat = obj.category listings = Listing.objects.get_queryset_wrapper( category=cat, content_types=[ContentType.objects.get_for_model(m) for m in mods] ) ...
def related_by_category(obj, count, collected_so_far, mods=[], only_from_same_site=True)
Returns other Publishable objects related to ``obj`` by using the same category principle. Returns up to ``count`` objects.
4.740594
4.612127
1.027854
# manually entered dependencies qset = Related.objects.filter(publishable=obj) if mods: qset = qset.filter(related_ct__in=[ ContentType.objects.get_for_model(m).pk for m in mods]) return get_cached_objects(qset.values_list('related_ct', 'related_id')[:count], missing=SKIP)
def directly_related(obj, count, collected_so_far, mods=[], only_from_same_site=True)
Returns objects related to ``obj`` up to ``count`` by searching ``Related`` instances for the ``obj``.
6.384448
6.155228
1.03724
report = et.Element('report') plipversion = et.SubElement(report, 'plipversion') plipversion.text = __version__ date_of_creation = et.SubElement(report, 'date_of_creation') date_of_creation.text = time.strftime("%Y/%m/%d") citation_information = et.SubElement(rep...
def construct_xml_tree(self)
Construct the basic XML tree
2.860882
2.849778
1.003896
textlines = ['Prediction of noncovalent interactions for PDB structure %s' % self.mol.pymol_name.upper(), ] textlines.append("=" * len(textlines[0])) textlines.append('Created on %s using PLIP v%s\n' % (time.strftime("%Y/%m/%d"), __version__)) textlines.append('If you are using ...
def construct_txt_file(self)
Construct the header of the txt file
6.227614
6.101932
1.020597
for i, site in enumerate(sorted(self.mol.interaction_sets)): s = self.mol.interaction_sets[site] bindingsite = BindingSiteReport(s).generate_xml() bindingsite.set('id', str(i + 1)) bindingsite.set('has_interactions', 'False') self.xmlreport.in...
def get_bindingsite_data(self)
Get the additional data for the binding sites
4.448379
4.302264
1.033962
if not as_string: et.ElementTree(self.xmlreport).write('{}/{}.xml'.format(self.outpath, self.outputprefix), pretty_print=True, xml_declaration=True) else: output = et.tostring(self.xmlreport, pretty_print=True) if config.RAWSTRING: output = re...
def write_xml(self, as_string=False)
Write the XML report
4.073793
3.754067
1.085168
if not as_string: with open('{}/{}.txt'.format(self.outpath, self.outputprefix), 'w') as f: [f.write(textline + '\n') for textline in self.txtreport] else: output = '\n'.join(self.txtreport) if config.RAWSTRING: output = repr(o...
def write_txt(self, as_string=False)
Write the TXT report
4.293231
3.898379
1.101286
if not len(info) == 0: f.write('\n\n### %s ###\n' % name) f.write('%s\n' % '\t'.join(features)) for line in info: f.write('%s\n' % '\t'.join(map(str, line)))
def write_section(self, name, features, info, f)
Provides formatting for one section (e.g. hydrogen bonds)
2.606894
2.528591
1.030967
# Determine cell width for each column cell_dict = {} for i, row in enumerate(array): for j, val in enumerate(row): if j not in cell_dict: cell_dict[j] = [] cell_dict[j].append(val) for item in cell_dict: ...
def rst_table(self, array)
Given an array, the function formats and returns and table in rST format.
2.451727
2.412378
1.016311
txt = [] titletext = '%s (%s) - %s' % (self.bsid, self.longname, self.ligtype) txt.append(titletext) for i, member in enumerate(self.lig_members[1:]): txt.append(' + %s' % ":".join(str(element) for element in member)) txt.append("-" * len(titletext)) ...
def generate_txt(self)
Generates an flat text report for a single binding site
3.286023
3.219848
1.020552
return zip(itertools.repeat(function), sequence, itertools.repeat(kwargs))
def pool_args(function, sequence, kwargs)
Return a single iterator of n elements of lists of length 3, given a sequence of len n.
4.436876
3.843724
1.154317
def simple_parallel(func, sequence, **args): if 'processes' in args: processes = args.get('processes') del args['processes'] else: processes = multiprocessing.cpu_count() pool = multiprocessing.Pool(processes) # depends on available cores ...
def parallel_fn(f)
Simple wrapper function, returning a parallel version of the given function f. The function f must have one argument and may have an arbitray number of keyword arguments.
4.299459
4.368594
0.984174
if self.as_string: fil = self.pdbpath.rstrip('\n').split('\n') # Removing trailing newline character else: f = read(self.pdbpath) fil = f.readlines() f.close() corrected_lines = [] i, j = 0, 0 # idx and PDB numbering d = ...
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. ...
4.472701
4.188336
1.067894
conf1, id1, chain1, pos1 = line[16].strip(), line[17:20].strip(), line[21].strip(), int(line[22:26]) conf2, id2, chain2, pos2 = line[46].strip(), line[47:50].strip(), line[51].strip(), int(line[52:56]) return self.covlinkage(id1=id1, chain1=chain1, pos1=pos1, conf1=conf1, ...
def get_linkage(self, line)
Get the linkage information from a LINK entry PDB line.
2.186912
2.017919
1.083746
all_from_chain = [o for o in pybel.ob.OBResidueIter( self.proteincomplex.OBMol) if o.GetChain() == chain] # All residues from chain if len(all_from_chain) == 0: return None else: non_water = [o for o in all_from_chain if not o.GetResidueProperty(9)] ...
def getpeptides(self, chain)
If peptide ligand chains are defined via the command line options, try to extract the underlying ligand formed by all residues in the given chain without water
4.324294
3.896327
1.109838
if config.PEPTIDES == [] and config.INTRA is None: # Extract small molecule ligands (default) ligands = [] # Filter for ligands using lists ligand_residues, self.lignames_all, self.water = self.filter_for_ligands() all_res_dict = {(a.GetNam...
def getligs(self)
Get all ligands from a PDB file and prepare them for analysis. Returns all non-empty ligands.
5.27162
5.257302
1.002723
if not obres.GetResidueProperty(0): # If the residue is NOT amino (0) # It can be amino_nucleo, coenzme, ion, nucleo, protein, purine, pyrimidine, solvent # In these cases, it is a ligand candidate return True else: # Here, the residue...
def is_het_residue(self, obres)
Given an OBResidue, determines if the residue is indeed a possible ligand in the PDB file
6.739906
6.526641
1.032676
candidates1 = [o for o in pybel.ob.OBResidueIter( self.proteincomplex.OBMol) if not o.GetResidueProperty(9) and self.is_het_residue(o)] if config.DNARECEPTOR: # If DNA is the receptor, don't consider DNA as a ligand candidates1 = [res for res in candidates1 if res.Get...
def filter_for_ligands(self)
Given an OpenBabel Molecule, get all ligands, their names, and water
4.920717
4.832036
1.018353
# Remove all those not considered by ligands and pairings including alternate conformations ligdoubles = [[(link.id1, link.chain1, link.pos1), (link.id2, link.chain2, link.pos2)] for link in [c for c in self.covalent if c.id1 in self.lignames_kept a...
def identify_kmers(self, residues)
Using the covalent linkage information, find out which fragments/subunits form a ligand.
4.139615
4.012419
1.031701
mapped_idx = self.mapid(idx, 'reversed') return pybel.Atom(self.original_structure.GetAtom(mapped_idx))
def id_to_atom(self, idx)
Returns the atom for a given original ligand ID. To do this, the ID is mapped to the protein first and then the atom returned.
12.610376
8.775669
1.43697
atom_set = [] data = namedtuple('hydrophobic', 'atom orig_atom orig_idx') atm = [a for a in all_atoms if a.atomicnum == 6 and set([natom.GetAtomicNum() for natom in pybel.ob.OBAtomAtomIter(a.OBAtom)]).issubset( ...
def hydrophobic_atoms(self, all_atoms)
Select all carbon atoms which have only carbons and/or hydrogens as direct neighbors.
4.311481
4.114625
1.047843
data = namedtuple('hbondacceptor', 'a a_orig_atom a_orig_idx type') a_set = [] for atom in filter(lambda at: at.OBAtom.IsHbondAcceptor(), all_atoms): if atom.atomicnum not in [9, 17, 35, 53] and atom.idx not in self.altconf: # Exclude halogen atoms a_orig_id...
def find_hba(self, all_atoms)
Find all possible hydrogen bond acceptors
4.124291
3.961205
1.041171