project_name
stringlengths
6
104
file_name
stringlengths
4
89
full_name
stringlengths
1
102
func_name
stringlengths
1
85
docstring
stringlengths
13
836
docstring_tokens
listlengths
4
122
code
stringlengths
23
39.7k
code_tokens
stringlengths
29
44.6k
url
int64
3
986k
kukuruza/shuffler
testing.py
Test_DB.assert_properties_count_by_object
assert_properties_count_by_object
Check the number of properties grouped by objectid.
[ "Check", "the", "number", "of", "properties", "grouped", "by", "objectid." ]
def assert_properties_count_by_object(self, c, expected): self.verify_that_expected_is_a_list_of_ints(expected) c.execute('SELECT COUNT(p.objectid) FROM objects o LEFT OUTER JOIN properties p ON o.objectid = p.objectid GROUP BY o.objectid') actual = c.fetchall() expected = [(x,) for x in expected] s...
['def', 'assert_properties_count_by_object(self,', 'c,', 'expected):', 'self.verify_that_expected_is_a_list_of_ints(expected)', "c.execute('SELECT", 'COUNT(p.objectid)', 'FROM', 'objects', 'o', 'LEFT', 'OUTER', 'JOIN', 'properties', 'p', 'ON', 'o.objectid', '=', 'p.objectid', 'GROUP', 'BY', "o.objectid')", 'actual', '=...
933,924
jonathanking/sidechainnet
create.py
combine
combine
Supplements one entry in ProteinNet with sidechain information.
[ "Supplements", "one", "entry", "in", "ProteinNet", "with", "sidechain", "information." ]
def combine(pn_entry, sc_entry, aligner, pnid): sc_entry = manually_adjust_data(pnid, sc_entry) if needs_manual_adjustment(pnid): return ({}, 'needs manual adjustment') if pn_entry is None: seq = get_sequence_from_pnid(pnid) pn_entry = {'primary': seq, 'evolutionary': np.zeros((len(s...
['def', 'combine(pn_entry,', 'sc_entry,', 'aligner,', 'pnid):', 'sc_entry', '=', 'manually_adjust_data(pnid,', 'sc_entry)', 'if', 'needs_manual_adjustment(pnid):', 'return', '({},', "'needs", 'manual', "adjustment')", 'if', 'pn_entry', 'is', 'None:', 'seq', '=', 'get_sequence_from_pnid(pnid)', 'pn_entry', '=', "{'prima...
933,971
jonathanking/sidechainnet
create.py
combine_datasets
combine_datasets
Adds sidechain information to ProteinNet to create SidechainNet.
[ "Adds", "sidechain", "information", "to", "ProteinNet", "to", "create", "SidechainNet." ]
def combine_datasets(proteinnet_out, sc_data, thinning=100): print('Preparing to merge ProteinNet data with downloaded sidechain data.') pn_files = [os.path.join(proteinnet_out, f'training_{thinning}.pkl'), os.path.join(proteinnet_out, 'validation.pkl'), os.path.join(proteinnet_out, 'testing.pkl')] pn_data ...
['def', 'combine_datasets(proteinnet_out,', 'sc_data,', 'thinning=100):', "print('Preparing", 'to', 'merge', 'ProteinNet', 'data', 'with', 'downloaded', 'sidechain', "data.')", 'pn_files', '=', '[os.path.join(proteinnet_out,', "f'training_{thinning}.pkl'),", 'os.path.join(proteinnet_out,', "'validation.pkl'),", 'os.pat...
933,974
jonathanking/sidechainnet
create.py
get_tuple
get_tuple
Extract relevant SidechainNet and ProteinNet data from their respective dicts.
[ "Extract", "relevant", "SidechainNet", "and", "ProteinNet", "data", "from", "their", "respective", "dicts." ]
def get_tuple(pndata, scdata, pnid): try: return (pndata[pnid], scdata[pnid], pnid) except KeyError: return (None, scdata[pnid], pnid)
['def', 'get_tuple(pndata,', 'scdata,', 'pnid):', 'try:', 'return', '(pndata[pnid],', 'scdata[pnid],', 'pnid)', 'except', 'KeyError:', 'return', '(None,', 'scdata[pnid],', 'pnid)']
933,975
jonathanking/sidechainnet
create.py
get_proteinnet_ids
get_proteinnet_ids
Return a list of ProteinNet IDs for a given CASP version, split, and thinning.
[ "Return", "a", "list", "of", "ProteinNet", "IDs", "for", "a", "given", "CASP", "version,", "split,", "and", "thinning." ]
def get_proteinnet_ids(casp_version, split, thinning=None): import pandas global PNID_CSV_FILE if PNID_CSV_FILE is None: PNID_CSV_FILE = pandas.read_csv(pkg_resources.resource_filename('sidechainnet', 'resources/all_proteinnet_ids.csv')).set_index('pnid').astype(bool) validsplitnum = None if...
['def', 'get_proteinnet_ids(casp_version,', 'split,', 'thinning=None):', 'import', 'pandas', 'global', 'PNID_CSV_FILE', 'if', 'PNID_CSV_FILE', 'is', 'None:', 'PNID_CSV_FILE', '=', "pandas.read_csv(pkg_resources.resource_filename('sidechainnet',", "'resources/all_proteinnet_ids.csv')).set_index('pnid').astype(bool)", 'v...
933,979
jonathanking/sidechainnet
collate.py
get_collate_fn
get_collate_fn
Return a collate function for collating ProteinDataset batches.
[ "Return", "a", "collate", "function", "for", "collating", "ProteinDataset", "batches." ]
def get_collate_fn(aggregate_input, seqs_as_onehot=None): if seqs_as_onehot is None: if aggregate_input: seqs_as_onehot = True else: seqs_as_onehot = False if not seqs_as_onehot and aggregate_input: raise ValueError('Sequences must be represented as one-hot vector...
['def', 'get_collate_fn(aggregate_input,', 'seqs_as_onehot=None):', 'if', 'seqs_as_onehot', 'is', 'None:', 'if', 'aggregate_input:', 'seqs_as_onehot', '=', 'True', 'else:', 'seqs_as_onehot', '=', 'False', 'if', 'not', 'seqs_as_onehot', 'and', 'aggregate_input:', 'raise', "ValueError('Sequences", 'must', 'be', 'represen...
933,998
jonathanking/sidechainnet
SCNDataset.py
SCNDataset.get_protein_list_by_split_name
get_protein_list_by_split_name
Return list of SCNProtein objects belonging to str split_name.
[ "Return", "list", "of", "SCNProtein", "objects", "belonging", "to", "str", "split_name." ]
def get_protein_list_by_split_name(self, split_name): return [p for p in self if p.split == split_name]
['def', 'get_protein_list_by_split_name(self,', 'split_name):', 'return', '[p', 'for', 'p', 'in', 'self', 'if', 'p.split', '==', 'split_name]']
934,001
jonathanking/sidechainnet
SCNDataset.py
SCNDataset.filter_ids
filter_ids
Remove proteins whose IDs are not included in list to_keep.
[ "Remove", "proteins", "whose", "IDs", "are", "not", "included", "in", "list", "to_keep." ]
def filter_ids(self, to_keep): to_delete = [] for pnid in self.ids_to_SCNProtein.keys(): if pnid not in to_keep: to_delete.append(pnid) for pnid in to_delete: p = self.ids_to_SCNProtein[pnid] self.split_to_ids[p.split].remove(pnid) del self.ids_to_SCNProtein[pnid]...
['def', 'filter_ids(self,', 'to_keep):', 'to_delete', '=', '[]', 'for', 'pnid', 'in', 'self.ids_to_SCNProtein.keys():', 'if', 'pnid', 'not', 'in', 'to_keep:', 'to_delete.append(pnid)', 'for', 'pnid', 'in', 'to_delete:', 'p', '=', 'self.ids_to_SCNProtein[pnid]', 'self.split_to_ids[p.split].remove(pnid)', 'del', 'self.id...
934,002
jonathanking/sidechainnet
SCNDataset.py
SCNProtein.to_pdb
to_pdb
Save structure to path as a PDB file.
[ "Save", "structure", "to", "path", "as", "a", "PDB", "file." ]
def to_pdb(self, path, title=None): if not title: title = self.id if self.sb is None: if self._has_hydrogens: self.sb = sidechainnet.StructureBuilder(self.seq, self.hcoords) else: self.sb = sidechainnet.StructureBuilder(self.seq, self.coords) return self.sb.to...
['def', 'to_pdb(self,', 'path,', 'title=None):', 'if', 'not', 'title:', 'title', '=', 'self.id', 'if', 'self.sb', 'is', 'None:', 'if', 'self._has_hydrogens:', 'self.sb', '=', 'sidechainnet.StructureBuilder(self.seq,', 'self.hcoords)', 'else:', 'self.sb', '=', 'sidechainnet.StructureBuilder(self.seq,', 'self.coords)', '...
934,004
jonathanking/sidechainnet
SCNDataset.py
SCNProtein.num_missing
num_missing
Return number of missing residues.
[ "Return", "number", "of", "missing", "residues." ]
def num_missing(self): return self.mask.count('-')
['def', 'num_missing(self):', 'return', "self.mask.count('-')"]
934,005
jonathanking/sidechainnet
losses.py
rmsd
rmsd
Return the RMSD between two sets of coordinates.
[ "Return", "the", "RMSD", "between", "two", "sets", "of", "coordinates." ]
def rmsd(a, b): t = pr.calcTransformation(a, b) return pr.calcRMSD(t.apply(a), b)
['def', 'rmsd(a,', 'b):', 't', '=', 'pr.calcTransformation(a,', 'b)', 'return', 'pr.calcRMSD(t.apply(a),', 'b)']
934,010
jonathanking/sidechainnet
models.py
BaseProteinAngleRNN.forward
forward
Run one forward step of the model.
[ "Run", "one", "forward", "step", "of", "the", "model." ]
def forward(self, *args, **kwargs): raise NotImplementedError
['def', 'forward(self,', '*args,', '**kwargs):', 'raise', 'NotImplementedError']
934,013
jonathanking/sidechainnet
BatchedStructureBuilder.py
BatchedStructureBuilder.to_gltf
to_gltf
Save protein structure as a GLTF (3D-object) file to given path.
[ "Save", "protein", "structure", "as", "a", "GLTF", "(3D-object)", "file", "to", "given", "path." ]
def to_gltf(self, idx, path, title=None): if not 0 <= idx < len(self.structure_builders): raise ValueError('provided index is not available.') if idx in self.unbuildable_structures: self._missing_residue_error(idx) return self.structure_builders[idx].to_gltf(path, title)
['def', 'to_gltf(self,', 'idx,', 'path,', 'title=None):', 'if', 'not', '0', '<=', 'idx', '<', 'len(self.structure_builders):', 'raise', "ValueError('provided", 'index', 'is', 'not', "available.')", 'if', 'idx', 'in', 'self.unbuildable_structures:', 'self._missing_residue_error(idx)', 'return', 'self.structure_builders[...
934,020
jonathanking/sidechainnet
HydrogenBuilder.py
HydrogenBuilder.scale
scale
Scale a vector to match a given target length.
[ "Scale", "a", "vector", "to", "match", "a", "given", "target", "length." ]
def scale(self, vector, target_len, v_len=None): if v_len is None: v_len = self.norm(vector) return vector / v_len * target_len
['def', 'scale(self,', 'vector,', 'target_len,', 'v_len=None):', 'if', 'v_len', 'is', 'None:', 'v_len', '=', 'self.norm(vector)', 'return', 'vector', '/', 'v_len', '*', 'target_len']
934,023
jonathanking/sidechainnet
HydrogenBuilder.py
HydrogenBuilder.get_methylene_hydrogens
get_methylene_hydrogens
Place methylene hydrogens (R1-CH2-R2) on central Carbon.
[ "Place", "methylene", "hydrogens", "(R1-CH2-R2)", "on", "central", "Carbon." ]
def get_methylene_hydrogens(self, r1, carbon, r2): R1 = r1 - carbon R2 = r2 - carbon PV = self.cross(R1, R2) axis = R2 - R1 R = self.M(axis, METHYLENE_ANGLE) H1 = self.dot(R, PV) vector_len = self.norm(H1) H1 = self.scale(vector=H1, target_len=METHYLENE_LEN, v_len=vector_len) R = sel...
['def', 'get_methylene_hydrogens(self,', 'r1,', 'carbon,', 'r2):', 'R1', '=', 'r1', '-', 'carbon', 'R2', '=', 'r2', '-', 'carbon', 'PV', '=', 'self.cross(R1,', 'R2)', 'axis', '=', 'R2', '-', 'R1', 'R', '=', 'self.M(axis,', 'METHYLENE_ANGLE)', 'H1', '=', 'self.dot(R,', 'PV)', 'vector_len', '=', 'self.norm(H1)', 'H1', '=...
934,025
jonathanking/sidechainnet
HydrogenBuilder.py
HydrogenBuilder.pad_hydrogens
pad_hydrogens
Pad hydrogen list with empty vectors to the correct length for a given res.
[ "Pad", "hydrogen", "list", "with", "empty", "vectors", "to", "the", "correct", "length", "for", "a", "given", "res." ]
def pad_hydrogens(self, resname, hydrogens): pad_vec = [GLOBAL_PAD_CHAR * self.ones(3)] n_heavy_atoms = sum([True if an != 'PAD' else False for an in self.atom_map[resname]]) n_pad = NUM_COORDS_PER_RES_W_HYDROGENS - n_heavy_atoms - len(hydrogens) hydrogens.extend(pad_vec * n_pad) return hydrogens
['def', 'pad_hydrogens(self,', 'resname,', 'hydrogens):', 'pad_vec', '=', '[GLOBAL_PAD_CHAR', '*', 'self.ones(3)]', 'n_heavy_atoms', '=', 'sum([True', 'if', 'an', '!=', "'PAD'", 'else', 'False', 'for', 'an', 'in', 'self.atom_map[resname]])', 'n_pad', '=', 'NUM_COORDS_PER_RES_W_HYDROGENS', '-', 'n_heavy_atoms', '-', 'le...
934,027
jonathanking/sidechainnet
HydrogenBuilder.py
HydrogenBuilder.get_hydrogens_for_res
get_hydrogens_for_res
Return a padded array of hydrogens for a given res name & atom coord tuple.
[ "Return", "a", "padded", "array", "of", "hydrogens", "for", "a", "given", "res", "name", "&", "atom", "coord", "tuple." ]
def get_hydrogens_for_res(self, resname, c, prevc, n_terminal=False, c_terminal=False): hs = [] if n_terminal: (h, h2, h3) = self.get_methyl_hydrogens(c.N, c.CA, c.C, use_amine_length=True) self.terminal_atoms.update({'H2': h2, 'H3': h3}) hs.append(h) if c_terminal: oxt = sel...
['def', 'get_hydrogens_for_res(self,', 'resname,', 'c,', 'prevc,', 'n_terminal=False,', 'c_terminal=False):', 'hs', '=', '[]', 'if', 'n_terminal:', '(h,', 'h2,', 'h3)', '=', 'self.get_methyl_hydrogens(c.N,', 'c.CA,', 'c.C,', 'use_amine_length=True)', "self.terminal_atoms.update({'H2':", 'h2,', "'H3':", 'h3})', 'hs.appe...
934,048
jonathanking/sidechainnet
structure.py
angles_to_coords
angles_to_coords
Convert torsional angles to coordinates.
[ "Convert", "torsional", "angles", "to", "coordinates." ]
def angles_to_coords(angles, seq, remove_batch_padding=False): (pred_ang, input_seq) = (angles, seq) if remove_batch_padding: batch_mask = input_seq.ne(VOCAB.pad_id) input_seq = input_seq[batch_mask] return generate_coords(pred_ang, input_seq, torch.device('cpu'))
['def', 'angles_to_coords(angles,', 'seq,', 'remove_batch_padding=False):', '(pred_ang,', 'input_seq)', '=', '(angles,', 'seq)', 'if', 'remove_batch_padding:', 'batch_mask', '=', 'input_seq.ne(VOCAB.pad_id)', 'input_seq', '=', 'input_seq[batch_mask]', 'return', 'generate_coords(pred_ang,', 'input_seq,', "torch.device('...
934,049
jonathanking/sidechainnet
structure.py
determine_missing_positions
determine_missing_positions
Uses GLOBAL_PAD_CHAR to determine location of missing atoms or residues.
[ "Uses", "GLOBAL_PAD_CHAR", "to", "determine", "location", "of", "missing", "atoms", "or", "residues." ]
def determine_missing_positions(ang_or_coord_matrix): raise NotImplementedError
['def', 'determine_missing_positions(ang_or_coord_matrix):', 'raise', 'NotImplementedError']
934,054
jonathanking/sidechainnet
structure.py
trig_transform
trig_transform
Expand the last dimension of an angle tensor to have sin/cos values.
[ "Expand", "the", "last", "dimension", "of", "an", "angle", "tensor", "to", "have", "sin/cos", "values." ]
def trig_transform(t): new_t = torch.zeros(*t.shape, 2) if len(new_t.shape) == 4: new_t[:, :, :, 0] = torch.cos(t) new_t[:, :, :, 1] = torch.sin(t) else: raise ValueError('trig_transform function is only defined for (batch x L x num_angle) tensors.') return new_t
['def', 'trig_transform(t):', 'new_t', '=', 'torch.zeros(*t.shape,', '2)', 'if', 'len(new_t.shape)', '==', '4:', 'new_t[:,', ':,', ':,', '0]', '=', 'torch.cos(t)', 'new_t[:,', ':,', ':,', '1]', '=', 'torch.sin(t)', 'else:', 'raise', "ValueError('trig_transform", 'function', 'is', 'only', 'defined', 'for', '(batch', 'x'...
934,057
jonathanking/sidechainnet
structure.py
compare_pdb_files
compare_pdb_files
Returns the RMSD between two PDB files of the same protein.
[ "Returns", "the", "RMSD", "between", "two", "PDB", "files", "of", "the", "same", "protein." ]
def compare_pdb_files(file1, file2): s1 = pr.parsePDB(file1) s2 = pr.parsePDB(file2) transformation = pr.calcTransformation(s1, s2) s1_aligned = transformation.apply(s1) return pr.calcRMSD(s1_aligned, s2)
['def', 'compare_pdb_files(file1,', 'file2):', 's1', '=', 'pr.parsePDB(file1)', 's2', '=', 'pr.parsePDB(file2)', 'transformation', '=', 'pr.calcTransformation(s1,', 's2)', 's1_aligned', '=', 'transformation.apply(s1)', 'return', 'pr.calcRMSD(s1_aligned,', 's2)']
934,058
jonathanking/sidechainnet
StructureBuilder.py
StructureBuilder.add_hydrogens
add_hydrogens
Add Hydrogen atom coordinates to coordinate representation (re-apply PADs).
[ "Add", "Hydrogen", "atom", "coordinates", "to", "coordinate", "representation", "(re-apply", "PADs)." ]
def add_hydrogens(self): if self.coords is None or not len(self.coords): raise ValueError('Cannot add hydrogens to a structure whose heavy atoms have not yet been built.') self.hb = HydrogenBuilder(self.seq_as_str, self.coords) self.coords = self.hb.build_hydrogens() self.has_hydrogens = True ...
['def', 'add_hydrogens(self):', 'if', 'self.coords', 'is', 'None', 'or', 'not', 'len(self.coords):', 'raise', "ValueError('Cannot", 'add', 'hydrogens', 'to', 'a', 'structure', 'whose', 'heavy', 'atoms', 'have', 'not', 'yet', 'been', "built.')", 'self.hb', '=', 'HydrogenBuilder(self.seq_as_str,', 'self.coords)', 'self.c...
934,062
jonathanking/sidechainnet
StructureBuilder.py
StructureBuilder.to_pdb
to_pdb
Save protein structure as a PDB file to given path.
[ "Save", "protein", "structure", "as", "a", "PDB", "file", "to", "given", "path." ]
def to_pdb(self, path, title='pred'): self._initialize_coordinates_and_PdbCreator() self.pdb_creator.save_pdb(path, title)
['def', 'to_pdb(self,', 'path,', "title='pred'):", 'self._initialize_coordinates_and_PdbCreator()', 'self.pdb_creator.save_pdb(path,', 'title)']
934,063
jonathanking/sidechainnet
StructureBuilder.py
StructureBuilder.to_pdbstr
to_pdbstr
Return protein structure as a PDB string.
[ "Return", "protein", "structure", "as", "a", "PDB", "string." ]
def to_pdbstr(self, title='pred'): self._initialize_coordinates_and_PdbCreator() return self.pdb_creator.get_pdb_string(title)
['def', 'to_pdbstr(self,', "title='pred'):", 'self._initialize_coordinates_and_PdbCreator()', 'return', 'self.pdb_creator.get_pdb_string(title)']
934,064
jonathanking/sidechainnet
StructureBuilder.py
ResidueBuilder.AA
AA
Return the one-letter amino acid code (str) for this residue.
[ "Return", "the", "one-letter", "amino", "acid", "code", "(str)", "for", "this", "residue." ]
def AA(self): return VOCAB.int2char(int(self.name))
['def', 'AA(self):', 'return', 'VOCAB.int2char(int(self.name))']
934,067
jonathanking/sidechainnet
StructureBuilder.py
ResidueBuilder.build
build
Construct and return atomic coordinates for this protein.
[ "Construct", "and", "return", "atomic", "coordinates", "for", "this", "protein." ]
def build(self): self.build_bb() self.build_sc() return self._stack_coords()
['def', 'build(self):', 'self.build_bb()', 'self.build_sc()', 'return', 'self._stack_coords()']
934,068
jonathanking/sidechainnet
align.py
init_basic_aligner
init_basic_aligner
Returns an aligner with minimal assumptions about gaps.
[ "Returns", "an", "aligner", "with", "minimal", "assumptions", "about", "gaps." ]
def init_basic_aligner(allow_mismatches=False): a = Align.PairwiseAligner() if allow_mismatches: a.mismatch_score = -1 a.gap_score = -3 a.target_gap_score = -np.inf if not allow_mismatches: a.mismatch = -np.inf a.mismatch_score = -np.inf return a
['def', 'init_basic_aligner(allow_mismatches=False):', 'a', '=', 'Align.PairwiseAligner()', 'if', 'allow_mismatches:', 'a.mismatch_score', '=', '-1', 'a.gap_score', '=', '-3', 'a.target_gap_score', '=', '-np.inf', 'if', 'not', 'allow_mismatches:', 'a.mismatch', '=', '-np.inf', 'a.mismatch_score', '=', '-np.inf', 'retur...
934,073
jonathanking/sidechainnet
align.py
get_mask_from_alignment
get_mask_from_alignment
For a single alignment, return the mask as a string of '+' and '-'s.
[ "For", "a", "single", "alignment,", "return", "the", "mask", "as", "a", "string", "of", "'+'", "and", "'-'s." ]
def get_mask_from_alignment(al): alignment_str = str(al).split('\n')[1] return alignment_str.replace('|', '+')
['def', 'get_mask_from_alignment(al):', 'alignment_str', '=', "str(al).split('\\n')[1]", 'return', "alignment_str.replace('|',", "'+')"]
934,075
jonathanking/sidechainnet
align.py
get_padded_second_seq_from_alignment
get_padded_second_seq_from_alignment
For a single alignment, return the second padded string.
[ "For", "a", "single", "alignment,", "return", "the", "second", "padded", "string." ]
def get_padded_second_seq_from_alignment(al): alignment_str = str(al).split('\n')[2] return alignment_str
['def', 'get_padded_second_seq_from_alignment(al):', 'alignment_str', '=', "str(al).split('\\n')[2]", 'return', 'alignment_str']
934,076
jonathanking/sidechainnet
align.py
locate_char
locate_char
Returns a list of indices of character c in string s.
[ "Returns", "a", "list", "of", "indices", "of", "character", "c", "in", "string", "s." ]
def locate_char(c, s): return [i for (i, l) in enumerate(s) if l == c]
['def', 'locate_char(c,', 's):', 'return', '[i', 'for', '(i,', 'l)', 'in', 'enumerate(s)', 'if', 'l', '==', 'c]']
934,077
jonathanking/sidechainnet
align.py
shorten_ends
shorten_ends
Shortens s1 by removing characters at either end that don't match s2.
[ "Shortens", "s1", "by", "removing", "characters", "at", "either", "end", "that", "don't", "match", "s2." ]
def shorten_ends(s1, s2, s1_ang, s1_crd, s1_raw_seq, s1_ismodified): aligner = init_aligner(allow_target_gaps=True) a = aligner.align(s1, s2) mask = get_padded_second_seq_from_alignment(a[0]) i = len(mask) - 1 while mask[i] == '-': s1 = s1[:-1] s1_ang = s1_ang[:-1] s1_crd = s...
['def', 'shorten_ends(s1,', 's2,', 's1_ang,', 's1_crd,', 's1_raw_seq,', 's1_ismodified):', 'aligner', '=', 'init_aligner(allow_target_gaps=True)', 'a', '=', 'aligner.align(s1,', 's2)', 'mask', '=', 'get_padded_second_seq_from_alignment(a[0])', 'i', '=', 'len(mask)', '-', '1', 'while', 'mask[i]', '==', "'-':", 's1', '='...
934,079
jonathanking/sidechainnet
align.py
other_alignments_with_same_score
other_alignments_with_same_score
Returns True if there are other alignments with identical scores.
[ "Returns", "True", "if", "there", "are", "other", "alignments", "with", "identical", "scores." ]
def other_alignments_with_same_score(all_alignments, cur_alignment_idx, cur_alignment_score): if len(all_alignments) <= 1: return False for (i, a0) in enumerate(all_alignments): if i > 0 and a0.score < cur_alignment_score: break if i == cur_alignment_idx: continue...
['def', 'other_alignments_with_same_score(all_alignments,', 'cur_alignment_idx,', 'cur_alignment_score):', 'if', 'len(all_alignments)', '<=', '1:', 'return', 'False', 'for', '(i,', 'a0)', 'in', 'enumerate(all_alignments):', 'if', 'i', '>', '0', 'and', 'a0.score', '<', 'cur_alignment_score:', 'break', 'if', 'i', '==', '...
934,081
jonathanking/sidechainnet
align.py
coordinate_iterator
coordinate_iterator
Iterates over coordinates in a numpy array grouped by residue.
[ "Iterates", "over", "coordinates", "in", "a", "numpy", "array", "grouped", "by", "residue." ]
def coordinate_iterator(coords, atoms_per_res): assert len(coords) % atoms_per_res == 0, f'There must be {atoms_per_res} atoms for every residue.\nlen(coords) = {len(coords)}' i = 0 while i + atoms_per_res <= len(coords): yield coords[i:i + atoms_per_res] i += atoms_per_res
['def', 'coordinate_iterator(coords,', 'atoms_per_res):', 'assert', 'len(coords)', '%', 'atoms_per_res', '==', '0,', "f'There", 'must', 'be', '{atoms_per_res}', 'atoms', 'for', 'every', 'residue.\\nlen(coords)', '=', "{len(coords)}'", 'i', '=', '0', 'while', 'i', '+', 'atoms_per_res', '<=', 'len(coords):', 'yield', 'co...
934,083
jonathanking/sidechainnet
align.py
expand_data_with_mask
expand_data_with_mask
Uses mask to expand data as necessary.
[ "Uses", "mask", "to", "expand", "data", "as", "necessary." ]
def expand_data_with_mask(data, mask): if (isinstance(data, str) or isinstance(data, list)) and mask.count('-') == 0 and (len(data) == len(mask)) or (not isinstance(data, str) and mask.count('-') == 0 and (data.shape[0] == len(mask))): return data if isinstance(data, str): size = len(data) ...
['def', 'expand_data_with_mask(data,', 'mask):', 'if', '(isinstance(data,', 'str)', 'or', 'isinstance(data,', 'list))', 'and', "mask.count('-')", '==', '0', 'and', '(len(data)', '==', 'len(mask))', 'or', '(not', 'isinstance(data,', 'str)', 'and', "mask.count('-')", '==', '0', 'and', '(data.shape[0]', '==', 'len(mask)))...
934,084
jonathanking/sidechainnet
align.py
pad_seq_with_mask
pad_seq_with_mask
Given a shorter sequence, expands it to match the padding in mask.
[ "Given", "a", "shorter", "sequence,", "expands", "it", "to", "match", "the", "padding", "in", "mask." ]
def pad_seq_with_mask(seq, mask): seq_iter = iter(seq) new_seq = '' for m in mask: if m == '+': new_seq += next(seq_iter) elif m == '-': new_seq += '-' return new_seq
['def', 'pad_seq_with_mask(seq,', 'mask):', 'seq_iter', '=', 'iter(seq)', 'new_seq', '=', "''", 'for', 'm', 'in', 'mask:', 'if', 'm', '==', "'+':", 'new_seq', '+=', 'next(seq_iter)', 'elif', 'm', '==', "'-':", 'new_seq', '+=', "'-'", 'return', 'new_seq']
934,085
jonathanking/sidechainnet
download.py
download_sidechain_data
download_sidechain_data
Download the sidechain data for the corresponding ProteinNet IDs.
[ "Download", "the", "sidechain", "data", "for", "the", "corresponding", "ProteinNet", "IDs." ]
def download_sidechain_data(pnids, sidechainnet_out_dir, casp_version, thinning, limit, proteinnet_in, regenerate_scdata=False, output_name=None): from sidechainnet.utils.organize import load_data, save_data global PROTEINNET_IN_DIR PROTEINNET_IN_DIR = proteinnet_in if output_name is None: outpu...
['def', 'download_sidechain_data(pnids,', 'sidechainnet_out_dir,', 'casp_version,', 'thinning,', 'limit,', 'proteinnet_in,', 'regenerate_scdata=False,', 'output_name=None):', 'from', 'sidechainnet.utils.organize', 'import', 'load_data,', 'save_data', 'global', 'PROTEINNET_IN_DIR', 'PROTEINNET_IN_DIR', '=', 'proteinnet_...
934,087
jonathanking/sidechainnet
download.py
get_sequence_from_pdbid
get_sequence_from_pdbid
Use RSCB PDB's API to download the sequence for a PDB ID and chain.
[ "Use", "RSCB", "PDB's", "API", "to", "download", "the", "sequence", "for", "a", "PDB", "ID", "and", "chain." ]
def get_sequence_from_pdbid(pdbid, chain): entity = 1 query_string = f'https://data.rcsb.org/rest/v1/core/polymer_entity/{pdbid}/{entity}' r = requests.get(query_string) if r.status_code != 200: res = None while True: query_string = f'https://data.rcsb.org/rest/v1/core/polymer_entity...
['def', 'get_sequence_from_pdbid(pdbid,', 'chain):', 'entity', '=', '1', 'query_string', '=', "f'https://data.rcsb.org/rest/v1/core/polymer_entity/{pdbid}/{entity}'", 'r', '=', 'requests.get(query_string)', 'if', 'r.status_code', '!=', '200:', 'res', '=', 'None', 'while', 'True:', 'query_string', '=', "f'https://data.r...
934,098
jonathanking/sidechainnet
download.py
get_pdbid_from_pnid
get_pdbid_from_pnid
Return RCSB PDB ID associated with a given ProteinNet ID.
[ "Return", "RCSB", "PDB", "ID", "associated", "with", "a", "given", "ProteinNet", "ID." ]
def get_pdbid_from_pnid(pnid, return_chain=False, include_is_astral=False): chid = None is_astral = False try: (pdbid, chnum, chid) = pnid.split('_') chnum = int(chnum) if '#' in pdbid: pdbid = pdbid.split('#')[1] except ValueError: try: (pdbid, as...
['def', 'get_pdbid_from_pnid(pnid,', 'return_chain=False,', 'include_is_astral=False):', 'chid', '=', 'None', 'is_astral', '=', 'False', 'try:', '(pdbid,', 'chnum,', 'chid)', '=', "pnid.split('_')", 'chnum', '=', 'int(chnum)', 'if', "'#'", 'in', 'pdbid:', 'pdbid', '=', "pdbid.split('#')[1]", 'except', 'ValueError:', 't...
934,102
jonathanking/sidechainnet
download.py
get_resolution_from_pnid
get_resolution_from_pnid
Return RCSB-reported resolution for a given ProteinNet identifier.
[ "Return", "RCSB-reported", "resolution", "for", "a", "given", "ProteinNet", "identifier." ]
def get_resolution_from_pnid(pnid): if determine_pnid_type(pnid) == 'test': return None return get_resolution_from_pdbid(get_pdbid_from_pnid(pnid))
['def', 'get_resolution_from_pnid(pnid):', 'if', 'determine_pnid_type(pnid)', '==', "'test':", 'return', 'None', 'return', 'get_resolution_from_pdbid(get_pdbid_from_pnid(pnid))']
934,103
jonathanking/sidechainnet
errors.py
ProteinErrors.count
count
Create a record of a certain PNID exhibiting a certain error.
[ "Create", "a", "record", "of", "a", "certain", "PNID", "exhibiting", "a", "certain", "error." ]
def count(self, ec, pnid): if not self.counts: self.counts = {ec: [] for ec in self.name_to_code.values()} self.counts[ec].append(pnid)
['def', 'count(self,', 'ec,', 'pnid):', 'if', 'not', 'self.counts:', 'self.counts', '=', '{ec:', '[]', 'for', 'ec', 'in', 'self.name_to_code.values()}', 'self.counts[ec].append(pnid)']
934,106
jonathanking/sidechainnet
errors.py
ProteinErrors.summarize
summarize
Print a summary of all errors that have been recorded.
[ "Print", "a", "summary", "of", "all", "errors", "that", "have", "been", "recorded." ]
def summarize(self, total_processed=None): if not self.counts: print('No errors recorded.') return print('The following errors occurred:') self.error_codes_inv = {v: k for (k, v) in self.name_to_code.items()} for (error_code, count_list) in self.counts.items(): if len(count_list)...
['def', 'summarize(self,', 'total_processed=None):', 'if', 'not', 'self.counts:', "print('No", 'errors', "recorded.')", 'return', "print('The", 'following', 'errors', "occurred:')", 'self.error_codes_inv', '=', '{v:', 'k', 'for', '(k,', 'v)', 'in', 'self.name_to_code.items()}', 'for', '(error_code,', 'count_list)', 'in...
934,107
jonathanking/sidechainnet
errors.py
ProteinErrors.get_pnids_with_error_name
get_pnids_with_error_name
After counting, returns a list of pnids that have failed with a specified error code.
[ "After", "counting,", "returns", "a", "list", "of", "pnids", "that", "have", "failed", "with", "a", "specified", "error", "code." ]
def get_pnids_with_error_name(self, error_name): error_code = self[error_name] return self.counts[error_code]
['def', 'get_pnids_with_error_name(self,', 'error_name):', 'error_code', '=', 'self[error_name]', 'return', 'self.counts[error_code]']
934,108
jonathanking/sidechainnet
errors.py
ProteinErrors.get_error_name_from_code
get_error_name_from_code
Returns the error name for the associated code.
[ "Returns", "the", "error", "name", "for", "the", "associated", "code." ]
def get_error_name_from_code(self, code): return self.code_to_name[code]
['def', 'get_error_name_from_code(self,', 'code):', 'return', 'self.code_to_name[code]']
934,111
jonathanking/sidechainnet
manual_adjustment.py
needs_manual_adjustment
needs_manual_adjustment
Declares a list of pnids that should be handled manually due to eggregious differences between observed and expected seqeuences and masks.
[ "Declares", "a", "list", "of", "pnids", "that", "should", "be", "handled", "manually", "due", "to", "eggregious", "differences", "between", "observed", "and", "expected", "seqeuences", "and", "masks." ]
def needs_manual_adjustment(pnid): return pnid in ['4PGI_1_A', '3CMG_1_A', '4ARW_1_A', '4Z08_1_A', '2PLV_1_1', '4PG7_1_A', '2O24_1_A', '5I4N_1_A', '4RYK_1_A', '1CS4_3_C', '3SRY_1_A', '2AV4_1_A', '3GW7_1_A', '1TQ5_1_A', '5DND_1_A', '4YCU_1_A', '1VRZ_1_A', '1RRX_1_A', '2XUV_1_A', '2CFO_1_A', '5DNC_1_A', '2WTS_1_A', '...
['def', 'needs_manual_adjustment(pnid):', 'return', 'pnid', 'in', "['4PGI_1_A',", "'3CMG_1_A',", "'4ARW_1_A',", "'4Z08_1_A',", "'2PLV_1_1',", "'4PG7_1_A',", "'2O24_1_A',", "'5I4N_1_A',", "'4RYK_1_A',", "'1CS4_3_C',", "'3SRY_1_A',", "'2AV4_1_A',", "'3GW7_1_A',", "'1TQ5_1_A',", "'5DND_1_A',", "'4YCU_1_A',", "'1VRZ_1_A',"...
934,116
jonathanking/sidechainnet
manual_adjustment.py
manually_adjust_data
manually_adjust_data
Returns a modified version of sc_entry to fix some issues manually.
[ "Returns", "a", "modified", "version", "of", "sc_entry", "to", "fix", "some", "issues", "manually." ]
def manually_adjust_data(pnid, sc_entry): if '5FXN' in pnid and len(sc_entry['seq']) == 316 and (sc_entry['seq'][-3:] == 'VVK'): sc_entry['seq'] = sc_entry['seq'][:-2] sc_entry['ang'] = sc_entry['ang'][:-2] sc_entry['crd'] = sc_entry['crd'][:-NUM_COORDS_PER_RES * 2] return sc_entry
['def', 'manually_adjust_data(pnid,', 'sc_entry):', 'if', "'5FXN'", 'in', 'pnid', 'and', "len(sc_entry['seq'])", '==', '316', 'and', "(sc_entry['seq'][-3:]", '==', "'VVK'):", "sc_entry['seq']", '=', "sc_entry['seq'][:-2]", "sc_entry['ang']", '=', "sc_entry['ang'][:-2]", "sc_entry['crd']", '=', "sc_entry['crd'][:-NUM_CO...
934,117
jonathanking/sidechainnet
measure.py
determine_sidechain_atomnames
determine_sidechain_atomnames
Given a residue from ProDy, returns a list of sidechain atom names that must be recorded.
[ "Given", "a", "residue", "from", "ProDy,", "returns", "a", "list", "of", "sidechain", "atom", "names", "that", "must", "be", "recorded." ]
def determine_sidechain_atomnames(_res): if _res.getResname() in SC_BUILD_INFO.keys(): return SC_BUILD_INFO[_res.getResname()]['atom-names'] else: raise NonStandardAminoAcidError
['def', 'determine_sidechain_atomnames(_res):', 'if', '_res.getResname()', 'in', 'SC_BUILD_INFO.keys():', 'return', "SC_BUILD_INFO[_res.getResname()]['atom-names']", 'else:', 'raise', 'NonStandardAminoAcidError']
934,120
jonathanking/sidechainnet
measure.py
measure_res_coordinates
measure_res_coordinates
Given a ProDy residue, measure all relevant coordinates.
[ "Given", "a", "ProDy", "residue,", "measure", "all", "relevant", "coordinates." ]
def measure_res_coordinates(_res): sc_atom_names = determine_sidechain_atomnames(_res) bbcoords = get_atom_coords_by_names(_res, ['N', 'CA', 'C', 'O']) sccoords = get_atom_coords_by_names(_res, sc_atom_names) coord_padding = np.zeros((NUM_COORDS_PER_RES - len(bbcoords) - len(sccoords), 3)) coord_pad...
['def', 'measure_res_coordinates(_res):', 'sc_atom_names', '=', 'determine_sidechain_atomnames(_res)', 'bbcoords', '=', 'get_atom_coords_by_names(_res,', "['N',", "'CA',", "'C',", "'O'])", 'sccoords', '=', 'get_atom_coords_by_names(_res,', 'sc_atom_names)', 'coord_padding', '=', 'np.zeros((NUM_COORDS_PER_RES', '-', 'le...
934,123
jonathanking/sidechainnet
measure.py
replace_nonstdaas
replace_nonstdaas
Replace the non-standard Amino Acids in a list with their equivalents.
[ "Replace", "the", "non-standard", "Amino", "Acids", "in", "a", "list", "with", "their", "equivalents." ]
def replace_nonstdaas(residues): replacements = ALLOWED_NONSTD_RESIDUES is_nonstd = [] resnames = [] for r in residues: rname = r.getResname() if rname in replacements.keys(): r.setResname(replacements[rname]) is_nonstd.append(1) else: is_nonst...
['def', 'replace_nonstdaas(residues):', 'replacements', '=', 'ALLOWED_NONSTD_RESIDUES', 'is_nonstd', '=', '[]', 'resnames', '=', '[]', 'for', 'r', 'in', 'residues:', 'rname', '=', 'r.getResname()', 'if', 'rname', 'in', 'replacements.keys():', 'r.setResname(replacements[rname])', 'is_nonstd.append(1)', 'else:', 'is_nons...
934,124
jonathanking/sidechainnet
measure.py
get_resname_as_int
get_resname_as_int
Return the integer represenation of a given residue name.
[ "Return", "the", "integer", "represenation", "of", "a", "given", "residue", "name." ]
def get_resname_as_int(resname): from sidechainnet.utils.sequence import THREE_TO_ONE_LETTER_MAP, VOCAB return VOCAB._char2int[THREE_TO_ONE_LETTER_MAP[resname]]
['def', 'get_resname_as_int(resname):', 'from', 'sidechainnet.utils.sequence', 'import', 'THREE_TO_ONE_LETTER_MAP,', 'VOCAB', 'return', 'VOCAB._char2int[THREE_TO_ONE_LETTER_MAP[resname]]']
934,127
jonathanking/sidechainnet
measure.py
no_nans_infs_allzeros
no_nans_infs_allzeros
Returns true if a matrix does not contain NaNs, infs, or all 0s.
[ "Returns", "true", "if", "a", "matrix", "does", "not", "contain", "NaNs,", "infs,", "or", "all", "0s." ]
def no_nans_infs_allzeros(matrix): return not np.any(np.isinf(matrix)) and np.any(matrix)
['def', 'no_nans_infs_allzeros(matrix):', 'return', 'not', 'np.any(np.isinf(matrix))', 'and', 'np.any(matrix)']
934,128
jonathanking/sidechainnet
measure.py
measure_bond_angles
measure_bond_angles
Given a residue, measure the ncac, cacn, and cnca bond angles.
[ "Given", "a", "residue,", "measure", "the", "ncac,", "cacn,", "and", "cnca", "bond", "angles." ]
def measure_bond_angles(residue, res_idx, all_res): if res_idx == len(all_res) - 1: next_res = None else: next_res = all_res[res_idx + 1] return list(get_bond_angles(residue, next_res))
['def', 'measure_bond_angles(residue,', 'res_idx,', 'all_res):', 'if', 'res_idx', '==', 'len(all_res)', '-', '1:', 'next_res', '=', 'None', 'else:', 'next_res', '=', 'all_res[res_idx', '+', '1]', 'return', 'list(get_bond_angles(residue,', 'next_res))']
934,131
jonathanking/sidechainnet
measure.py
measure_phi_psi_omega
measure_phi_psi_omega
Measures a residue's primary backbone torsional angles (phi, psi, omega).
[ "Measures", "a", "residue's", "primary", "backbone", "torsional", "angles", "(phi,", "psi,", "omega)." ]
def measure_phi_psi_omega(residue, include_OXT=False, last_res=False): try: phi = pr.calcPhi(residue, radian=True) except ValueError: phi = GLOBAL_PAD_CHAR try: if last_res: psi = compute_single_dihedral([residue.select('name ' + an) for an in 'N CA C O'.split()]) ...
['def', 'measure_phi_psi_omega(residue,', 'include_OXT=False,', 'last_res=False):', 'try:', 'phi', '=', 'pr.calcPhi(residue,', 'radian=True)', 'except', 'ValueError:', 'phi', '=', 'GLOBAL_PAD_CHAR', 'try:', 'if', 'last_res:', 'psi', '=', "compute_single_dihedral([residue.select('name", "'", '+', 'an)', 'for', 'an', 'in...
934,132
jonathanking/sidechainnet
measure.py
compute_single_dihedral
compute_single_dihedral
Given 4 Atoms, calculate the dihedral angle between them in radians.
[ "Given", "4", "Atoms,", "calculate", "the", "dihedral", "angle", "between", "them", "in", "radians." ]
def compute_single_dihedral(atoms): if None in atoms: return GLOBAL_PAD_CHAR else: atoms = [a.getCoords()[0] for a in atoms] return get_dihedral(atoms[0], atoms[1], atoms[2], atoms[3], radian=True)
['def', 'compute_single_dihedral(atoms):', 'if', 'None', 'in', 'atoms:', 'return', 'GLOBAL_PAD_CHAR', 'else:', 'atoms', '=', '[a.getCoords()[0]', 'for', 'a', 'in', 'atoms]', 'return', 'get_dihedral(atoms[0],', 'atoms[1],', 'atoms[2],', 'atoms[3],', 'radian=True)']
934,133
jonathanking/sidechainnet
organize.py
validate_data_dict
validate_data_dict
Performs several sanity checks on the data dict before saving.
[ "Performs", "several", "sanity", "checks", "on", "the", "data", "dict", "before", "saving." ]
def validate_data_dict(data): from sidechainnet.utils.download import VALID_SPLITS train_len = len(data['train']['seq']) test_len = len(data['test']['seq']) items_recorded = ['seq', 'ang', 'ids', 'crd', 'msk', 'evo'] for (num_items, subset) in zip([train_len, test_len], ['train', 'test']): a...
['def', 'validate_data_dict(data):', 'from', 'sidechainnet.utils.download', 'import', 'VALID_SPLITS', 'train_len', '=', "len(data['train']['seq'])", 'test_len', '=', "len(data['test']['seq'])", 'items_recorded', '=', "['seq',", "'ang',", "'ids',", "'crd',", "'msk',", "'evo']", 'for', '(num_items,', 'subset)', 'in', 'zi...
934,135
jonathanking/sidechainnet
organize.py
create_empty_dictionary
create_empty_dictionary
Create an empty SidechainNet dictionary ready to hold SidechainNet data.
[ "Create", "an", "empty", "SidechainNet", "dictionary", "ready", "to", "hold", "SidechainNet", "data." ]
def create_empty_dictionary(): from sidechainnet.utils.download import VALID_SPLITS data = {'train': copy.deepcopy(EMPTY_SPLIT_DICT), 'test': copy.deepcopy(EMPTY_SPLIT_DICT), 'date': datetime.datetime.now().strftime('%I:%M%p %b %d, %Y'), 'settings': dict()} validation_subdict = {vsplit: copy.deepcopy(EMPTY_...
['def', 'create_empty_dictionary():', 'from', 'sidechainnet.utils.download', 'import', 'VALID_SPLITS', 'data', '=', "{'train':", 'copy.deepcopy(EMPTY_SPLIT_DICT),', "'test':", 'copy.deepcopy(EMPTY_SPLIT_DICT),', "'date':", "datetime.datetime.now().strftime('%I:%M%p", '%b', '%d,', "%Y'),", "'settings':", 'dict()}', 'val...
934,136
jonathanking/sidechainnet
organize.py
compute_angle_means
compute_angle_means
Computes mean of angle matrices in a Python list ignoring all-zero rows.
[ "Computes", "mean", "of", "angle", "matrices", "in", "a", "Python", "list", "ignoring", "all-zero", "rows." ]
def compute_angle_means(angle_list): angles = np.concatenate(angle_list) angles = angles[~(angles == 0).all(axis=1)] return angles.mean(axis=0)
['def', 'compute_angle_means(angle_list):', 'angles', '=', 'np.concatenate(angle_list)', 'angles', '=', 'angles[~(angles', '==', '0).all(axis=1)]', 'return', 'angles.mean(axis=0)']
934,140
jonathanking/sidechainnet
organize.py
save_data
save_data
Saves an organized SidechainNet data dict to a given, local filepath.
[ "Saves", "an", "organized", "SidechainNet", "data", "dict", "to", "a", "given,", "local", "filepath." ]
def save_data(data, path): with open(path, 'wb') as f: return pickle.dump(data, f)
['def', 'save_data(data,', 'path):', 'with', 'open(path,', "'wb')", 'as', 'f:', 'return', 'pickle.dump(data,', 'f)']
934,141
jonathanking/sidechainnet
organize.py
sort_datasplit
sort_datasplit
Sorts a single split of the SidechainNet data dict by ascending length.
[ "Sorts", "a", "single", "split", "of", "the", "SidechainNet", "data", "dict", "by", "ascending", "length." ]
def sort_datasplit(split): sorted_len_indices = [a[0] for a in sorted(enumerate(split['seq']), key=lambda x: len(x[1]), reverse=False)] for datatype in split.keys(): split[datatype] = [split[datatype][i] for i in sorted_len_indices] return split
['def', 'sort_datasplit(split):', 'sorted_len_indices', '=', '[a[0]', 'for', 'a', 'in', "sorted(enumerate(split['seq']),", 'key=lambda', 'x:', 'len(x[1]),', 'reverse=False)]', 'for', 'datatype', 'in', 'split.keys():', 'split[datatype]', '=', '[split[datatype][i]', 'for', 'i', 'in', 'sorted_len_indices]', 'return', 'spl...
934,143
jonathanking/sidechainnet
parse.py
retrieve_relevant_proteinnetids_from_files
retrieve_relevant_proteinnetids_from_files
Returns a list of ProteinNet IDs relevant for a particular training set.
[ "Returns", "a", "list", "of", "ProteinNet", "IDs", "relevant", "for", "a", "particular", "training", "set." ]
def retrieve_relevant_proteinnetids_from_files(proteinnet_out_dir, thinning): train_file = f'training_{thinning}.pkl' relevant_training_file = os.path.join(proteinnet_out_dir, train_file.replace('.pkl', '_ids.txt')) relevant_id_files = [os.path.join(proteinnet_out_dir, 'testing_ids.txt'), os.path.join(prote...
['def', 'retrieve_relevant_proteinnetids_from_files(proteinnet_out_dir,', 'thinning):', 'train_file', '=', "f'training_{thinning}.pkl'", 'relevant_training_file', '=', 'os.path.join(proteinnet_out_dir,', "train_file.replace('.pkl',", "'_ids.txt'))", 'relevant_id_files', '=', '[os.path.join(proteinnet_out_dir,', "'testi...
934,147
jonathanking/sidechainnet
parse.py
parse_dssp_file
parse_dssp_file
Parse AlQuraishi's DSSP files provided from ProteinNet.
[ "Parse", "AlQuraishi's", "DSSP", "files", "provided", "from", "ProteinNet." ]
def parse_dssp_file(path): with open(path, 'r') as f: data = json.load(f) new_dict = {} for key in data: new_dict[key] = data[key]['DSSP'] return new_dict
['def', 'parse_dssp_file(path):', 'with', 'open(path,', "'r')", 'as', 'f:', 'data', '=', 'json.load(f)', 'new_dict', '=', '{}', 'for', 'key', 'in', 'data:', 'new_dict[key]', '=', "data[key]['DSSP']", 'return', 'new_dict']
934,149
jonathanking/sidechainnet
parse.py
get_chain_from_astral_id
get_chain_from_astral_id
Given an ASTRAL ID and the ASTRAL->PDB/chain mapping dictionary, this function attempts to return the relevant, parsed ProDy object.
[ "Given", "an", "ASTRAL", "ID", "and", "the", "ASTRAL->PDB/chain", "mapping", "dictionary,", "this", "function", "attempts", "to", "return", "the", "relevant,", "parsed", "ProDy", "object." ]
def get_chain_from_astral_id(astral_id, d): (pdbid, chain) = d[astral_id] assert ',' not in chain, f'Issue parsing {astral_id} with chain {chain} and pdbid {pdbid}.' (chain, resnums) = chain.split(':') if astral_id == 'd4qrye_' or astral_id in ASTRAL_IDS_INCORRECTLY_PARSED: chain = 'A' r...
['def', 'get_chain_from_astral_id(astral_id,', 'd):', '(pdbid,', 'chain)', '=', 'd[astral_id]', 'assert', "','", 'not', 'in', 'chain,', "f'Issue", 'parsing', '{astral_id}', 'with', 'chain', '{chain}', 'and', 'pdbid', "{pdbid}.'", '(chain,', 'resnums)', '=', "chain.split(':')", 'if', 'astral_id', '==', "'d4qrye_'", 'or'...
934,150
jonathanking/sidechainnet
sequence.py
empty_coord
empty_coord
Return an empty coordinate tensor representing 1 residue-level pad character.
[ "Return", "an", "empty", "coordinate", "tensor", "representing", "1", "residue-level", "pad", "character." ]
def empty_coord(): coord_padding = np.zeros((NUM_COORDS_PER_RES, 3)) coord_padding[:] = GLOBAL_PAD_CHAR return coord_padding
['def', 'empty_coord():', 'coord_padding', '=', 'np.zeros((NUM_COORDS_PER_RES,', '3))', 'coord_padding[:]', '=', 'GLOBAL_PAD_CHAR', 'return', 'coord_padding']
934,152
srama2512/sidekicks
utils.py
evaluate
evaluate
Evaluation function - evaluates the agent over fixed grid locations as starting points and returns the overall average reconstruction error.
[ "Evaluation", "function", "-", "evaluates", "the", "agent", "over", "fixed", "grid", "locations", "as", "starting", "points", "and", "returns", "the", "overall", "average", "reconstruction", "error." ]
def evaluate(loader, agent, split, opts): depleted = False agent.policy.eval() overall_err = 0 overall_count = 0 err_values = [] decoded_images = [] while not depleted: if split == 'val': if opts.expert_rewards and opts.expert_trajectories: (pano, pano_map...
['def', 'evaluate(loader,', 'agent,', 'split,', 'opts):', 'depleted', '=', 'False', 'agent.policy.eval()', 'overall_err', '=', '0', 'overall_count', '=', '0', 'err_values', '=', '[]', 'decoded_images', '=', '[]', 'while', 'not', 'depleted:', 'if', 'split', '==', "'val':", 'if', 'opts.expert_rewards', 'and', 'opts.exper...
934,183
srama2512/sidekicks
utils.py
evaluate_adversarial
evaluate_adversarial
Evaluation function - evaluates the agent over all grid locations as starting points and returns the average of worst reconstruction error over different locations for the panoramas (average(max error over locations)).
[ "Evaluation", "function", "-", "evaluates", "the", "agent", "over", "all", "grid", "locations", "as", "starting", "points", "and", "returns", "the", "average", "of", "worst", "reconstruction", "error", "over", "different", "locations", "for", "the", "panoramas", ...
def evaluate_adversarial(loader, agent, split, opts): depleted = False agent.policy.eval() overall_err = 0 overall_count = 0 decoded_images = [] err_values = [] while not depleted: if split == 'val': if opts.expert_trajectories or opts.actorType == 'demo_sidekick': ...
['def', 'evaluate_adversarial(loader,', 'agent,', 'split,', 'opts):', 'depleted', '=', 'False', 'agent.policy.eval()', 'overall_err', '=', '0', 'overall_count', '=', '0', 'decoded_images', '=', '[]', 'err_values', '=', '[]', 'while', 'not', 'depleted:', 'if', 'split', '==', "'val':", 'if', 'opts.expert_trajectories', '...
934,185
srama2512/sidekicks
utils.py
get_all_trajectories
get_all_trajectories
Gathers trajectories from all starting positions and returns them.
[ "Gathers", "trajectories", "from", "all", "starting", "positions", "and", "returns", "them." ]
def get_all_trajectories(loader, agent, split, opts): depleted = False agent.policy.eval() trajectories = {} elevations = range(0, opts.N) azimuths = range(0, opts.M) for i in elevations: for j in azimuths: trajectories[i, j] = [] while not depleted: if split == '...
['def', 'get_all_trajectories(loader,', 'agent,', 'split,', 'opts):', 'depleted', '=', 'False', 'agent.policy.eval()', 'trajectories', '=', '{}', 'elevations', '=', 'range(0,', 'opts.N)', 'azimuths', '=', 'range(0,', 'opts.M)', 'for', 'i', 'in', 'elevations:', 'for', 'j', 'in', 'azimuths:', 'trajectories[i,', 'j]', '='...
934,186
jesse1029/SiGAN
srez_model.py
Model.add_sigmoid
add_sigmoid
Adds a sigmoid (0,1) activation function layer to this model.
[ "Adds", "a", "sigmoid", "(0,1)", "activation", "function", "layer", "to", "this", "model." ]
def add_sigmoid(self): with tf.variable_scope(self._get_layer_str()): prev_units = self._get_num_inputs() out = tf.nn.sigmoid(self.get_output()) self.outputs.append(out) return self
['def', 'add_sigmoid(self):', 'with', 'tf.variable_scope(self._get_layer_str()):', 'prev_units', '=', 'self._get_num_inputs()', 'out', '=', 'tf.nn.sigmoid(self.get_output())', 'self.outputs.append(out)', 'return', 'self']
934,291
zhiqwang/sightseq
coco_generator.py
ObjectDetectionGenerator.generate
generate
Score a batch of images with best path decoding.
[ "Score", "a", "batch", "of", "images", "with", "best", "path", "decoding." ]
def generate(self, models, sample, **kwargs): assert len(models) == 1 model = ObjectDetectionEnsembleModel(models) model.eval() net_input = sample['image'] hypos = model.forward_featurize(net_input) return hypos
['def', 'generate(self,', 'models,', 'sample,', '**kwargs):', 'assert', 'len(models)', '==', '1', 'model', '=', 'ObjectDetectionEnsembleModel(models)', 'model.eval()', 'net_input', '=', "sample['image']", 'hypos', '=', 'model.forward_featurize(net_input)', 'return', 'hypos']
934,384
zhiqwang/sightseq
ctc_loss_generator.py
CTCLossGenerator.decode
decode
Decode encoded labels back into strings.
[ "Decode", "encoded", "labels", "back", "into", "strings." ]
def decode(self, decoder_out, length): if length.numel() == 1: length = length[0] assert decoder_out.numel() == length if self.raw: if self.strings: return u''.join([self.tgt_dict.symbols[i] for i in decoder_out]).encode('utf-8') return decoder_out.tol...
['def', 'decode(self,', 'decoder_out,', 'length):', 'if', 'length.numel()', '==', '1:', 'length', '=', 'length[0]', 'assert', 'decoder_out.numel()', '==', 'length', 'if', 'self.raw:', 'if', 'self.strings:', 'return', "u''.join([self.tgt_dict.symbols[i]", 'for', 'i', 'in', "decoder_out]).encode('utf-8')", 'return', 'dec...
934,387
zhiqwang/sightseq
coco_dataset.py
collate
collate
collate samples of images and targets.
[ "collate", "samples", "of", "images", "and", "targets." ]
def collate(samples): if len(samples) == 0: return {} id = torch.LongTensor([s['id'] for s in samples]) images = [s['image'] for s in samples] targets = [s['target'] for s in samples] ntokens = sum((len(t['labels']) for t in targets)) batch = {'id': id, 'nsentences': len(samples), 'ntoke...
['def', 'collate(samples):', 'if', 'len(samples)', '==', '0:', 'return', '{}', 'id', '=', "torch.LongTensor([s['id']", 'for', 's', 'in', 'samples])', 'images', '=', "[s['image']", 'for', 's', 'in', 'samples]', 'targets', '=', "[s['target']", 'for', 's', 'in', 'samples]', 'ntokens', '=', "sum((len(t['labels'])", 'for', ...
934,407
zhiqwang/sightseq
coco_dictionary.py
CocoDictionary.string
string
Helper for converting a tensor of token indices to a string.
[ "Helper", "for", "converting", "a", "tensor", "of", "token", "indices", "to", "a", "string." ]
def string(self, tensor, bpe_symbol=None, escape_unk=False): if torch.is_tensor(tensor) and tensor.dim() == 2: return '\n'.join((self.string(t) for t in tensor)) sent = ' '.join((self[i] for i in tensor)) return sent
['def', 'string(self,', 'tensor,', 'bpe_symbol=None,', 'escape_unk=False):', 'if', 'torch.is_tensor(tensor)', 'and', 'tensor.dim()', '==', '2:', 'return', "'\\n'.join((self.string(t)", 'for', 't', 'in', 'tensor))', 'sent', '=', "'", "'.join((self[i]", 'for', 'i', 'in', 'tensor))', 'return', 'sent']
934,412
zhiqwang/sightseq
text_recognition_encoder.py
TextRecognitionEncoder.max_positions
max_positions
Maximum sequence length supported by the encoder.
[ "Maximum", "sequence", "length", "supported", "by", "the", "encoder." ]
def max_positions(self): return 128
['def', 'max_positions(self):', 'return', '128']
934,444
alvinwan/sign-language-translator
step_2_dataset.py
SignLanguageMNIST.read_label_samples_from_csv
read_label_samples_from_csv
Assumes first column in CSV is the label and subsequent 28^2 values are image pixel values 0-255.
[ "Assumes", "first", "column", "in", "CSV", "is", "the", "label", "and", "subsequent", "28^2", "values", "are", "image", "pixel", "values", "0-255." ]
def read_label_samples_from_csv(path: str): mapping = SignLanguageMNIST.get_label_mapping() (labels, samples) = ([], []) with open(path) as f: _ = next(f) for line in csv.reader(f): label = int(line[0]) labels.append(mapping.index(label)) samples.append(li...
['def', 'read_label_samples_from_csv(path:', 'str):', 'mapping', '=', 'SignLanguageMNIST.get_label_mapping()', '(labels,', 'samples)', '=', '([],', '[])', 'with', 'open(path)', 'as', 'f:', '_', '=', 'next(f)', 'for', 'line', 'in', 'csv.reader(f):', 'label', '=', 'int(line[0])', 'labels.append(mapping.index(label))', 's...
934,629
twangnh/SimCal
get_instance_group.py
get_masks
get_masks
Merge the mask of multiple objects in klist.
[ "Merge", "the", "mask", "of", "multiple", "objects", "in", "klist." ]
def get_masks(mat, klist): retMat = np.zeros_like(mat) for k in klist: retMat += (mat - 1 == k).astype(np.uint8) return retMat
['def', 'get_masks(mat,', 'klist):', 'retMat', '=', 'np.zeros_like(mat)', 'for', 'k', 'in', 'klist:', 'retMat', '+=', '(mat', '-', '1', '==', 'k).astype(np.uint8)', 'return', 'retMat']
934,741
bcmi/SimFormer-Weak-Shot-Semantic-
pseudo_labeling.py
generate_pseudo_label
generate_pseudo_label
pred_segm is cid, while gt_segm_raw is did.
[ "pred_segm", "is", "cid,", "while", "gt_segm_raw", "is", "did." ]
def generate_pseudo_label(pred_segm, gt_segm_raw, ant_file, output_dir, meta, ant_file_to_type=None): img_type = 'existing' assert img_type in ['existing', 'updated'] mixed_mask = np.ones_like(gt_segm_raw) * 255 for gt_did in np.unique(gt_segm_raw): if gt_did == 255: continue ...
['def', 'generate_pseudo_label(pred_segm,', 'gt_segm_raw,', 'ant_file,', 'output_dir,', 'meta,', 'ant_file_to_type=None):', 'img_type', '=', "'existing'", 'assert', 'img_type', 'in', "['existing',", "'updated']", 'mixed_mask', '=', 'np.ones_like(gt_segm_raw)', '*', '255', 'for', 'gt_did', 'in', 'np.unique(gt_segm_raw):...
934,858
chribsen/simple-machine-learning-examples
update_checker.py
update_check
update_check
Convenience method that outputs to stdout if an update is available.
[ "Convenience", "method", "that", "outputs", "to", "stdout", "if", "an", "update", "is", "available." ]
def update_check(package_name, package_version, bypass_cache=False, url=None, **extra_data): checker = UpdateChecker(url) checker.bypass_cache = bypass_cache result = checker.check(package_name, package_version, **extra_data) if result: print(result)
['def', 'update_check(package_name,', 'package_version,', 'bypass_cache=False,', 'url=None,', '**extra_data):', 'checker', '=', 'UpdateChecker(url)', 'checker.bypass_cache', '=', 'bypass_cache', 'result', '=', 'checker.check(package_name,', 'package_version,', '**extra_data)', 'if', 'result:', 'print(result)']
934,922
chribsen/simple-machine-learning-examples
update_checker.py
UpdateChecker.check
check
Return a UpdateResult object if there is a newer version.
[ "Return", "a", "UpdateResult", "object", "if", "there", "is", "a", "newer", "version." ]
def check(self, package_name, package_version, **extra_data): data = extra_data data['package_name'] = package_name data['package_version'] = package_version data['python_version'] = sys.version.split()[0] data['platform'] = platform.platform(True) try: headers = {'connection': 'close', ...
['def', 'check(self,', 'package_name,', 'package_version,', '**extra_data):', 'data', '=', 'extra_data', "data['package_name']", '=', 'package_name', "data['package_version']", '=', 'package_version', "data['python_version']", '=', 'sys.version.split()[0]', "data['platform']", '=', 'platform.platform(True)', 'try:', 'h...
934,923
chribsen/simple-machine-learning-examples
binary.py
royal_road2
royal_road2
Royal Road Function R2 as presented by Melanie Mitchell in : "An introduction to Genetic Algorithms".
[ "Royal", "Road", "Function", "R2", "as", "presented", "by", "Melanie", "Mitchell", "in", ":", "\"An", "introduction", "to", "Genetic", "Algorithms\"." ]
def royal_road2(individual, order): total = 0 norder = order while norder < order ** 2: total += royal_road1(norder, individual)[0] norder *= 2 return (total,)
['def', 'royal_road2(individual,', 'order):', 'total', '=', '0', 'norder', '=', 'order', 'while', 'norder', '<', 'order', '**', '2:', 'total', '+=', 'royal_road1(norder,', 'individual)[0]', 'norder', '*=', '2', 'return', '(total,)']
934,973
chribsen/simple-machine-learning-examples
support.py
HallOfFame.clear
clear
Clear the hall of fame.
[ "Clear", "the", "hall", "of", "fame." ]
def clear(self): del self.items[:] del self.keys[:]
['def', 'clear(self):', 'del', 'self.items[:]', 'del', 'self.keys[:]']
935,068
chribsen/simple-machine-learning-examples
ols.py
OLS.p_value
p_value
Returns the p values.
[ "Returns", "the", "p", "values." ]
def p_value(self): return Series(self._p_value_raw, index=self.beta.index)
['def', 'p_value(self):', 'return', 'Series(self._p_value_raw,', 'index=self.beta.index)']
936,570
chribsen/simple-machine-learning-examples
ols.py
OLS.rmse
rmse
Returns the rmse value.
[ "Returns", "the", "rmse", "value." ]
def rmse(self): return self._rmse_raw
['def', 'rmse(self):', 'return', 'self._rmse_raw']
936,573
chribsen/simple-machine-learning-examples
ols.py
OLS.summary_as_matrix
summary_as_matrix
Returns the formatted results of the OLS as a DataFrame.
[ "Returns", "the", "formatted", "results", "of", "the", "OLS", "as", "a", "DataFrame." ]
def summary_as_matrix(self): results = self._results beta = results['beta'] data = {'beta': results['beta'], 't-stat': results['t_stat'], 'p-value': results['p_value'], 'std err': results['std_err']} return DataFrame(data, beta.index).T
['def', 'summary_as_matrix(self):', 'results', '=', 'self._results', 'beta', '=', "results['beta']", 'data', '=', "{'beta':", "results['beta'],", "'t-stat':", "results['t_stat'],", "'p-value':", "results['p_value'],", "'std", "err':", "results['std_err']}", 'return', 'DataFrame(data,', 'beta.index).T']
936,580
chribsen/simple-machine-learning-examples
test_generic.py
TestDataFrame.test_describe_multi_index_df_column_names
test_describe_multi_index_df_column_names
Test that column names persist after the describe operation.
[ "Test", "that", "column", "names", "persist", "after", "the", "describe", "operation." ]
def test_describe_multi_index_df_column_names(self): df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'], 'C': np.random.randn(8), 'D': np.random.randn(8)}) hierarchical_index_df = df.groupby(['A', 'B']).mean().T ...
['def', 'test_describe_multi_index_df_column_names(self):', 'df', '=', "pd.DataFrame({'A':", "['foo',", "'bar',", "'foo',", "'bar',", "'foo',", "'bar',", "'foo',", "'foo'],", "'B':", "['one',", "'one',", "'two',", "'three',", "'two',", "'two',", "'one',", "'three'],", "'C':", 'np.random.randn(8),', "'D':", 'np.random.r...
936,614
chribsen/simple-machine-learning-examples
test_decomp.py
TestEig.test_falker
test_falker
Test matrices giving some Nan generalized eigen values.
[ "Test", "matrices", "giving", "some", "Nan", "generalized", "eigen", "values." ]
def test_falker(self): M = diag(array([1, 0, 3])) K = array(([2, -1, -1], [-1, 2, -1], [-1, -1, 2])) D = array(([1, -1, 0], [-1, 1, 0], [0, 0, 0])) Z = zeros((3, 3)) I = identity(3) A = bmat([[I, Z], [Z, -K]]) B = bmat([[Z, I], [M, D]]) olderr = np.seterr(all='ignore') try: s...
['def', 'test_falker(self):', 'M', '=', 'diag(array([1,', '0,', '3]))', 'K', '=', 'array(([2,', '-1,', '-1],', '[-1,', '2,', '-1],', '[-1,', '-1,', '2]))', 'D', '=', 'array(([1,', '-1,', '0],', '[-1,', '1,', '0],', '[0,', '0,', '0]))', 'Z', '=', 'zeros((3,', '3))', 'I', '=', 'identity(3)', 'A', '=', 'bmat([[I,', 'Z],',...
938,180
chribsen/simple-machine-learning-examples
ast_tools.py
remove_reserved_names
remove_reserved_names
These are functions names -- don't create variables for them There is a more reobust approach, but this ought to work pretty well.
[ "These", "are", "functions", "names", "--", "don't", "create", "variables", "for", "them", "There", "is", "a", "more", "reobust", "approach,", "but", "this", "ought", "to", "work", "pretty", "well." ]
def remove_reserved_names(lst): output = [] for item in lst: if item not in reserved_names: output.append(item) return output
['def', 'remove_reserved_names(lst):', 'output', '=', '[]', 'for', 'item', 'in', 'lst:', 'if', 'item', 'not', 'in', 'reserved_names:', 'output.append(item)', 'return', 'output']
938,625
chribsen/simple-machine-learning-examples
ast_tools.py
harvest_variables
harvest_variables
Retrieve all the variables that need to be defined.
[ "Retrieve", "all", "the", "variables", "that", "need", "to", "be", "defined." ]
def harvest_variables(ast_list): variables = [] if issequence(ast_list): (found, data) = match(name_pattern, ast_list) if found: variables.append(data['var']) for item in ast_list: if issequence(item): variables.extend(harvest_variables(item)) ...
['def', 'harvest_variables(ast_list):', 'variables', '=', '[]', 'if', 'issequence(ast_list):', '(found,', 'data)', '=', 'match(name_pattern,', 'ast_list)', 'if', 'found:', "variables.append(data['var'])", 'for', 'item', 'in', 'ast_list:', 'if', 'issequence(item):', 'variables.extend(harvest_variables(item))', 'variable...
938,626
chribsen/simple-machine-learning-examples
catalog.py
whoami
whoami
return a string identifying the user.
[ "return", "a", "string", "identifying", "the", "user." ]
def whoami(): return os.environ.get('USER') or os.environ.get('USERNAME') or 'unknown'
['def', 'whoami():', 'return', "os.environ.get('USER')", 'or', "os.environ.get('USERNAME')", 'or', "'unknown'"]
938,632
chribsen/simple-machine-learning-examples
catalog.py
intermediate_dir_prefix
intermediate_dir_prefix
Prefix of root intermediate dir (<tmp>/<root_im_dir>).
[ "Prefix", "of", "root", "intermediate", "dir", "(<tmp>/<root_im_dir>)." ]
def intermediate_dir_prefix(): return '%s-%s-' % ('scipy', whoami())
['def', 'intermediate_dir_prefix():', 'return', "'%s-%s-'", '%', "('scipy',", 'whoami())']
938,638
chribsen/simple-machine-learning-examples
catalog.py
catalog.get_module_directory
get_module_directory
Return the path used to replace the 'MODULE' in searches.
[ "Return", "the", "path", "used", "to", "replace", "the", "'MODULE'", "in", "searches." ]
def get_module_directory(self): return self.module_dir
['def', 'get_module_directory(self):', 'return', 'self.module_dir']
938,647
chribsen/simple-machine-learning-examples
catalog.py
catalog.clear_module_directory
clear_module_directory
Reset 'MODULE' path to None so that it is ignored in searches.
[ "Reset", "'MODULE'", "path", "to", "None", "so", "that", "it", "is", "ignored", "in", "searches." ]
def clear_module_directory(self): self.module_dir = None
['def', 'clear_module_directory(self):', 'self.module_dir', '=', 'None']
938,648
chribsen/simple-machine-learning-examples
catalog.py
catalog.path_key
path_key
Return key for path information for functions associated with code.
[ "Return", "key", "for", "path", "information", "for", "functions", "associated", "with", "code." ]
def path_key(self, code): return '__path__' + code
['def', 'path_key(self,', 'code):', 'return', "'__path__'", '+', 'code']
938,656
chribsen/simple-machine-learning-examples
platform_info.py
msvc_exists
msvc_exists
Determine whether MSVC is available on the machine.
[ "Determine", "whether", "MSVC", "is", "available", "on", "the", "machine." ]
def msvc_exists(): result = 0 try: p = subprocess.Popen(['cl'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) str_result = p.stdout.read() if 'Microsoft' in str_result: result = 1 except: import distutils.msvccompiler try: versi...
['def', 'msvc_exists():', 'result', '=', '0', 'try:', 'p', '=', "subprocess.Popen(['cl'],", 'shell=True,', 'stdout=subprocess.PIPE,', 'stderr=subprocess.STDOUT)', 'str_result', '=', 'p.stdout.read()', 'if', "'Microsoft'", 'in', 'str_result:', 'result', '=', '1', 'except:', 'import', 'distutils.msvccompiler', 'try:', 'v...
938,669
chribsen/simple-machine-learning-examples
scxx_timings.py
time_list_append
time_list_append
Compare the list append method from scxx to using the Python API directly.
[ "Compare", "the", "list", "append", "method", "from", "scxx", "to", "using", "the", "Python", "API", "directly." ]
def time_list_append(Na): print('list appending times:', end=' ') a = [] t1 = time.time() list_append_c(a, Na) t2 = time.time() print('py api: ', t2 - t1, '<note: first time takes longer -- repeat below>') a = [] t1 = time.time() list_append_c(a, Na) t2 = time.time() print('p...
['def', 'time_list_append(Na):', "print('list", 'appending', "times:',", "end='", "')", 'a', '=', '[]', 't1', '=', 'time.time()', 'list_append_c(a,', 'Na)', 't2', '=', 'time.time()', "print('py", 'api:', "',", 't2', '-', 't1,', "'<note:", 'first', 'time', 'takes', 'longer', '--', 'repeat', "below>')", 'a', '=', '[]', '...
938,687
chribsen/simple-machine-learning-examples
weave_test_utils.py
clear_temp_catalog
clear_temp_catalog
Remove any catalog from the temp dir.
[ "Remove", "any", "catalog", "from", "the", "temp", "dir." ]
def clear_temp_catalog(): backup_dir = tempfile.mkdtemp() for file in temp_catalog_files(): move_file(file, backup_dir) return backup_dir
['def', 'clear_temp_catalog():', 'backup_dir', '=', 'tempfile.mkdtemp()', 'for', 'file', 'in', 'temp_catalog_files():', 'move_file(file,', 'backup_dir)', 'return', 'backup_dir']
938,690
chribsen/simple-machine-learning-examples
msvc.py
SystemInfo.WindowsSdkVersion
WindowsSdkVersion
Microsoft Windows SDK versions.
[ "Microsoft", "Windows", "SDK", "versions." ]
def WindowsSdkVersion(self): if self.vc_ver <= 9.0: return ('7.0', '6.1', '6.0a') elif self.vc_ver == 10.0: return ('7.1', '7.0a') elif self.vc_ver == 11.0: return ('8.0', '8.0a') elif self.vc_ver == 12.0: return ('8.1', '8.1a') elif self.vc_ver >= 14.0: retur...
['def', 'WindowsSdkVersion(self):', 'if', 'self.vc_ver', '<=', '9.0:', 'return', "('7.0',", "'6.1',", "'6.0a')", 'elif', 'self.vc_ver', '==', '10.0:', 'return', "('7.1',", "'7.0a')", 'elif', 'self.vc_ver', '==', '11.0:', 'return', "('8.0',", "'8.0a')", 'elif', 'self.vc_ver', '==', '12.0:', 'return', "('8.1',", "'8.1a')...
938,789
chribsen/simple-machine-learning-examples
base.py
LinearRegression.residues_
residues_
Get the residues of the fitted model.
[ "Get", "the", "residues", "of", "the", "fitted", "model." ]
def residues_(self): return self._residues
['def', 'residues_(self):', 'return', 'self._residues']
939,436
swasun/VQ-VAE-Images
vector_quantizer.py
VectorQuantizer.forward
forward
Connects the module to some inputs.
[ "Connects", "the", "module", "to", "some", "inputs." ]
def forward(self, inputs): inputs = inputs.permute(0, 2, 3, 1).contiguous() input_shape = inputs.shape flat_input = inputs.view(-1, self._embedding_dim) distances = torch.sum(flat_input ** 2, dim=1, keepdim=True) + torch.sum(self._embedding.weight ** 2, dim=1) - 2 * torch.matmul(flat_input, self._embedd...
['def', 'forward(self,', 'inputs):', 'inputs', '=', 'inputs.permute(0,', '2,', '3,', '1).contiguous()', 'input_shape', '=', 'inputs.shape', 'flat_input', '=', 'inputs.view(-1,', 'self._embedding_dim)', 'distances', '=', 'torch.sum(flat_input', '**', '2,', 'dim=1,', 'keepdim=True)', '+', 'torch.sum(self._embedding.weigh...
939,775
ipazc/vrpwrp
test_boundingbox.py
TestBoundingBox.setUp
setUp
Definition of some common rect values for the tests.
[ "Definition", "of", "some", "common", "rect", "values", "for", "the", "tests." ]
def setUp(self): self.rect_sets = [[[80, 60, 250, 170], [200, 130, 200, 170], 13000, 38.24], [[80, 60, 40, 170], [200, 130, 200, 170], 0, 0.0]]
['def', 'setUp(self):', 'self.rect_sets', '=', '[[[80,', '60,', '250,', '170],', '[200,', '130,', '200,', '170],', '13000,', '38.24],', '[[80,', '60,', '40,', '170],', '[200,', '130,', '200,', '170],', '0,', '0.0]]']
940,006
ipazc/vrpwrp
test_boundingbox.py
TestBoundingBox.test_expand
test_expand
Tests the expansion of bounding box.
[ "Tests", "the", "expansion", "of", "bounding", "box." ]
def test_expand(self): box1 = BoundingBox(3, 3, 100, 100) box1.expand() self.assertEqual(box1.get_box(), [-7, -7, 120, 120])
['def', 'test_expand(self):', 'box1', '=', 'BoundingBox(3,', '3,', '100,', '100)', 'box1.expand()', 'self.assertEqual(box1.get_box(),', '[-7,', '-7,', '120,', '120])']
940,007
ipazc/vrpwrp
test_boundingbox.py
TestBoundingBox.test_bounding_box_from_string
test_bounding_box_from_string
Tests the creation a bounding box from a string.
[ "Tests", "the", "creation", "a", "bounding", "box", "from", "a", "string." ]
def test_bounding_box_from_string(self): bbox_string = '22,34,122,432' bbox = BoundingBox.from_string(bbox_string) self.assertEqual(bbox.get_box(), [22, 34, 122, 432]) bbox_string = '22, 34,122,432' bbox = BoundingBox.from_string(bbox_string) self.assertEqual(bbox.get_box(), [22, 34, 122, 432]) ...
['def', 'test_bounding_box_from_string(self):', 'bbox_string', '=', "'22,34,122,432'", 'bbox', '=', 'BoundingBox.from_string(bbox_string)', 'self.assertEqual(bbox.get_box(),', '[22,', '34,', '122,', '432])', 'bbox_string', '=', "'22,", "34,122,432'", 'bbox', '=', 'BoundingBox.from_string(bbox_string)', 'self.assertEqua...
940,008
ipazc/vrpwrp
test_boundingbox.py
TestBoundingBox.test_fit_in_size
test_fit_in_size
Tests that bounding box is able to adapt itself to specified bounds.
[ "Tests", "that", "bounding", "box", "is", "able", "to", "adapt", "itself", "to", "specified", "bounds." ]
def test_fit_in_size(self): image_size = [300, 300] box1 = BoundingBox(-1, -1, 302, 302) box1.fit_in_size(image_size) self.assertEqual(box1.get_box(), [0, 0, 300, 300]) box1 = BoundingBox(-1, -1, 301, 301) box1.fit_in_size(image_size) self.assertEqual(box1.get_box(), [0, 0, 300, 300]) bo...
['def', 'test_fit_in_size(self):', 'image_size', '=', '[300,', '300]', 'box1', '=', 'BoundingBox(-1,', '-1,', '302,', '302)', 'box1.fit_in_size(image_size)', 'self.assertEqual(box1.get_box(),', '[0,', '0,', '300,', '300])', 'box1', '=', 'BoundingBox(-1,', '-1,', '301,', '301)', 'box1.fit_in_size(image_size)', 'self.ass...
940,009