repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
SBRG/ssbio | ssbio/protein/structure/structprop.py | StructProp.find_disulfide_bridges | def find_disulfide_bridges(self, threshold=3.0):
"""Run Biopython's search_ss_bonds to find potential disulfide bridges for each chain and store in ChainProp.
Will add a list of tuple pairs into the annotations field, looks like this::
[ ((' ', 79, ' '), (' ', 110, ' ')),
((' ', 174, ' '), (' ', 180, ' ')),
((' ', 369, ' '), (' ', 377, ' '))]
Where each pair is a pair of cysteine residues close together in space.
"""
if self.structure:
parsed = self.structure
else:
parsed = self.parse_structure()
if not parsed:
log.error('{}: unable to open structure to find S-S bridges'.format(self.id))
return
disulfide_bridges = ssbio.protein.structure.properties.residues.search_ss_bonds(parsed.first_model,
threshold=threshold)
if not disulfide_bridges:
log.debug('{}: no disulfide bridges found'.format(self.id))
for chain, bridges in disulfide_bridges.items():
self.chains.get_by_id(chain).seq_record.annotations['SSBOND-biopython'] = disulfide_bridges[chain]
log.debug('{}: found {} disulfide bridges'.format(chain, len(bridges)))
log.debug('{}: stored disulfide bridges in the chain\'s seq_record letter_annotations'.format(chain)) | python | def find_disulfide_bridges(self, threshold=3.0):
"""Run Biopython's search_ss_bonds to find potential disulfide bridges for each chain and store in ChainProp.
Will add a list of tuple pairs into the annotations field, looks like this::
[ ((' ', 79, ' '), (' ', 110, ' ')),
((' ', 174, ' '), (' ', 180, ' ')),
((' ', 369, ' '), (' ', 377, ' '))]
Where each pair is a pair of cysteine residues close together in space.
"""
if self.structure:
parsed = self.structure
else:
parsed = self.parse_structure()
if not parsed:
log.error('{}: unable to open structure to find S-S bridges'.format(self.id))
return
disulfide_bridges = ssbio.protein.structure.properties.residues.search_ss_bonds(parsed.first_model,
threshold=threshold)
if not disulfide_bridges:
log.debug('{}: no disulfide bridges found'.format(self.id))
for chain, bridges in disulfide_bridges.items():
self.chains.get_by_id(chain).seq_record.annotations['SSBOND-biopython'] = disulfide_bridges[chain]
log.debug('{}: found {} disulfide bridges'.format(chain, len(bridges)))
log.debug('{}: stored disulfide bridges in the chain\'s seq_record letter_annotations'.format(chain)) | [
"def",
"find_disulfide_bridges",
"(",
"self",
",",
"threshold",
"=",
"3.0",
")",
":",
"if",
"self",
".",
"structure",
":",
"parsed",
"=",
"self",
".",
"structure",
"else",
":",
"parsed",
"=",
"self",
".",
"parse_structure",
"(",
")",
"if",
"not",
"parsed... | Run Biopython's search_ss_bonds to find potential disulfide bridges for each chain and store in ChainProp.
Will add a list of tuple pairs into the annotations field, looks like this::
[ ((' ', 79, ' '), (' ', 110, ' ')),
((' ', 174, ' '), (' ', 180, ' ')),
((' ', 369, ' '), (' ', 377, ' '))]
Where each pair is a pair of cysteine residues close together in space. | [
"Run",
"Biopython",
"s",
"search_ss_bonds",
"to",
"find",
"potential",
"disulfide",
"bridges",
"for",
"each",
"chain",
"and",
"store",
"in",
"ChainProp",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/structprop.py#L319-L349 | train | 29,100 |
SBRG/ssbio | ssbio/protein/structure/structprop.py | StructProp.get_polypeptide_within | def get_polypeptide_within(self, chain_id, resnum, angstroms, only_protein=True,
use_ca=False, custom_coord=None, return_resnums=False):
"""Get a Polypeptide object of the amino acids within X angstroms of the specified chain + residue number.
Args:
resnum (int): Residue number of the structure
chain_id (str): Chain ID of the residue number
angstroms (float): Radius of the search sphere
only_protein (bool): If only protein atoms (no HETATMS) should be included in the returned sequence
use_ca (bool): If the alpha-carbon atom should be used for searching, default is False (last atom of residue used)
custom_coord (list): custom XYZ coord
return_resnums (bool): if list of resnums should be returned
Returns:
Bio.PDB.Polypeptide.Polypeptide: Biopython Polypeptide object
"""
# XTODO: documentation, unit test
if self.structure:
parsed = self.structure
else:
parsed = self.parse_structure()
residue_list = ssbio.protein.structure.properties.residues.within(resnum=resnum, chain_id=chain_id,
model=parsed.first_model,
angstroms=angstroms, use_ca=use_ca,
custom_coord=custom_coord)
if only_protein:
filtered_residue_list = [x for x in residue_list if x.id[0] == ' ']
else:
filtered_residue_list = residue_list
residue_list_combined = Polypeptide(filtered_residue_list)
if return_resnums:
resnums = [int(x.id[1]) for x in filtered_residue_list]
return residue_list_combined, resnums
return residue_list_combined | python | def get_polypeptide_within(self, chain_id, resnum, angstroms, only_protein=True,
use_ca=False, custom_coord=None, return_resnums=False):
"""Get a Polypeptide object of the amino acids within X angstroms of the specified chain + residue number.
Args:
resnum (int): Residue number of the structure
chain_id (str): Chain ID of the residue number
angstroms (float): Radius of the search sphere
only_protein (bool): If only protein atoms (no HETATMS) should be included in the returned sequence
use_ca (bool): If the alpha-carbon atom should be used for searching, default is False (last atom of residue used)
custom_coord (list): custom XYZ coord
return_resnums (bool): if list of resnums should be returned
Returns:
Bio.PDB.Polypeptide.Polypeptide: Biopython Polypeptide object
"""
# XTODO: documentation, unit test
if self.structure:
parsed = self.structure
else:
parsed = self.parse_structure()
residue_list = ssbio.protein.structure.properties.residues.within(resnum=resnum, chain_id=chain_id,
model=parsed.first_model,
angstroms=angstroms, use_ca=use_ca,
custom_coord=custom_coord)
if only_protein:
filtered_residue_list = [x for x in residue_list if x.id[0] == ' ']
else:
filtered_residue_list = residue_list
residue_list_combined = Polypeptide(filtered_residue_list)
if return_resnums:
resnums = [int(x.id[1]) for x in filtered_residue_list]
return residue_list_combined, resnums
return residue_list_combined | [
"def",
"get_polypeptide_within",
"(",
"self",
",",
"chain_id",
",",
"resnum",
",",
"angstroms",
",",
"only_protein",
"=",
"True",
",",
"use_ca",
"=",
"False",
",",
"custom_coord",
"=",
"None",
",",
"return_resnums",
"=",
"False",
")",
":",
"# XTODO: documentat... | Get a Polypeptide object of the amino acids within X angstroms of the specified chain + residue number.
Args:
resnum (int): Residue number of the structure
chain_id (str): Chain ID of the residue number
angstroms (float): Radius of the search sphere
only_protein (bool): If only protein atoms (no HETATMS) should be included in the returned sequence
use_ca (bool): If the alpha-carbon atom should be used for searching, default is False (last atom of residue used)
custom_coord (list): custom XYZ coord
return_resnums (bool): if list of resnums should be returned
Returns:
Bio.PDB.Polypeptide.Polypeptide: Biopython Polypeptide object | [
"Get",
"a",
"Polypeptide",
"object",
"of",
"the",
"amino",
"acids",
"within",
"X",
"angstroms",
"of",
"the",
"specified",
"chain",
"+",
"residue",
"number",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/structprop.py#L351-L390 | train | 29,101 |
SBRG/ssbio | ssbio/protein/structure/structprop.py | StructProp.get_seqprop_within | def get_seqprop_within(self, chain_id, resnum, angstroms, only_protein=True,
use_ca=False, custom_coord=None, return_resnums=False):
"""Get a SeqProp object of the amino acids within X angstroms of the specified chain + residue number.
Args:
resnum (int): Residue number of the structure
chain_id (str): Chain ID of the residue number
angstroms (float): Radius of the search sphere
only_protein (bool): If only protein atoms (no HETATMS) should be included in the returned sequence
use_ca (bool): If the alpha-carbon atom should be used for searching, default is False (last atom of residue used)
Returns:
SeqProp: Sequence that represents the amino acids in the vicinity of your residue number.
"""
# XTODO: change "remove" parameter to be clean_seq and to remove all non standard amino acids
# TODO: make return_resnums smarter
polypep, resnums = self.get_polypeptide_within(chain_id=chain_id, resnum=resnum, angstroms=angstroms, use_ca=use_ca,
only_protein=only_protein, custom_coord=custom_coord,
return_resnums=True)
# final_seq = polypep.get_sequence()
# seqprop = SeqProp(id='{}-{}_within_{}_of_{}'.format(self.id, chain_id, angstroms, resnum),
# seq=final_seq)
chain_subseq = self.chains.get_by_id(chain_id).get_subsequence(resnums)
if return_resnums:
return chain_subseq, resnums
else:
return chain_subseq | python | def get_seqprop_within(self, chain_id, resnum, angstroms, only_protein=True,
use_ca=False, custom_coord=None, return_resnums=False):
"""Get a SeqProp object of the amino acids within X angstroms of the specified chain + residue number.
Args:
resnum (int): Residue number of the structure
chain_id (str): Chain ID of the residue number
angstroms (float): Radius of the search sphere
only_protein (bool): If only protein atoms (no HETATMS) should be included in the returned sequence
use_ca (bool): If the alpha-carbon atom should be used for searching, default is False (last atom of residue used)
Returns:
SeqProp: Sequence that represents the amino acids in the vicinity of your residue number.
"""
# XTODO: change "remove" parameter to be clean_seq and to remove all non standard amino acids
# TODO: make return_resnums smarter
polypep, resnums = self.get_polypeptide_within(chain_id=chain_id, resnum=resnum, angstroms=angstroms, use_ca=use_ca,
only_protein=only_protein, custom_coord=custom_coord,
return_resnums=True)
# final_seq = polypep.get_sequence()
# seqprop = SeqProp(id='{}-{}_within_{}_of_{}'.format(self.id, chain_id, angstroms, resnum),
# seq=final_seq)
chain_subseq = self.chains.get_by_id(chain_id).get_subsequence(resnums)
if return_resnums:
return chain_subseq, resnums
else:
return chain_subseq | [
"def",
"get_seqprop_within",
"(",
"self",
",",
"chain_id",
",",
"resnum",
",",
"angstroms",
",",
"only_protein",
"=",
"True",
",",
"use_ca",
"=",
"False",
",",
"custom_coord",
"=",
"None",
",",
"return_resnums",
"=",
"False",
")",
":",
"# XTODO: change \"remov... | Get a SeqProp object of the amino acids within X angstroms of the specified chain + residue number.
Args:
resnum (int): Residue number of the structure
chain_id (str): Chain ID of the residue number
angstroms (float): Radius of the search sphere
only_protein (bool): If only protein atoms (no HETATMS) should be included in the returned sequence
use_ca (bool): If the alpha-carbon atom should be used for searching, default is False (last atom of residue used)
Returns:
SeqProp: Sequence that represents the amino acids in the vicinity of your residue number. | [
"Get",
"a",
"SeqProp",
"object",
"of",
"the",
"amino",
"acids",
"within",
"X",
"angstroms",
"of",
"the",
"specified",
"chain",
"+",
"residue",
"number",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/structprop.py#L392-L422 | train | 29,102 |
SBRG/ssbio | ssbio/protein/structure/structprop.py | StructProp.get_dssp_annotations | def get_dssp_annotations(self, outdir, force_rerun=False):
"""Run DSSP on this structure and store the DSSP annotations in the corresponding ChainProp SeqRecords
Calculations are stored in the ChainProp's ``letter_annotations`` at the following keys:
* ``SS-dssp``
* ``RSA-dssp``
* ``ASA-dssp``
* ``PHI-dssp``
* ``PSI-dssp``
Args:
outdir (str): Path to where DSSP dataframe will be stored.
force_rerun (bool): If DSSP results should be recalculated
TODO:
* Also parse global properties, like total accessible surface area. Don't think Biopython parses those?
"""
if self.structure:
parsed = self.structure
else:
parsed = self.parse_structure()
if not parsed:
log.error('{}: unable to open structure to run DSSP'.format(self.id))
return
log.debug('{}: running DSSP'.format(self.id))
dssp_results = ssbio.protein.structure.properties.dssp.get_dssp_df(model=parsed.first_model,
pdb_file=self.structure_path,
outdir=outdir,
force_rerun=force_rerun)
if dssp_results.empty:
log.error('{}: unable to run DSSP'.format(self.id))
return
chains = dssp_results.chain.unique()
dssp_summary = ssbio.protein.structure.properties.dssp.secondary_structure_summary(dssp_results)
for chain in chains:
ss = dssp_results[dssp_results.chain == chain].ss.tolist()
exposure_rsa = dssp_results[dssp_results.chain == chain].exposure_rsa.tolist()
exposure_asa = dssp_results[dssp_results.chain == chain].exposure_asa.tolist()
phi = dssp_results[dssp_results.chain == chain].phi.tolist()
psi = dssp_results[dssp_results.chain == chain].psi.tolist()
chain_prop = self.chains.get_by_id(chain)
chain_seq = chain_prop.seq_record
# Making sure the X's are filled in
ss = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain_seq,
new_seq=ss,
fill_with='-')
exposure_rsa = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain_seq,
new_seq=exposure_rsa,
fill_with=float('Inf'))
exposure_asa = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain_seq,
new_seq=exposure_asa,
fill_with=float('Inf'))
phi = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain_seq,
new_seq=phi,
fill_with=float('Inf'))
psi = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain_seq,
new_seq=psi,
fill_with=float('Inf'))
chain_prop.seq_record.annotations.update(dssp_summary[chain])
chain_prop.seq_record.letter_annotations['SS-dssp'] = ss
chain_prop.seq_record.letter_annotations['RSA-dssp'] = exposure_rsa
chain_prop.seq_record.letter_annotations['ASA-dssp'] = exposure_asa
chain_prop.seq_record.letter_annotations['PHI-dssp'] = phi
chain_prop.seq_record.letter_annotations['PSI-dssp'] = psi
log.debug('{}: stored DSSP annotations in chain seq_record letter_annotations'.format(chain)) | python | def get_dssp_annotations(self, outdir, force_rerun=False):
"""Run DSSP on this structure and store the DSSP annotations in the corresponding ChainProp SeqRecords
Calculations are stored in the ChainProp's ``letter_annotations`` at the following keys:
* ``SS-dssp``
* ``RSA-dssp``
* ``ASA-dssp``
* ``PHI-dssp``
* ``PSI-dssp``
Args:
outdir (str): Path to where DSSP dataframe will be stored.
force_rerun (bool): If DSSP results should be recalculated
TODO:
* Also parse global properties, like total accessible surface area. Don't think Biopython parses those?
"""
if self.structure:
parsed = self.structure
else:
parsed = self.parse_structure()
if not parsed:
log.error('{}: unable to open structure to run DSSP'.format(self.id))
return
log.debug('{}: running DSSP'.format(self.id))
dssp_results = ssbio.protein.structure.properties.dssp.get_dssp_df(model=parsed.first_model,
pdb_file=self.structure_path,
outdir=outdir,
force_rerun=force_rerun)
if dssp_results.empty:
log.error('{}: unable to run DSSP'.format(self.id))
return
chains = dssp_results.chain.unique()
dssp_summary = ssbio.protein.structure.properties.dssp.secondary_structure_summary(dssp_results)
for chain in chains:
ss = dssp_results[dssp_results.chain == chain].ss.tolist()
exposure_rsa = dssp_results[dssp_results.chain == chain].exposure_rsa.tolist()
exposure_asa = dssp_results[dssp_results.chain == chain].exposure_asa.tolist()
phi = dssp_results[dssp_results.chain == chain].phi.tolist()
psi = dssp_results[dssp_results.chain == chain].psi.tolist()
chain_prop = self.chains.get_by_id(chain)
chain_seq = chain_prop.seq_record
# Making sure the X's are filled in
ss = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain_seq,
new_seq=ss,
fill_with='-')
exposure_rsa = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain_seq,
new_seq=exposure_rsa,
fill_with=float('Inf'))
exposure_asa = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain_seq,
new_seq=exposure_asa,
fill_with=float('Inf'))
phi = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain_seq,
new_seq=phi,
fill_with=float('Inf'))
psi = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain_seq,
new_seq=psi,
fill_with=float('Inf'))
chain_prop.seq_record.annotations.update(dssp_summary[chain])
chain_prop.seq_record.letter_annotations['SS-dssp'] = ss
chain_prop.seq_record.letter_annotations['RSA-dssp'] = exposure_rsa
chain_prop.seq_record.letter_annotations['ASA-dssp'] = exposure_asa
chain_prop.seq_record.letter_annotations['PHI-dssp'] = phi
chain_prop.seq_record.letter_annotations['PSI-dssp'] = psi
log.debug('{}: stored DSSP annotations in chain seq_record letter_annotations'.format(chain)) | [
"def",
"get_dssp_annotations",
"(",
"self",
",",
"outdir",
",",
"force_rerun",
"=",
"False",
")",
":",
"if",
"self",
".",
"structure",
":",
"parsed",
"=",
"self",
".",
"structure",
"else",
":",
"parsed",
"=",
"self",
".",
"parse_structure",
"(",
")",
"if... | Run DSSP on this structure and store the DSSP annotations in the corresponding ChainProp SeqRecords
Calculations are stored in the ChainProp's ``letter_annotations`` at the following keys:
* ``SS-dssp``
* ``RSA-dssp``
* ``ASA-dssp``
* ``PHI-dssp``
* ``PSI-dssp``
Args:
outdir (str): Path to where DSSP dataframe will be stored.
force_rerun (bool): If DSSP results should be recalculated
TODO:
* Also parse global properties, like total accessible surface area. Don't think Biopython parses those? | [
"Run",
"DSSP",
"on",
"this",
"structure",
"and",
"store",
"the",
"DSSP",
"annotations",
"in",
"the",
"corresponding",
"ChainProp",
"SeqRecords"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/structprop.py#L424-L499 | train | 29,103 |
SBRG/ssbio | ssbio/protein/structure/structprop.py | StructProp.get_freesasa_annotations | def get_freesasa_annotations(self, outdir, include_hetatms=False, force_rerun=False):
"""Run ``freesasa`` on this structure and store the calculated properties in the corresponding ChainProps
"""
if self.file_type != 'pdb':
log.error('{}: unable to run freesasa with "{}" file type. Please change file type to "pdb"'.format(self.id,
self.file_type))
return
# Parse the structure to store chain sequences
if self.structure:
parsed = self.structure
else:
parsed = self.parse_structure()
if not parsed:
log.error('{}: unable to open structure to run freesasa'.format(self.id))
return
# Set outfile name
log.debug('{}: running freesasa'.format(self.id))
if include_hetatms:
outfile = '{}.freesasa_het.rsa'.format(self.id)
else:
outfile = '{}.freesasa_nohet.rsa'.format(self.id)
# Run freesasa
result = fs.run_freesasa(infile=self.structure_path,
outfile=outfile,
include_hetatms=include_hetatms,
outdir=outdir,
force_rerun=force_rerun)
# Parse results
result_parsed = fs.parse_rsa_data(result)
prop_dict = defaultdict(lambda: defaultdict(list))
for k, v in result_parsed.items():
chain = k[0]
for prop, calc in v.items():
prop_dict[chain][prop].append(calc)
# Reorganize and store results
all_props = ['all_atoms_abs', 'all_atoms_rel', 'side_chain_abs', 'side_chain_rel', 'main_chain_abs',
'main_chain_rel', 'non_polar_abs', 'non_polar_rel', 'all_polar_abs', 'all_polar_rel']
all_props_renamed = {'all_atoms_abs' : 'ASA_ALL-freesasa',
'all_atoms_rel' : 'RSA_ALL-freesasa',
'all_polar_abs' : 'ASA_POLAR-freesasa',
'all_polar_rel' : 'RSA_POLAR-freesasa',
'main_chain_abs': 'ASA_BACKBONE-freesasa',
'main_chain_rel': 'RSA_BACKBONE-freesasa',
'non_polar_abs' : 'ASA_NONPOLAR-freesasa',
'non_polar_rel' : 'RSA_NONPOLAR-freesasa',
'side_chain_abs': 'ASA_RESIDUE-freesasa',
'side_chain_rel': 'RSA_RESIDUE-freesasa'}
## Rename dictionary keys based on if HETATMs were included
if include_hetatms:
suffix = '_het'
else:
suffix = '_nohet'
for k, v in all_props_renamed.items():
all_props_renamed[k] = v + suffix
for chain in self.chains:
for prop in all_props:
prop_list = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain.seq_record,
new_seq=prop_dict[chain.id][prop],
fill_with=float('Inf'),
ignore_excess=True)
chain.seq_record.letter_annotations[all_props_renamed[prop]] = prop_list
log.debug('{}: stored freesasa calculations in chain seq_record letter_annotations'.format(chain)) | python | def get_freesasa_annotations(self, outdir, include_hetatms=False, force_rerun=False):
"""Run ``freesasa`` on this structure and store the calculated properties in the corresponding ChainProps
"""
if self.file_type != 'pdb':
log.error('{}: unable to run freesasa with "{}" file type. Please change file type to "pdb"'.format(self.id,
self.file_type))
return
# Parse the structure to store chain sequences
if self.structure:
parsed = self.structure
else:
parsed = self.parse_structure()
if not parsed:
log.error('{}: unable to open structure to run freesasa'.format(self.id))
return
# Set outfile name
log.debug('{}: running freesasa'.format(self.id))
if include_hetatms:
outfile = '{}.freesasa_het.rsa'.format(self.id)
else:
outfile = '{}.freesasa_nohet.rsa'.format(self.id)
# Run freesasa
result = fs.run_freesasa(infile=self.structure_path,
outfile=outfile,
include_hetatms=include_hetatms,
outdir=outdir,
force_rerun=force_rerun)
# Parse results
result_parsed = fs.parse_rsa_data(result)
prop_dict = defaultdict(lambda: defaultdict(list))
for k, v in result_parsed.items():
chain = k[0]
for prop, calc in v.items():
prop_dict[chain][prop].append(calc)
# Reorganize and store results
all_props = ['all_atoms_abs', 'all_atoms_rel', 'side_chain_abs', 'side_chain_rel', 'main_chain_abs',
'main_chain_rel', 'non_polar_abs', 'non_polar_rel', 'all_polar_abs', 'all_polar_rel']
all_props_renamed = {'all_atoms_abs' : 'ASA_ALL-freesasa',
'all_atoms_rel' : 'RSA_ALL-freesasa',
'all_polar_abs' : 'ASA_POLAR-freesasa',
'all_polar_rel' : 'RSA_POLAR-freesasa',
'main_chain_abs': 'ASA_BACKBONE-freesasa',
'main_chain_rel': 'RSA_BACKBONE-freesasa',
'non_polar_abs' : 'ASA_NONPOLAR-freesasa',
'non_polar_rel' : 'RSA_NONPOLAR-freesasa',
'side_chain_abs': 'ASA_RESIDUE-freesasa',
'side_chain_rel': 'RSA_RESIDUE-freesasa'}
## Rename dictionary keys based on if HETATMs were included
if include_hetatms:
suffix = '_het'
else:
suffix = '_nohet'
for k, v in all_props_renamed.items():
all_props_renamed[k] = v + suffix
for chain in self.chains:
for prop in all_props:
prop_list = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain.seq_record,
new_seq=prop_dict[chain.id][prop],
fill_with=float('Inf'),
ignore_excess=True)
chain.seq_record.letter_annotations[all_props_renamed[prop]] = prop_list
log.debug('{}: stored freesasa calculations in chain seq_record letter_annotations'.format(chain)) | [
"def",
"get_freesasa_annotations",
"(",
"self",
",",
"outdir",
",",
"include_hetatms",
"=",
"False",
",",
"force_rerun",
"=",
"False",
")",
":",
"if",
"self",
".",
"file_type",
"!=",
"'pdb'",
":",
"log",
".",
"error",
"(",
"'{}: unable to run freesasa with \"{}\... | Run ``freesasa`` on this structure and store the calculated properties in the corresponding ChainProps | [
"Run",
"freesasa",
"on",
"this",
"structure",
"and",
"store",
"the",
"calculated",
"properties",
"in",
"the",
"corresponding",
"ChainProps"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/structprop.py#L548-L618 | train | 29,104 |
SBRG/ssbio | ssbio/protein/structure/structprop.py | StructProp.view_structure | def view_structure(self, only_chains=None, opacity=1.0, recolor=False, gui=False):
"""Use NGLviewer to display a structure in a Jupyter notebook
Args:
only_chains (str, list): Chain ID or IDs to display
opacity (float): Opacity of the structure
recolor (bool): If structure should be cleaned and recolored to silver
gui (bool): If the NGLview GUI should show up
Returns:
NGLviewer object
"""
# TODO: show_structure_file does not work for MMTF files - need to check for that and load accordingly
if ssbio.utils.is_ipynb():
import nglview as nv
else:
raise EnvironmentError('Unable to display structure - not running in a Jupyter notebook environment')
if not self.structure_file:
raise ValueError("Structure file not loaded")
only_chains = ssbio.utils.force_list(only_chains)
to_show_chains = '( '
for c in only_chains:
to_show_chains += ':{} or'.format(c)
to_show_chains = to_show_chains.strip(' or ')
to_show_chains += ' )'
if self.file_type == 'mmtf' or self.file_type == 'mmtf.gz':
view = nv.NGLWidget()
view.add_component(self.structure_path)
else:
view = nv.show_structure_file(self.structure_path, gui=gui)
if recolor:
view.clear_representations()
if only_chains:
view.add_cartoon(selection='{} and (not hydrogen)'.format(to_show_chains), color='silver', opacity=opacity)
else:
view.add_cartoon(selection='protein', color='silver', opacity=opacity)
elif only_chains:
view.clear_representations()
view.add_cartoon(selection='{} and (not hydrogen)'.format(to_show_chains), color='silver', opacity=opacity)
return view | python | def view_structure(self, only_chains=None, opacity=1.0, recolor=False, gui=False):
"""Use NGLviewer to display a structure in a Jupyter notebook
Args:
only_chains (str, list): Chain ID or IDs to display
opacity (float): Opacity of the structure
recolor (bool): If structure should be cleaned and recolored to silver
gui (bool): If the NGLview GUI should show up
Returns:
NGLviewer object
"""
# TODO: show_structure_file does not work for MMTF files - need to check for that and load accordingly
if ssbio.utils.is_ipynb():
import nglview as nv
else:
raise EnvironmentError('Unable to display structure - not running in a Jupyter notebook environment')
if not self.structure_file:
raise ValueError("Structure file not loaded")
only_chains = ssbio.utils.force_list(only_chains)
to_show_chains = '( '
for c in only_chains:
to_show_chains += ':{} or'.format(c)
to_show_chains = to_show_chains.strip(' or ')
to_show_chains += ' )'
if self.file_type == 'mmtf' or self.file_type == 'mmtf.gz':
view = nv.NGLWidget()
view.add_component(self.structure_path)
else:
view = nv.show_structure_file(self.structure_path, gui=gui)
if recolor:
view.clear_representations()
if only_chains:
view.add_cartoon(selection='{} and (not hydrogen)'.format(to_show_chains), color='silver', opacity=opacity)
else:
view.add_cartoon(selection='protein', color='silver', opacity=opacity)
elif only_chains:
view.clear_representations()
view.add_cartoon(selection='{} and (not hydrogen)'.format(to_show_chains), color='silver', opacity=opacity)
return view | [
"def",
"view_structure",
"(",
"self",
",",
"only_chains",
"=",
"None",
",",
"opacity",
"=",
"1.0",
",",
"recolor",
"=",
"False",
",",
"gui",
"=",
"False",
")",
":",
"# TODO: show_structure_file does not work for MMTF files - need to check for that and load accordingly",
... | Use NGLviewer to display a structure in a Jupyter notebook
Args:
only_chains (str, list): Chain ID or IDs to display
opacity (float): Opacity of the structure
recolor (bool): If structure should be cleaned and recolored to silver
gui (bool): If the NGLview GUI should show up
Returns:
NGLviewer object | [
"Use",
"NGLviewer",
"to",
"display",
"a",
"structure",
"in",
"a",
"Jupyter",
"notebook"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/structprop.py#L620-L666 | train | 29,105 |
SBRG/ssbio | ssbio/protein/sequence/properties/tmhmm.py | label_TM_tmhmm_residue_numbers_and_leaflets | def label_TM_tmhmm_residue_numbers_and_leaflets(tmhmm_seq):
"""Determine the residue numbers of the TM-helix residues that cross the membrane and label them by leaflet.
Args:
tmhmm_seq: g.protein.representative_sequence.seq_record.letter_annotations['TM-tmhmm']
Returns:
leaflet_dict: a dictionary with leaflet_variable : [residue list] where the variable is inside or outside
TM_boundary dict: outputs a dictionar with : TM helix number : [TM helix residue start , TM helix residue end]
TODO:
untested method!
"""
TM_number_dict = {}
T_index = []
T_residue = []
residue_count = 1
for residue_label in tmhmm_seq:
if residue_label == 'T':
T_residue.append(residue_count)
residue_count = residue_count + 1
TM_number_dict.update({'T_residue': T_residue})
# finding the TM boundaries
T_residue_list = TM_number_dict['T_residue']
count = 0
max_count = len(T_residue_list) - 1
TM_helix_count = 0
TM_boundary_dict = {}
while count <= max_count:
# first residue = TM start
if count == 0:
TM_start = T_residue_list[count]
count = count + 1
continue
# Last residue = TM end
elif count == max_count:
TM_end = T_residue_list[count]
TM_helix_count = TM_helix_count + 1
TM_boundary_dict.update({'TM_helix_' + str(TM_helix_count): [TM_start, TM_end]})
break
# middle residues need to be start or end
elif T_residue_list[count] != T_residue_list[count + 1] - 1:
TM_end = T_residue_list[count]
TM_helix_count = TM_helix_count + 1
TM_boundary_dict.update({'TM_helix_' + str(TM_helix_count): [TM_start, TM_end]})
# new TM_start
TM_start = T_residue_list[count + 1]
count = count + 1
# assign leaflet to proper TM residues O or I
leaflet_dict = {}
for leaflet in ['O', 'I']:
leaflet_list = []
for TM_helix, TM_residues in TM_boundary_dict.items():
for residue_num in TM_residues:
tmhmm_seq_index = residue_num - 1
previous_residue = tmhmm_seq_index - 1
next_residue = tmhmm_seq_index + 1
# identify if the previous or next residue closest to the TM helix start/end is the proper leaflet
if tmhmm_seq[previous_residue] == leaflet or tmhmm_seq[next_residue] == leaflet:
leaflet_list.append(residue_num)
leaflet_dict.update({'tmhmm_leaflet_' + leaflet: leaflet_list})
return TM_boundary_dict, leaflet_dict | python | def label_TM_tmhmm_residue_numbers_and_leaflets(tmhmm_seq):
"""Determine the residue numbers of the TM-helix residues that cross the membrane and label them by leaflet.
Args:
tmhmm_seq: g.protein.representative_sequence.seq_record.letter_annotations['TM-tmhmm']
Returns:
leaflet_dict: a dictionary with leaflet_variable : [residue list] where the variable is inside or outside
TM_boundary dict: outputs a dictionar with : TM helix number : [TM helix residue start , TM helix residue end]
TODO:
untested method!
"""
TM_number_dict = {}
T_index = []
T_residue = []
residue_count = 1
for residue_label in tmhmm_seq:
if residue_label == 'T':
T_residue.append(residue_count)
residue_count = residue_count + 1
TM_number_dict.update({'T_residue': T_residue})
# finding the TM boundaries
T_residue_list = TM_number_dict['T_residue']
count = 0
max_count = len(T_residue_list) - 1
TM_helix_count = 0
TM_boundary_dict = {}
while count <= max_count:
# first residue = TM start
if count == 0:
TM_start = T_residue_list[count]
count = count + 1
continue
# Last residue = TM end
elif count == max_count:
TM_end = T_residue_list[count]
TM_helix_count = TM_helix_count + 1
TM_boundary_dict.update({'TM_helix_' + str(TM_helix_count): [TM_start, TM_end]})
break
# middle residues need to be start or end
elif T_residue_list[count] != T_residue_list[count + 1] - 1:
TM_end = T_residue_list[count]
TM_helix_count = TM_helix_count + 1
TM_boundary_dict.update({'TM_helix_' + str(TM_helix_count): [TM_start, TM_end]})
# new TM_start
TM_start = T_residue_list[count + 1]
count = count + 1
# assign leaflet to proper TM residues O or I
leaflet_dict = {}
for leaflet in ['O', 'I']:
leaflet_list = []
for TM_helix, TM_residues in TM_boundary_dict.items():
for residue_num in TM_residues:
tmhmm_seq_index = residue_num - 1
previous_residue = tmhmm_seq_index - 1
next_residue = tmhmm_seq_index + 1
# identify if the previous or next residue closest to the TM helix start/end is the proper leaflet
if tmhmm_seq[previous_residue] == leaflet or tmhmm_seq[next_residue] == leaflet:
leaflet_list.append(residue_num)
leaflet_dict.update({'tmhmm_leaflet_' + leaflet: leaflet_list})
return TM_boundary_dict, leaflet_dict | [
"def",
"label_TM_tmhmm_residue_numbers_and_leaflets",
"(",
"tmhmm_seq",
")",
":",
"TM_number_dict",
"=",
"{",
"}",
"T_index",
"=",
"[",
"]",
"T_residue",
"=",
"[",
"]",
"residue_count",
"=",
"1",
"for",
"residue_label",
"in",
"tmhmm_seq",
":",
"if",
"residue_lab... | Determine the residue numbers of the TM-helix residues that cross the membrane and label them by leaflet.
Args:
tmhmm_seq: g.protein.representative_sequence.seq_record.letter_annotations['TM-tmhmm']
Returns:
leaflet_dict: a dictionary with leaflet_variable : [residue list] where the variable is inside or outside
TM_boundary dict: outputs a dictionar with : TM helix number : [TM helix residue start , TM helix residue end]
TODO:
untested method! | [
"Determine",
"the",
"residue",
"numbers",
"of",
"the",
"TM",
"-",
"helix",
"residues",
"that",
"cross",
"the",
"membrane",
"and",
"label",
"them",
"by",
"leaflet",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/properties/tmhmm.py#L101-L169 | train | 29,106 |
SBRG/ssbio | ssbio/protein/sequence/properties/residues.py | biopython_protein_scale | def biopython_protein_scale(inseq, scale, custom_scale_dict=None, window=7):
"""Use Biopython to calculate properties using a sliding window over a sequence given a specific scale to use."""
if scale == 'kd_hydrophobicity':
scale_dict = kd_hydrophobicity_one
elif scale == 'bulkiness':
scale_dict = bulkiness_one
elif scale == 'custom':
scale_dict = custom_scale_dict
else:
raise ValueError('Scale not available')
inseq = ssbio.protein.sequence.utils.cast_to_str(inseq)
analysed_seq = ProteinAnalysis(inseq)
result = analysed_seq.protein_scale(param_dict=scale_dict, window=window)
# Correct list length by prepending and appending "inf" (result needs to be same length as sequence)
for i in range(window // 2):
result.insert(0, float("Inf"))
result.append(float("Inf"))
return result | python | def biopython_protein_scale(inseq, scale, custom_scale_dict=None, window=7):
"""Use Biopython to calculate properties using a sliding window over a sequence given a specific scale to use."""
if scale == 'kd_hydrophobicity':
scale_dict = kd_hydrophobicity_one
elif scale == 'bulkiness':
scale_dict = bulkiness_one
elif scale == 'custom':
scale_dict = custom_scale_dict
else:
raise ValueError('Scale not available')
inseq = ssbio.protein.sequence.utils.cast_to_str(inseq)
analysed_seq = ProteinAnalysis(inseq)
result = analysed_seq.protein_scale(param_dict=scale_dict, window=window)
# Correct list length by prepending and appending "inf" (result needs to be same length as sequence)
for i in range(window // 2):
result.insert(0, float("Inf"))
result.append(float("Inf"))
return result | [
"def",
"biopython_protein_scale",
"(",
"inseq",
",",
"scale",
",",
"custom_scale_dict",
"=",
"None",
",",
"window",
"=",
"7",
")",
":",
"if",
"scale",
"==",
"'kd_hydrophobicity'",
":",
"scale_dict",
"=",
"kd_hydrophobicity_one",
"elif",
"scale",
"==",
"'bulkines... | Use Biopython to calculate properties using a sliding window over a sequence given a specific scale to use. | [
"Use",
"Biopython",
"to",
"calculate",
"properties",
"using",
"a",
"sliding",
"window",
"over",
"a",
"sequence",
"given",
"a",
"specific",
"scale",
"to",
"use",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/properties/residues.py#L113-L134 | train | 29,107 |
SBRG/ssbio | ssbio/protein/sequence/properties/residues.py | biopython_protein_analysis | def biopython_protein_analysis(inseq):
"""Utiize Biopython's ProteinAnalysis module to return general sequence properties of an amino acid string.
For full definitions see: http://biopython.org/DIST/docs/api/Bio.SeqUtils.ProtParam.ProteinAnalysis-class.html
Args:
inseq: Amino acid sequence
Returns:
dict: Dictionary of sequence properties. Some definitions include:
instability_index: Any value above 40 means the protein is unstable (has a short half life).
secondary_structure_fraction: Percentage of protein in helix, turn or sheet
TODO:
Finish definitions of dictionary
"""
inseq = ssbio.protein.sequence.utils.cast_to_str(inseq)
analysed_seq = ProteinAnalysis(inseq)
info_dict = {}
info_dict['amino_acids_content-biop'] = analysed_seq.count_amino_acids()
info_dict['amino_acids_percent-biop'] = analysed_seq.get_amino_acids_percent()
info_dict['length-biop'] = analysed_seq.length
info_dict['monoisotopic-biop'] = analysed_seq.monoisotopic
info_dict['molecular_weight-biop'] = analysed_seq.molecular_weight()
info_dict['aromaticity-biop'] = analysed_seq.aromaticity()
info_dict['instability_index-biop'] = analysed_seq.instability_index()
# TODO: What is flexibility?
info_dict['flexibility-biop'] = analysed_seq.flexibility()
info_dict['isoelectric_point-biop'] = analysed_seq.isoelectric_point()
# grand average of hydrophobicity
info_dict['gravy-biop'] = analysed_seq.gravy()
# Separated secondary_structure_fraction into each definition
# info_dict['secondary_structure_fraction-biop'] = analysed_seq.secondary_structure_fraction()
info_dict['percent_helix_naive-biop'] = analysed_seq.secondary_structure_fraction()[0]
info_dict['percent_turn_naive-biop'] = analysed_seq.secondary_structure_fraction()[1]
info_dict['percent_strand_naive-biop'] = analysed_seq.secondary_structure_fraction()[2]
return info_dict | python | def biopython_protein_analysis(inseq):
"""Utiize Biopython's ProteinAnalysis module to return general sequence properties of an amino acid string.
For full definitions see: http://biopython.org/DIST/docs/api/Bio.SeqUtils.ProtParam.ProteinAnalysis-class.html
Args:
inseq: Amino acid sequence
Returns:
dict: Dictionary of sequence properties. Some definitions include:
instability_index: Any value above 40 means the protein is unstable (has a short half life).
secondary_structure_fraction: Percentage of protein in helix, turn or sheet
TODO:
Finish definitions of dictionary
"""
inseq = ssbio.protein.sequence.utils.cast_to_str(inseq)
analysed_seq = ProteinAnalysis(inseq)
info_dict = {}
info_dict['amino_acids_content-biop'] = analysed_seq.count_amino_acids()
info_dict['amino_acids_percent-biop'] = analysed_seq.get_amino_acids_percent()
info_dict['length-biop'] = analysed_seq.length
info_dict['monoisotopic-biop'] = analysed_seq.monoisotopic
info_dict['molecular_weight-biop'] = analysed_seq.molecular_weight()
info_dict['aromaticity-biop'] = analysed_seq.aromaticity()
info_dict['instability_index-biop'] = analysed_seq.instability_index()
# TODO: What is flexibility?
info_dict['flexibility-biop'] = analysed_seq.flexibility()
info_dict['isoelectric_point-biop'] = analysed_seq.isoelectric_point()
# grand average of hydrophobicity
info_dict['gravy-biop'] = analysed_seq.gravy()
# Separated secondary_structure_fraction into each definition
# info_dict['secondary_structure_fraction-biop'] = analysed_seq.secondary_structure_fraction()
info_dict['percent_helix_naive-biop'] = analysed_seq.secondary_structure_fraction()[0]
info_dict['percent_turn_naive-biop'] = analysed_seq.secondary_structure_fraction()[1]
info_dict['percent_strand_naive-biop'] = analysed_seq.secondary_structure_fraction()[2]
return info_dict | [
"def",
"biopython_protein_analysis",
"(",
"inseq",
")",
":",
"inseq",
"=",
"ssbio",
".",
"protein",
".",
"sequence",
".",
"utils",
".",
"cast_to_str",
"(",
"inseq",
")",
"analysed_seq",
"=",
"ProteinAnalysis",
"(",
"inseq",
")",
"info_dict",
"=",
"{",
"}",
... | Utiize Biopython's ProteinAnalysis module to return general sequence properties of an amino acid string.
For full definitions see: http://biopython.org/DIST/docs/api/Bio.SeqUtils.ProtParam.ProteinAnalysis-class.html
Args:
inseq: Amino acid sequence
Returns:
dict: Dictionary of sequence properties. Some definitions include:
instability_index: Any value above 40 means the protein is unstable (has a short half life).
secondary_structure_fraction: Percentage of protein in helix, turn or sheet
TODO:
Finish definitions of dictionary | [
"Utiize",
"Biopython",
"s",
"ProteinAnalysis",
"module",
"to",
"return",
"general",
"sequence",
"properties",
"of",
"an",
"amino",
"acid",
"string",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/properties/residues.py#L137-L180 | train | 29,108 |
SBRG/ssbio | ssbio/protein/sequence/properties/residues.py | emboss_pepstats_on_fasta | def emboss_pepstats_on_fasta(infile, outfile='', outdir='', outext='.pepstats', force_rerun=False):
"""Run EMBOSS pepstats on a FASTA file.
Args:
infile: Path to FASTA file
outfile: Name of output file without extension
outdir: Path to output directory
outext: Extension of results file, default is ".pepstats"
force_rerun: Flag to rerun pepstats
Returns:
str: Path to output file.
"""
# Create the output file name
outfile = ssbio.utils.outfile_maker(inname=infile, outname=outfile, outdir=outdir, outext=outext)
# Run pepstats
program = 'pepstats'
pepstats_args = '-sequence="{}" -outfile="{}"'.format(infile, outfile)
cmd_string = '{} {}'.format(program, pepstats_args)
ssbio.utils.command_runner(cmd_string, force_rerun_flag=force_rerun, outfile_checker=outfile, silent=True)
return outfile | python | def emboss_pepstats_on_fasta(infile, outfile='', outdir='', outext='.pepstats', force_rerun=False):
"""Run EMBOSS pepstats on a FASTA file.
Args:
infile: Path to FASTA file
outfile: Name of output file without extension
outdir: Path to output directory
outext: Extension of results file, default is ".pepstats"
force_rerun: Flag to rerun pepstats
Returns:
str: Path to output file.
"""
# Create the output file name
outfile = ssbio.utils.outfile_maker(inname=infile, outname=outfile, outdir=outdir, outext=outext)
# Run pepstats
program = 'pepstats'
pepstats_args = '-sequence="{}" -outfile="{}"'.format(infile, outfile)
cmd_string = '{} {}'.format(program, pepstats_args)
ssbio.utils.command_runner(cmd_string, force_rerun_flag=force_rerun, outfile_checker=outfile, silent=True)
return outfile | [
"def",
"emboss_pepstats_on_fasta",
"(",
"infile",
",",
"outfile",
"=",
"''",
",",
"outdir",
"=",
"''",
",",
"outext",
"=",
"'.pepstats'",
",",
"force_rerun",
"=",
"False",
")",
":",
"# Create the output file name",
"outfile",
"=",
"ssbio",
".",
"utils",
".",
... | Run EMBOSS pepstats on a FASTA file.
Args:
infile: Path to FASTA file
outfile: Name of output file without extension
outdir: Path to output directory
outext: Extension of results file, default is ".pepstats"
force_rerun: Flag to rerun pepstats
Returns:
str: Path to output file. | [
"Run",
"EMBOSS",
"pepstats",
"on",
"a",
"FASTA",
"file",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/properties/residues.py#L183-L207 | train | 29,109 |
SBRG/ssbio | ssbio/protein/sequence/properties/residues.py | emboss_pepstats_parser | def emboss_pepstats_parser(infile):
"""Get dictionary of pepstats results.
Args:
infile: Path to pepstats outfile
Returns:
dict: Parsed information from pepstats
TODO:
Only currently parsing the bottom of the file for percentages of properties.
"""
with open(infile) as f:
lines = f.read().split('\n')
info_dict = {}
for l in lines[38:47]:
info = l.split('\t')
cleaninfo = list(filter(lambda x: x != '', info))
prop = cleaninfo[0]
num = cleaninfo[2]
percent = float(cleaninfo[-1]) / float(100)
info_dict['mol_percent_' + prop.lower() + '-pepstats'] = percent
return info_dict | python | def emboss_pepstats_parser(infile):
"""Get dictionary of pepstats results.
Args:
infile: Path to pepstats outfile
Returns:
dict: Parsed information from pepstats
TODO:
Only currently parsing the bottom of the file for percentages of properties.
"""
with open(infile) as f:
lines = f.read().split('\n')
info_dict = {}
for l in lines[38:47]:
info = l.split('\t')
cleaninfo = list(filter(lambda x: x != '', info))
prop = cleaninfo[0]
num = cleaninfo[2]
percent = float(cleaninfo[-1]) / float(100)
info_dict['mol_percent_' + prop.lower() + '-pepstats'] = percent
return info_dict | [
"def",
"emboss_pepstats_parser",
"(",
"infile",
")",
":",
"with",
"open",
"(",
"infile",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"read",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"info_dict",
"=",
"{",
"}",
"for",
"l",
"in",
"lines",
"[",
"... | Get dictionary of pepstats results.
Args:
infile: Path to pepstats outfile
Returns:
dict: Parsed information from pepstats
TODO:
Only currently parsing the bottom of the file for percentages of properties. | [
"Get",
"dictionary",
"of",
"pepstats",
"results",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/properties/residues.py#L210-L237 | train | 29,110 |
SBRG/ssbio | ssbio/pipeline/atlas.py | ATLAS.load_strain | def load_strain(self, strain_id, strain_genome_file):
"""Load a strain as a new GEM-PRO by its ID and associated genome file. Stored in the ``strains`` attribute.
Args:
strain_id (str): Strain ID
strain_genome_file (str): Path to strain genome file
"""
# logging.disable(logging.WARNING)
strain_gp = GEMPRO(gem_name=strain_id, genome_path=strain_genome_file, write_protein_fasta_files=False)
# logging.disable(logging.NOTSET)
self.strains.append(strain_gp)
return self.strains.get_by_id(strain_id) | python | def load_strain(self, strain_id, strain_genome_file):
"""Load a strain as a new GEM-PRO by its ID and associated genome file. Stored in the ``strains`` attribute.
Args:
strain_id (str): Strain ID
strain_genome_file (str): Path to strain genome file
"""
# logging.disable(logging.WARNING)
strain_gp = GEMPRO(gem_name=strain_id, genome_path=strain_genome_file, write_protein_fasta_files=False)
# logging.disable(logging.NOTSET)
self.strains.append(strain_gp)
return self.strains.get_by_id(strain_id) | [
"def",
"load_strain",
"(",
"self",
",",
"strain_id",
",",
"strain_genome_file",
")",
":",
"# logging.disable(logging.WARNING)",
"strain_gp",
"=",
"GEMPRO",
"(",
"gem_name",
"=",
"strain_id",
",",
"genome_path",
"=",
"strain_genome_file",
",",
"write_protein_fasta_files"... | Load a strain as a new GEM-PRO by its ID and associated genome file. Stored in the ``strains`` attribute.
Args:
strain_id (str): Strain ID
strain_genome_file (str): Path to strain genome file | [
"Load",
"a",
"strain",
"as",
"a",
"new",
"GEM",
"-",
"PRO",
"by",
"its",
"ID",
"and",
"associated",
"genome",
"file",
".",
"Stored",
"in",
"the",
"strains",
"attribute",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas.py#L212-L225 | train | 29,111 |
SBRG/ssbio | ssbio/pipeline/atlas.py | ATLAS.download_patric_genomes | def download_patric_genomes(self, ids, force_rerun=False):
"""Download genome files from PATRIC given a list of PATRIC genome IDs and load them as strains.
Args:
ids (str, list): PATRIC ID or list of PATRIC IDs
force_rerun (bool): If genome files should be downloaded again even if they exist
"""
ids = ssbio.utils.force_list(ids)
counter = 0
log.info('Downloading sequences from PATRIC...')
for patric_id in tqdm(ids):
f = ssbio.databases.patric.download_coding_sequences(patric_id=patric_id, seqtype='protein',
outdir=self.sequences_by_organism_dir,
force_rerun=force_rerun)
if f:
self.load_strain(patric_id, f)
counter += 1
log.debug('{}: downloaded sequence'.format(patric_id))
else:
log.warning('{}: unable to download sequence'.format(patric_id))
log.info('Created {} new strain GEM-PROs, accessible at "strains" attribute'.format(counter)) | python | def download_patric_genomes(self, ids, force_rerun=False):
"""Download genome files from PATRIC given a list of PATRIC genome IDs and load them as strains.
Args:
ids (str, list): PATRIC ID or list of PATRIC IDs
force_rerun (bool): If genome files should be downloaded again even if they exist
"""
ids = ssbio.utils.force_list(ids)
counter = 0
log.info('Downloading sequences from PATRIC...')
for patric_id in tqdm(ids):
f = ssbio.databases.patric.download_coding_sequences(patric_id=patric_id, seqtype='protein',
outdir=self.sequences_by_organism_dir,
force_rerun=force_rerun)
if f:
self.load_strain(patric_id, f)
counter += 1
log.debug('{}: downloaded sequence'.format(patric_id))
else:
log.warning('{}: unable to download sequence'.format(patric_id))
log.info('Created {} new strain GEM-PROs, accessible at "strains" attribute'.format(counter)) | [
"def",
"download_patric_genomes",
"(",
"self",
",",
"ids",
",",
"force_rerun",
"=",
"False",
")",
":",
"ids",
"=",
"ssbio",
".",
"utils",
".",
"force_list",
"(",
"ids",
")",
"counter",
"=",
"0",
"log",
".",
"info",
"(",
"'Downloading sequences from PATRIC...... | Download genome files from PATRIC given a list of PATRIC genome IDs and load them as strains.
Args:
ids (str, list): PATRIC ID or list of PATRIC IDs
force_rerun (bool): If genome files should be downloaded again even if they exist | [
"Download",
"genome",
"files",
"from",
"PATRIC",
"given",
"a",
"list",
"of",
"PATRIC",
"genome",
"IDs",
"and",
"load",
"them",
"as",
"strains",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas.py#L227-L250 | train | 29,112 |
SBRG/ssbio | ssbio/pipeline/atlas.py | ATLAS._pare_down_model | def _pare_down_model(self, strain_gempro, genes_to_remove):
"""Mark genes as non-functional in a GEM-PRO. If there is a COBRApy model associated with it, the
COBRApy method delete_model_genes is utilized to delete genes.
Args:
strain_gempro (GEMPRO): GEMPRO object
genes_to_remove (list): List of gene IDs to remove from the model
"""
# Filter out genes in genes_to_remove which do not show up in the model
strain_genes = [x.id for x in strain_gempro.genes]
genes_to_remove.extend(self.missing_in_orthology_matrix)
genes_to_remove = list(set(genes_to_remove).intersection(set(strain_genes)))
if len(genes_to_remove) == 0:
log.info('{}: no genes marked non-functional'.format(strain_gempro.id))
return
else:
log.debug('{}: {} genes to be marked non-functional'.format(strain_gempro.id, len(genes_to_remove)))
# If a COBRApy model exists, utilize the delete_model_genes method
if strain_gempro.model:
strain_gempro.model._trimmed = False
strain_gempro.model._trimmed_genes = []
strain_gempro.model._trimmed_reactions = {}
# Delete genes!
cobra.manipulation.delete_model_genes(strain_gempro.model, genes_to_remove)
if strain_gempro.model._trimmed:
log.info('{}: marked {} genes as non-functional, '
'deactivating {} reactions'.format(strain_gempro.id, len(strain_gempro.model._trimmed_genes),
len(strain_gempro.model._trimmed_reactions)))
# Otherwise, just mark the genes as non-functional
else:
for g in genes_to_remove:
strain_gempro.genes.get_by_id(g).functional = False
log.info('{}: marked {} genes as non-functional'.format(strain_gempro.id, len(genes_to_remove))) | python | def _pare_down_model(self, strain_gempro, genes_to_remove):
"""Mark genes as non-functional in a GEM-PRO. If there is a COBRApy model associated with it, the
COBRApy method delete_model_genes is utilized to delete genes.
Args:
strain_gempro (GEMPRO): GEMPRO object
genes_to_remove (list): List of gene IDs to remove from the model
"""
# Filter out genes in genes_to_remove which do not show up in the model
strain_genes = [x.id for x in strain_gempro.genes]
genes_to_remove.extend(self.missing_in_orthology_matrix)
genes_to_remove = list(set(genes_to_remove).intersection(set(strain_genes)))
if len(genes_to_remove) == 0:
log.info('{}: no genes marked non-functional'.format(strain_gempro.id))
return
else:
log.debug('{}: {} genes to be marked non-functional'.format(strain_gempro.id, len(genes_to_remove)))
# If a COBRApy model exists, utilize the delete_model_genes method
if strain_gempro.model:
strain_gempro.model._trimmed = False
strain_gempro.model._trimmed_genes = []
strain_gempro.model._trimmed_reactions = {}
# Delete genes!
cobra.manipulation.delete_model_genes(strain_gempro.model, genes_to_remove)
if strain_gempro.model._trimmed:
log.info('{}: marked {} genes as non-functional, '
'deactivating {} reactions'.format(strain_gempro.id, len(strain_gempro.model._trimmed_genes),
len(strain_gempro.model._trimmed_reactions)))
# Otherwise, just mark the genes as non-functional
else:
for g in genes_to_remove:
strain_gempro.genes.get_by_id(g).functional = False
log.info('{}: marked {} genes as non-functional'.format(strain_gempro.id, len(genes_to_remove))) | [
"def",
"_pare_down_model",
"(",
"self",
",",
"strain_gempro",
",",
"genes_to_remove",
")",
":",
"# Filter out genes in genes_to_remove which do not show up in the model",
"strain_genes",
"=",
"[",
"x",
".",
"id",
"for",
"x",
"in",
"strain_gempro",
".",
"genes",
"]",
"... | Mark genes as non-functional in a GEM-PRO. If there is a COBRApy model associated with it, the
COBRApy method delete_model_genes is utilized to delete genes.
Args:
strain_gempro (GEMPRO): GEMPRO object
genes_to_remove (list): List of gene IDs to remove from the model | [
"Mark",
"genes",
"as",
"non",
"-",
"functional",
"in",
"a",
"GEM",
"-",
"PRO",
".",
"If",
"there",
"is",
"a",
"COBRApy",
"model",
"associated",
"with",
"it",
"the",
"COBRApy",
"method",
"delete_model_genes",
"is",
"utilized",
"to",
"delete",
"genes",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas.py#L418-L455 | train | 29,113 |
SBRG/ssbio | ssbio/pipeline/atlas.py | ATLAS._load_strain_sequences | def _load_strain_sequences(self, strain_gempro):
"""Load strain sequences from the orthology matrix into the base model for comparisons, and into the
strain-specific model itself.
"""
if self._orthology_matrix_has_sequences: # Load directly from the orthology matrix if it contains sequences
strain_sequences = self.df_orthology_matrix[strain_gempro.id].to_dict()
else: # Otherwise load from the genome file if the orthology matrix contains gene IDs
# Load the genome FASTA file
log.debug('{}: loading strain genome CDS file'.format(strain_gempro.genome_path))
strain_sequences = SeqIO.index(strain_gempro.genome_path, 'fasta')
for strain_gene in strain_gempro.genes:
if strain_gene.functional:
if self._orthology_matrix_has_sequences:
strain_gene_key = strain_gene.id
else:
# Pull the gene ID of the strain from the orthology matrix
strain_gene_key = self.df_orthology_matrix.loc[strain_gene.id, strain_gempro.id]
log.debug('{}: original gene ID to be pulled from strain fasta file'.format(strain_gene_key))
# # Load into the base strain for comparisons
ref_gene = self.reference_gempro.genes.get_by_id(strain_gene.id)
new_id = '{}_{}'.format(strain_gene.id, strain_gempro.id)
if ref_gene.protein.sequences.has_id(new_id):
log.debug('{}: sequence already loaded into reference model'.format(new_id))
continue
ref_gene.protein.load_manual_sequence(seq=strain_sequences[strain_gene_key], ident=new_id,
set_as_representative=False)
log.debug('{}: loaded sequence into reference model'.format(new_id))
# Load into the strain GEM-PRO
strain_gene.protein.load_manual_sequence(seq=strain_sequences[strain_gene_key], ident=new_id,
set_as_representative=True)
log.debug('{}: loaded sequence into strain model'.format(new_id)) | python | def _load_strain_sequences(self, strain_gempro):
"""Load strain sequences from the orthology matrix into the base model for comparisons, and into the
strain-specific model itself.
"""
if self._orthology_matrix_has_sequences: # Load directly from the orthology matrix if it contains sequences
strain_sequences = self.df_orthology_matrix[strain_gempro.id].to_dict()
else: # Otherwise load from the genome file if the orthology matrix contains gene IDs
# Load the genome FASTA file
log.debug('{}: loading strain genome CDS file'.format(strain_gempro.genome_path))
strain_sequences = SeqIO.index(strain_gempro.genome_path, 'fasta')
for strain_gene in strain_gempro.genes:
if strain_gene.functional:
if self._orthology_matrix_has_sequences:
strain_gene_key = strain_gene.id
else:
# Pull the gene ID of the strain from the orthology matrix
strain_gene_key = self.df_orthology_matrix.loc[strain_gene.id, strain_gempro.id]
log.debug('{}: original gene ID to be pulled from strain fasta file'.format(strain_gene_key))
# # Load into the base strain for comparisons
ref_gene = self.reference_gempro.genes.get_by_id(strain_gene.id)
new_id = '{}_{}'.format(strain_gene.id, strain_gempro.id)
if ref_gene.protein.sequences.has_id(new_id):
log.debug('{}: sequence already loaded into reference model'.format(new_id))
continue
ref_gene.protein.load_manual_sequence(seq=strain_sequences[strain_gene_key], ident=new_id,
set_as_representative=False)
log.debug('{}: loaded sequence into reference model'.format(new_id))
# Load into the strain GEM-PRO
strain_gene.protein.load_manual_sequence(seq=strain_sequences[strain_gene_key], ident=new_id,
set_as_representative=True)
log.debug('{}: loaded sequence into strain model'.format(new_id)) | [
"def",
"_load_strain_sequences",
"(",
"self",
",",
"strain_gempro",
")",
":",
"if",
"self",
".",
"_orthology_matrix_has_sequences",
":",
"# Load directly from the orthology matrix if it contains sequences",
"strain_sequences",
"=",
"self",
".",
"df_orthology_matrix",
"[",
"st... | Load strain sequences from the orthology matrix into the base model for comparisons, and into the
strain-specific model itself. | [
"Load",
"strain",
"sequences",
"from",
"the",
"orthology",
"matrix",
"into",
"the",
"base",
"model",
"for",
"comparisons",
"and",
"into",
"the",
"strain",
"-",
"specific",
"model",
"itself",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas.py#L457-L491 | train | 29,114 |
SBRG/ssbio | ssbio/pipeline/atlas.py | ATLAS.build_strain_specific_models | def build_strain_specific_models(self, save_models=False):
"""Using the orthologous genes matrix, create and modify the strain specific models based on if orthologous
genes exist.
Also store the sequences directly in the reference GEM-PRO protein sequence attribute for the strains.
"""
if len(self.df_orthology_matrix) == 0:
raise RuntimeError('Empty orthology matrix')
# Create an emptied copy of the reference GEM-PRO
for strain_gempro in tqdm(self.strains):
log.debug('{}: building strain specific model'.format(strain_gempro.id))
# For each genome, load the metabolic model or genes from the reference GEM-PRO
logging.disable(logging.WARNING)
if self._empty_reference_gempro.model:
strain_gempro.load_cobra_model(self._empty_reference_gempro.model)
elif self._empty_reference_gempro.genes:
strain_gempro.genes = [x.id for x in self._empty_reference_gempro.genes]
logging.disable(logging.NOTSET)
# Get a list of genes which do not have orthology in the strain
not_in_strain = self.df_orthology_matrix[pd.isnull(self.df_orthology_matrix[strain_gempro.id])][strain_gempro.id].index.tolist()
# Mark genes non-functional
self._pare_down_model(strain_gempro=strain_gempro, genes_to_remove=not_in_strain)
# Load sequences into the base and strain models
self._load_strain_sequences(strain_gempro=strain_gempro)
if save_models:
cobra.io.save_json_model(model=strain_gempro.model,
filename=op.join(self.model_dir, '{}.json'.format(strain_gempro.id)))
strain_gempro.save_pickle(op.join(self.model_dir, '{}_gp.pckl'.format(strain_gempro.id)))
log.info('Created {} new strain-specific models and loaded in sequences'.format(len(self.strains))) | python | def build_strain_specific_models(self, save_models=False):
"""Using the orthologous genes matrix, create and modify the strain specific models based on if orthologous
genes exist.
Also store the sequences directly in the reference GEM-PRO protein sequence attribute for the strains.
"""
if len(self.df_orthology_matrix) == 0:
raise RuntimeError('Empty orthology matrix')
# Create an emptied copy of the reference GEM-PRO
for strain_gempro in tqdm(self.strains):
log.debug('{}: building strain specific model'.format(strain_gempro.id))
# For each genome, load the metabolic model or genes from the reference GEM-PRO
logging.disable(logging.WARNING)
if self._empty_reference_gempro.model:
strain_gempro.load_cobra_model(self._empty_reference_gempro.model)
elif self._empty_reference_gempro.genes:
strain_gempro.genes = [x.id for x in self._empty_reference_gempro.genes]
logging.disable(logging.NOTSET)
# Get a list of genes which do not have orthology in the strain
not_in_strain = self.df_orthology_matrix[pd.isnull(self.df_orthology_matrix[strain_gempro.id])][strain_gempro.id].index.tolist()
# Mark genes non-functional
self._pare_down_model(strain_gempro=strain_gempro, genes_to_remove=not_in_strain)
# Load sequences into the base and strain models
self._load_strain_sequences(strain_gempro=strain_gempro)
if save_models:
cobra.io.save_json_model(model=strain_gempro.model,
filename=op.join(self.model_dir, '{}.json'.format(strain_gempro.id)))
strain_gempro.save_pickle(op.join(self.model_dir, '{}_gp.pckl'.format(strain_gempro.id)))
log.info('Created {} new strain-specific models and loaded in sequences'.format(len(self.strains))) | [
"def",
"build_strain_specific_models",
"(",
"self",
",",
"save_models",
"=",
"False",
")",
":",
"if",
"len",
"(",
"self",
".",
"df_orthology_matrix",
")",
"==",
"0",
":",
"raise",
"RuntimeError",
"(",
"'Empty orthology matrix'",
")",
"# Create an emptied copy of the... | Using the orthologous genes matrix, create and modify the strain specific models based on if orthologous
genes exist.
Also store the sequences directly in the reference GEM-PRO protein sequence attribute for the strains. | [
"Using",
"the",
"orthologous",
"genes",
"matrix",
"create",
"and",
"modify",
"the",
"strain",
"specific",
"models",
"based",
"on",
"if",
"orthologous",
"genes",
"exist",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas.py#L493-L530 | train | 29,115 |
SBRG/ssbio | ssbio/pipeline/atlas.py | ATLAS.align_orthologous_genes_pairwise | def align_orthologous_genes_pairwise(self, gapopen=10, gapextend=0.5):
"""For each gene in the base strain, run a pairwise alignment for all orthologous gene sequences to it."""
for ref_gene in tqdm(self.reference_gempro.genes):
if len(ref_gene.protein.sequences) > 1:
alignment_dir = op.join(self.sequences_by_gene_dir, ref_gene.id)
if not op.exists(alignment_dir):
os.mkdir(alignment_dir)
ref_gene.protein.pairwise_align_sequences_to_representative(gapopen=gapopen, gapextend=gapextend,
outdir=alignment_dir, parse=True) | python | def align_orthologous_genes_pairwise(self, gapopen=10, gapextend=0.5):
"""For each gene in the base strain, run a pairwise alignment for all orthologous gene sequences to it."""
for ref_gene in tqdm(self.reference_gempro.genes):
if len(ref_gene.protein.sequences) > 1:
alignment_dir = op.join(self.sequences_by_gene_dir, ref_gene.id)
if not op.exists(alignment_dir):
os.mkdir(alignment_dir)
ref_gene.protein.pairwise_align_sequences_to_representative(gapopen=gapopen, gapextend=gapextend,
outdir=alignment_dir, parse=True) | [
"def",
"align_orthologous_genes_pairwise",
"(",
"self",
",",
"gapopen",
"=",
"10",
",",
"gapextend",
"=",
"0.5",
")",
":",
"for",
"ref_gene",
"in",
"tqdm",
"(",
"self",
".",
"reference_gempro",
".",
"genes",
")",
":",
"if",
"len",
"(",
"ref_gene",
".",
"... | For each gene in the base strain, run a pairwise alignment for all orthologous gene sequences to it. | [
"For",
"each",
"gene",
"in",
"the",
"base",
"strain",
"run",
"a",
"pairwise",
"alignment",
"for",
"all",
"orthologous",
"gene",
"sequences",
"to",
"it",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas.py#L532-L540 | train | 29,116 |
SBRG/ssbio | ssbio/pipeline/atlas.py | ATLAS.get_atlas_per_gene_mutation_df | def get_atlas_per_gene_mutation_df(self, gene_id):
"""Create a single data frame which summarizes a gene and its mutations.
Args:
gene_id (str): Gene ID in the base model
Returns:
DataFrame: Pandas DataFrame of the results
"""
# TODO: also count: number of unique mutations (have to consider position, amino acid change)
# TODO: keep track of strain with most mutations, least mutations
# TODO: keep track of strains that conserve the length of the protein, others that extend or truncate it
# need statistical test for that too (how long is "extended"/"truncated"?)
# TODO: number of strains with at least 1 mutations
# TODO: number of strains with <5% mutated, 5-10%, etc
g = self.reference_gempro.genes.get_by_id(gene_id)
single, fingerprint = g.protein.sequence_mutation_summary(alignment_type='seqalign')
structure_type_suffix = 'NA'
appender = []
for k, strains in single.items():
# Mutations in the strain
to_append = {}
orig_res = k[0]
resnum = int(k[1])
mutated_res = k[2]
num_strains_mutated = len(strains)
strain_ids = [str(x.split(g.id + '_')[1]) for x in strains]
to_append['ref_residue'] = orig_res
to_append['ref_resnum'] = resnum
to_append['strain_residue'] = mutated_res
to_append['num_strains_mutated'] = num_strains_mutated
to_append['strains_mutated'] = ';'.join(strain_ids)
to_append['at_disulfide_bridge'] = False
# Residue properties
origres_props = ssbio.protein.sequence.properties.residues.residue_biochemical_definition(orig_res)
mutres_props = ssbio.protein.sequence.properties.residues.residue_biochemical_definition(mutated_res)
to_append['ref_residue_prop'] = origres_props
to_append['strain_residue_prop'] = mutres_props
# Grantham score - score a mutation based on biochemical properties
grantham_s, grantham_txt = ssbio.protein.sequence.properties.residues.grantham_score(orig_res, mutated_res)
to_append['grantham_score'] = grantham_s
to_append['grantham_annotation'] = grantham_txt
# Get all per residue annotations - predicted from sequence and calculated from structure
to_append.update(g.protein.get_residue_annotations(seq_resnum=resnum, use_representatives=True))
# Check structure type
if g.protein.representative_structure:
if g.protein.representative_structure.is_experimental:
to_append['structure_type'] = 'EXP'
else:
to_append['structure_type'] = 'HOM'
# At disulfide bond?
repchain = g.protein.representative_chain
repchain_annotations = g.protein.representative_structure.chains.get_by_id(repchain).seq_record.annotations
if 'SSBOND-biopython' in repchain_annotations:
structure_resnum = g.protein.map_seqprop_resnums_to_structprop_resnums(resnums=resnum,
use_representatives=True)
if resnum in structure_resnum:
ssbonds = repchain_annotations['SSBOND-biopython']
ssbonds_res = []
for x in ssbonds:
ssbonds_res.append(x[0])
ssbonds_res.append(x[1])
if structure_resnum in ssbonds_res:
to_append['at_disulfide_bridge'] = True
appender.append(to_append)
if not appender:
return pd.DataFrame()
cols = ['ref_residue', 'ref_resnum', 'strain_residue', 'num_strains_mutated', 'strains_mutated',
'ref_residue_prop', 'strain_residue_prop', 'grantham_score', 'grantham_annotation',
'at_disulfide_bridge',
'seq_SS-sspro', 'seq_SS-sspro8', 'seq_RSA-accpro', 'seq_RSA-accpro20', 'seq_TM-tmhmm',
'struct_SS-dssp', 'struct_RSA-dssp', 'struct_ASA-dssp',
'struct_CA_DEPTH-msms', 'struct_RES_DEPTH-msms',
'struct_PHI-dssp', 'struct_PSI-dssp',
'struct_resnum', 'struct_residue'
'strains_mutated']
df_gene_summary = pd.DataFrame.from_records(appender, columns=cols)
# Drop columns that don't have anything in them
df_gene_summary.dropna(axis=1, how='all', inplace=True)
df_gene_summary.sort_values(by='ref_resnum', inplace=True)
df_gene_summary = df_gene_summary.set_index('ref_resnum')
return df_gene_summary | python | def get_atlas_per_gene_mutation_df(self, gene_id):
"""Create a single data frame which summarizes a gene and its mutations.
Args:
gene_id (str): Gene ID in the base model
Returns:
DataFrame: Pandas DataFrame of the results
"""
# TODO: also count: number of unique mutations (have to consider position, amino acid change)
# TODO: keep track of strain with most mutations, least mutations
# TODO: keep track of strains that conserve the length of the protein, others that extend or truncate it
# need statistical test for that too (how long is "extended"/"truncated"?)
# TODO: number of strains with at least 1 mutations
# TODO: number of strains with <5% mutated, 5-10%, etc
g = self.reference_gempro.genes.get_by_id(gene_id)
single, fingerprint = g.protein.sequence_mutation_summary(alignment_type='seqalign')
structure_type_suffix = 'NA'
appender = []
for k, strains in single.items():
# Mutations in the strain
to_append = {}
orig_res = k[0]
resnum = int(k[1])
mutated_res = k[2]
num_strains_mutated = len(strains)
strain_ids = [str(x.split(g.id + '_')[1]) for x in strains]
to_append['ref_residue'] = orig_res
to_append['ref_resnum'] = resnum
to_append['strain_residue'] = mutated_res
to_append['num_strains_mutated'] = num_strains_mutated
to_append['strains_mutated'] = ';'.join(strain_ids)
to_append['at_disulfide_bridge'] = False
# Residue properties
origres_props = ssbio.protein.sequence.properties.residues.residue_biochemical_definition(orig_res)
mutres_props = ssbio.protein.sequence.properties.residues.residue_biochemical_definition(mutated_res)
to_append['ref_residue_prop'] = origres_props
to_append['strain_residue_prop'] = mutres_props
# Grantham score - score a mutation based on biochemical properties
grantham_s, grantham_txt = ssbio.protein.sequence.properties.residues.grantham_score(orig_res, mutated_res)
to_append['grantham_score'] = grantham_s
to_append['grantham_annotation'] = grantham_txt
# Get all per residue annotations - predicted from sequence and calculated from structure
to_append.update(g.protein.get_residue_annotations(seq_resnum=resnum, use_representatives=True))
# Check structure type
if g.protein.representative_structure:
if g.protein.representative_structure.is_experimental:
to_append['structure_type'] = 'EXP'
else:
to_append['structure_type'] = 'HOM'
# At disulfide bond?
repchain = g.protein.representative_chain
repchain_annotations = g.protein.representative_structure.chains.get_by_id(repchain).seq_record.annotations
if 'SSBOND-biopython' in repchain_annotations:
structure_resnum = g.protein.map_seqprop_resnums_to_structprop_resnums(resnums=resnum,
use_representatives=True)
if resnum in structure_resnum:
ssbonds = repchain_annotations['SSBOND-biopython']
ssbonds_res = []
for x in ssbonds:
ssbonds_res.append(x[0])
ssbonds_res.append(x[1])
if structure_resnum in ssbonds_res:
to_append['at_disulfide_bridge'] = True
appender.append(to_append)
if not appender:
return pd.DataFrame()
cols = ['ref_residue', 'ref_resnum', 'strain_residue', 'num_strains_mutated', 'strains_mutated',
'ref_residue_prop', 'strain_residue_prop', 'grantham_score', 'grantham_annotation',
'at_disulfide_bridge',
'seq_SS-sspro', 'seq_SS-sspro8', 'seq_RSA-accpro', 'seq_RSA-accpro20', 'seq_TM-tmhmm',
'struct_SS-dssp', 'struct_RSA-dssp', 'struct_ASA-dssp',
'struct_CA_DEPTH-msms', 'struct_RES_DEPTH-msms',
'struct_PHI-dssp', 'struct_PSI-dssp',
'struct_resnum', 'struct_residue'
'strains_mutated']
df_gene_summary = pd.DataFrame.from_records(appender, columns=cols)
# Drop columns that don't have anything in them
df_gene_summary.dropna(axis=1, how='all', inplace=True)
df_gene_summary.sort_values(by='ref_resnum', inplace=True)
df_gene_summary = df_gene_summary.set_index('ref_resnum')
return df_gene_summary | [
"def",
"get_atlas_per_gene_mutation_df",
"(",
"self",
",",
"gene_id",
")",
":",
"# TODO: also count: number of unique mutations (have to consider position, amino acid change)",
"# TODO: keep track of strain with most mutations, least mutations",
"# TODO: keep track of strains that conserve the l... | Create a single data frame which summarizes a gene and its mutations.
Args:
gene_id (str): Gene ID in the base model
Returns:
DataFrame: Pandas DataFrame of the results | [
"Create",
"a",
"single",
"data",
"frame",
"which",
"summarizes",
"a",
"gene",
"and",
"its",
"mutations",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas.py#L701-L799 | train | 29,117 |
SBRG/ssbio | ssbio/viz/nglview.py | add_residues_highlight_to_nglview | def add_residues_highlight_to_nglview(view, structure_resnums, chain, res_color='red'):
"""Add a residue number or numbers to an NGLWidget view object.
Args:
view (NGLWidget): NGLWidget view object
structure_resnums (int, list): Residue number(s) to highlight, structure numbering
chain (str, list): Chain ID or IDs of which residues are a part of. If not provided, all chains in the
mapped_chains attribute will be used. If that is also empty, and exception is raised.
res_color (str): Color to highlight residues with
"""
chain = ssbio.utils.force_list(chain)
if isinstance(structure_resnums, list):
structure_resnums = list(set(structure_resnums))
elif isinstance(structure_resnums, int):
structure_resnums = ssbio.utils.force_list(structure_resnums)
else:
raise ValueError('Input must either be a residue number of a list of residue numbers')
to_show_chains = '( '
for c in chain:
to_show_chains += ':{} or'.format(c)
to_show_chains = to_show_chains.strip(' or ')
to_show_chains += ' )'
to_show_res = '( '
for m in structure_resnums:
to_show_res += '{} or '.format(m)
to_show_res = to_show_res.strip(' or ')
to_show_res += ' )'
log.info('Selection: {} and not hydrogen and {}'.format(to_show_chains, to_show_res))
view.add_ball_and_stick(selection='{} and not hydrogen and {}'.format(to_show_chains, to_show_res), color=res_color) | python | def add_residues_highlight_to_nglview(view, structure_resnums, chain, res_color='red'):
"""Add a residue number or numbers to an NGLWidget view object.
Args:
view (NGLWidget): NGLWidget view object
structure_resnums (int, list): Residue number(s) to highlight, structure numbering
chain (str, list): Chain ID or IDs of which residues are a part of. If not provided, all chains in the
mapped_chains attribute will be used. If that is also empty, and exception is raised.
res_color (str): Color to highlight residues with
"""
chain = ssbio.utils.force_list(chain)
if isinstance(structure_resnums, list):
structure_resnums = list(set(structure_resnums))
elif isinstance(structure_resnums, int):
structure_resnums = ssbio.utils.force_list(structure_resnums)
else:
raise ValueError('Input must either be a residue number of a list of residue numbers')
to_show_chains = '( '
for c in chain:
to_show_chains += ':{} or'.format(c)
to_show_chains = to_show_chains.strip(' or ')
to_show_chains += ' )'
to_show_res = '( '
for m in structure_resnums:
to_show_res += '{} or '.format(m)
to_show_res = to_show_res.strip(' or ')
to_show_res += ' )'
log.info('Selection: {} and not hydrogen and {}'.format(to_show_chains, to_show_res))
view.add_ball_and_stick(selection='{} and not hydrogen and {}'.format(to_show_chains, to_show_res), color=res_color) | [
"def",
"add_residues_highlight_to_nglview",
"(",
"view",
",",
"structure_resnums",
",",
"chain",
",",
"res_color",
"=",
"'red'",
")",
":",
"chain",
"=",
"ssbio",
".",
"utils",
".",
"force_list",
"(",
"chain",
")",
"if",
"isinstance",
"(",
"structure_resnums",
... | Add a residue number or numbers to an NGLWidget view object.
Args:
view (NGLWidget): NGLWidget view object
structure_resnums (int, list): Residue number(s) to highlight, structure numbering
chain (str, list): Chain ID or IDs of which residues are a part of. If not provided, all chains in the
mapped_chains attribute will be used. If that is also empty, and exception is raised.
res_color (str): Color to highlight residues with | [
"Add",
"a",
"residue",
"number",
"or",
"numbers",
"to",
"an",
"NGLWidget",
"view",
"object",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/viz/nglview.py#L7-L41 | train | 29,118 |
SBRG/ssbio | ssbio/databases/kegg.py | download_kegg_gene_metadata | def download_kegg_gene_metadata(gene_id, outdir=None, force_rerun=False):
"""Download the KEGG flatfile for a KEGG ID and return the path.
Args:
gene_id: KEGG gene ID (with organism code), i.e. "eco:1244"
outdir: optional output directory of metadata
Returns:
Path to metadata file
"""
if not outdir:
outdir = ''
# Replace colon with dash in the KEGG gene ID
outfile = op.join(outdir, '{}.kegg'.format(custom_slugify(gene_id)))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
raw_text = bs_kegg.get("{}".format(gene_id))
if raw_text == 404:
return
with io.open(outfile, mode='wt', encoding='utf-8') as f:
f.write(raw_text)
log.debug('{}: downloaded KEGG metadata file'.format(outfile))
else:
log.debug('{}: KEGG metadata file already exists'.format(outfile))
return outfile | python | def download_kegg_gene_metadata(gene_id, outdir=None, force_rerun=False):
"""Download the KEGG flatfile for a KEGG ID and return the path.
Args:
gene_id: KEGG gene ID (with organism code), i.e. "eco:1244"
outdir: optional output directory of metadata
Returns:
Path to metadata file
"""
if not outdir:
outdir = ''
# Replace colon with dash in the KEGG gene ID
outfile = op.join(outdir, '{}.kegg'.format(custom_slugify(gene_id)))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
raw_text = bs_kegg.get("{}".format(gene_id))
if raw_text == 404:
return
with io.open(outfile, mode='wt', encoding='utf-8') as f:
f.write(raw_text)
log.debug('{}: downloaded KEGG metadata file'.format(outfile))
else:
log.debug('{}: KEGG metadata file already exists'.format(outfile))
return outfile | [
"def",
"download_kegg_gene_metadata",
"(",
"gene_id",
",",
"outdir",
"=",
"None",
",",
"force_rerun",
"=",
"False",
")",
":",
"if",
"not",
"outdir",
":",
"outdir",
"=",
"''",
"# Replace colon with dash in the KEGG gene ID",
"outfile",
"=",
"op",
".",
"join",
"("... | Download the KEGG flatfile for a KEGG ID and return the path.
Args:
gene_id: KEGG gene ID (with organism code), i.e. "eco:1244"
outdir: optional output directory of metadata
Returns:
Path to metadata file | [
"Download",
"the",
"KEGG",
"flatfile",
"for",
"a",
"KEGG",
"ID",
"and",
"return",
"the",
"path",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/databases/kegg.py#L74-L103 | train | 29,119 |
SBRG/ssbio | ssbio/databases/kegg.py | parse_kegg_gene_metadata | def parse_kegg_gene_metadata(infile):
"""Parse the KEGG flatfile and return a dictionary of metadata.
Dictionary keys are:
refseq
uniprot
pdbs
taxonomy
Args:
infile: Path to KEGG flatfile
Returns:
dict: Dictionary of metadata
"""
metadata = defaultdict(str)
with open(infile) as mf:
kegg_parsed = bs_kegg.parse(mf.read())
# TODO: additional fields can be parsed
if 'DBLINKS' in kegg_parsed.keys():
if 'UniProt' in kegg_parsed['DBLINKS']:
unis = str(kegg_parsed['DBLINKS']['UniProt']).split(' ')
# TODO: losing other uniprot ids by doing this
if isinstance(unis, list):
metadata['uniprot'] = unis[0]
else:
metadata['uniprot'] = unis
if 'NCBI-ProteinID' in kegg_parsed['DBLINKS']:
metadata['refseq'] = str(kegg_parsed['DBLINKS']['NCBI-ProteinID'])
if 'STRUCTURE' in kegg_parsed.keys():
metadata['pdbs'] = str(kegg_parsed['STRUCTURE']['PDB']).split(' ')
else:
metadata['pdbs'] = None
if 'ORGANISM' in kegg_parsed.keys():
metadata['taxonomy'] = str(kegg_parsed['ORGANISM'])
return metadata | python | def parse_kegg_gene_metadata(infile):
"""Parse the KEGG flatfile and return a dictionary of metadata.
Dictionary keys are:
refseq
uniprot
pdbs
taxonomy
Args:
infile: Path to KEGG flatfile
Returns:
dict: Dictionary of metadata
"""
metadata = defaultdict(str)
with open(infile) as mf:
kegg_parsed = bs_kegg.parse(mf.read())
# TODO: additional fields can be parsed
if 'DBLINKS' in kegg_parsed.keys():
if 'UniProt' in kegg_parsed['DBLINKS']:
unis = str(kegg_parsed['DBLINKS']['UniProt']).split(' ')
# TODO: losing other uniprot ids by doing this
if isinstance(unis, list):
metadata['uniprot'] = unis[0]
else:
metadata['uniprot'] = unis
if 'NCBI-ProteinID' in kegg_parsed['DBLINKS']:
metadata['refseq'] = str(kegg_parsed['DBLINKS']['NCBI-ProteinID'])
if 'STRUCTURE' in kegg_parsed.keys():
metadata['pdbs'] = str(kegg_parsed['STRUCTURE']['PDB']).split(' ')
else:
metadata['pdbs'] = None
if 'ORGANISM' in kegg_parsed.keys():
metadata['taxonomy'] = str(kegg_parsed['ORGANISM'])
return metadata | [
"def",
"parse_kegg_gene_metadata",
"(",
"infile",
")",
":",
"metadata",
"=",
"defaultdict",
"(",
"str",
")",
"with",
"open",
"(",
"infile",
")",
"as",
"mf",
":",
"kegg_parsed",
"=",
"bs_kegg",
".",
"parse",
"(",
"mf",
".",
"read",
"(",
")",
")",
"# TOD... | Parse the KEGG flatfile and return a dictionary of metadata.
Dictionary keys are:
refseq
uniprot
pdbs
taxonomy
Args:
infile: Path to KEGG flatfile
Returns:
dict: Dictionary of metadata | [
"Parse",
"the",
"KEGG",
"flatfile",
"and",
"return",
"a",
"dictionary",
"of",
"metadata",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/databases/kegg.py#L106-L146 | train | 29,120 |
SBRG/ssbio | ssbio/databases/kegg.py | map_kegg_all_genes | def map_kegg_all_genes(organism_code, target_db):
"""Map all of an organism's gene IDs to the target database.
This is faster than supplying a specific list of genes to map,
plus there seems to be a limit on the number you can map with a manual REST query anyway.
Args:
organism_code: the three letter KEGG code of your organism
target_db: ncbi-proteinid | ncbi-geneid | uniprot
Returns:
Dictionary of ID mapping
"""
mapping = bs_kegg.conv(target_db, organism_code)
# strip the organism code from the keys and the identifier in the values
new_mapping = {}
for k,v in mapping.items():
new_mapping[k.replace(organism_code + ':', '')] = str(v.split(':')[1])
return new_mapping | python | def map_kegg_all_genes(organism_code, target_db):
"""Map all of an organism's gene IDs to the target database.
This is faster than supplying a specific list of genes to map,
plus there seems to be a limit on the number you can map with a manual REST query anyway.
Args:
organism_code: the three letter KEGG code of your organism
target_db: ncbi-proteinid | ncbi-geneid | uniprot
Returns:
Dictionary of ID mapping
"""
mapping = bs_kegg.conv(target_db, organism_code)
# strip the organism code from the keys and the identifier in the values
new_mapping = {}
for k,v in mapping.items():
new_mapping[k.replace(organism_code + ':', '')] = str(v.split(':')[1])
return new_mapping | [
"def",
"map_kegg_all_genes",
"(",
"organism_code",
",",
"target_db",
")",
":",
"mapping",
"=",
"bs_kegg",
".",
"conv",
"(",
"target_db",
",",
"organism_code",
")",
"# strip the organism code from the keys and the identifier in the values",
"new_mapping",
"=",
"{",
"}",
... | Map all of an organism's gene IDs to the target database.
This is faster than supplying a specific list of genes to map,
plus there seems to be a limit on the number you can map with a manual REST query anyway.
Args:
organism_code: the three letter KEGG code of your organism
target_db: ncbi-proteinid | ncbi-geneid | uniprot
Returns:
Dictionary of ID mapping | [
"Map",
"all",
"of",
"an",
"organism",
"s",
"gene",
"IDs",
"to",
"the",
"target",
"database",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/databases/kegg.py#L180-L201 | train | 29,121 |
SBRG/ssbio | ssbio/protein/structure/homology/itasser/itasserprep.py | ITASSERPrep.prep_folder | def prep_folder(self, seq):
"""Take in a sequence string and prepares the folder for the I-TASSER run."""
itasser_dir = op.join(self.root_dir, self.id)
if not op.exists(itasser_dir):
os.makedirs(itasser_dir)
tmp = {self.id: seq}
fasta.write_fasta_file_from_dict(indict=tmp,
outname='seq',
outext='.fasta',
outdir=itasser_dir)
return itasser_dir | python | def prep_folder(self, seq):
"""Take in a sequence string and prepares the folder for the I-TASSER run."""
itasser_dir = op.join(self.root_dir, self.id)
if not op.exists(itasser_dir):
os.makedirs(itasser_dir)
tmp = {self.id: seq}
fasta.write_fasta_file_from_dict(indict=tmp,
outname='seq',
outext='.fasta',
outdir=itasser_dir)
return itasser_dir | [
"def",
"prep_folder",
"(",
"self",
",",
"seq",
")",
":",
"itasser_dir",
"=",
"op",
".",
"join",
"(",
"self",
".",
"root_dir",
",",
"self",
".",
"id",
")",
"if",
"not",
"op",
".",
"exists",
"(",
"itasser_dir",
")",
":",
"os",
".",
"makedirs",
"(",
... | Take in a sequence string and prepares the folder for the I-TASSER run. | [
"Take",
"in",
"a",
"sequence",
"string",
"and",
"prepares",
"the",
"folder",
"for",
"the",
"I",
"-",
"TASSER",
"run",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/homology/itasser/itasserprep.py#L107-L120 | train | 29,122 |
SBRG/ssbio | ssbio/protein/sequence/utils/blast.py | run_makeblastdb | def run_makeblastdb(infile, dbtype, outdir=''):
"""Make the BLAST database for a genome file.
Args:
infile (str): path to genome FASTA file
dbtype (str): "nucl" or "prot" - what format your genome files are in
outdir (str): path to directory to output database files (default is original folder)
Returns:
Paths to BLAST databases.
"""
# TODO: add force_rerun option
# TODO: rewrite using utils function command
# Output location
og_dir, name, ext = utils.split_folder_and_path(infile)
if not outdir:
outdir = og_dir
outfile_basename = op.join(outdir, name)
# Check if BLAST DB was already made
if dbtype == 'nucl':
outext = ['.nhr', '.nin', '.nsq']
elif dbtype == 'prot':
outext = ['.phr', '.pin', '.psq']
else:
raise ValueError('dbtype must be "nucl" or "prot"')
outfile_all = [outfile_basename + x for x in outext]
db_made = True
for f in outfile_all:
if not op.exists(f):
db_made = False
# Run makeblastdb if DB does not exist
if db_made:
log.debug('BLAST database already exists at {}'.format(outfile_basename))
return outfile_all
else:
retval = subprocess.call('makeblastdb -in {} -dbtype {} -out {}'.format(infile, dbtype, outfile_basename), shell=True)
if retval == 0:
log.debug('Made BLAST database at {}'.format(outfile_basename))
return outfile_all
else:
log.error('Error running makeblastdb, exit code {}'.format(retval)) | python | def run_makeblastdb(infile, dbtype, outdir=''):
"""Make the BLAST database for a genome file.
Args:
infile (str): path to genome FASTA file
dbtype (str): "nucl" or "prot" - what format your genome files are in
outdir (str): path to directory to output database files (default is original folder)
Returns:
Paths to BLAST databases.
"""
# TODO: add force_rerun option
# TODO: rewrite using utils function command
# Output location
og_dir, name, ext = utils.split_folder_and_path(infile)
if not outdir:
outdir = og_dir
outfile_basename = op.join(outdir, name)
# Check if BLAST DB was already made
if dbtype == 'nucl':
outext = ['.nhr', '.nin', '.nsq']
elif dbtype == 'prot':
outext = ['.phr', '.pin', '.psq']
else:
raise ValueError('dbtype must be "nucl" or "prot"')
outfile_all = [outfile_basename + x for x in outext]
db_made = True
for f in outfile_all:
if not op.exists(f):
db_made = False
# Run makeblastdb if DB does not exist
if db_made:
log.debug('BLAST database already exists at {}'.format(outfile_basename))
return outfile_all
else:
retval = subprocess.call('makeblastdb -in {} -dbtype {} -out {}'.format(infile, dbtype, outfile_basename), shell=True)
if retval == 0:
log.debug('Made BLAST database at {}'.format(outfile_basename))
return outfile_all
else:
log.error('Error running makeblastdb, exit code {}'.format(retval)) | [
"def",
"run_makeblastdb",
"(",
"infile",
",",
"dbtype",
",",
"outdir",
"=",
"''",
")",
":",
"# TODO: add force_rerun option",
"# TODO: rewrite using utils function command",
"# Output location",
"og_dir",
",",
"name",
",",
"ext",
"=",
"utils",
".",
"split_folder_and_pat... | Make the BLAST database for a genome file.
Args:
infile (str): path to genome FASTA file
dbtype (str): "nucl" or "prot" - what format your genome files are in
outdir (str): path to directory to output database files (default is original folder)
Returns:
Paths to BLAST databases. | [
"Make",
"the",
"BLAST",
"database",
"for",
"a",
"genome",
"file",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/utils/blast.py#L24-L68 | train | 29,123 |
SBRG/ssbio | ssbio/protein/sequence/utils/blast.py | run_bidirectional_blast | def run_bidirectional_blast(reference, other_genome, dbtype, outdir=''):
"""BLAST a genome against another, and vice versa.
This function requires BLAST to be installed, do so by running:
sudo apt install ncbi-blast+
Args:
reference (str): path to "reference" genome, aka your "base strain"
other_genome (str): path to other genome which will be BLASTed to the reference
dbtype (str): "nucl" or "prot" - what format your genome files are in
outdir (str): path to folder where BLAST outputs should be placed
Returns:
Paths to BLAST output files.
(reference_vs_othergenome.out, othergenome_vs_reference.out)
"""
# TODO: add force_rerun option
if dbtype == 'nucl':
command = 'blastn'
elif dbtype == 'prot':
command = 'blastp'
else:
raise ValueError('dbtype must be "nucl" or "prot"')
r_folder, r_name, r_ext = utils.split_folder_and_path(reference)
g_folder, g_name, g_ext = utils.split_folder_and_path(other_genome)
# make sure BLAST DBs have been made
run_makeblastdb(infile=reference, dbtype=dbtype, outdir=r_folder)
run_makeblastdb(infile=other_genome, dbtype=dbtype, outdir=g_folder)
# Reference vs genome
r_vs_g = r_name + '_vs_' + g_name + '_blast.out'
r_vs_g = op.join(outdir, r_vs_g)
if op.exists(r_vs_g) and os.stat(r_vs_g).st_size != 0:
log.debug('{} vs {} BLAST already run'.format(r_name, g_name))
else:
cmd = '{} -query {} -db {} -outfmt 6 -out {}'.format(command, reference, op.join(g_folder, g_name), r_vs_g)
log.debug('Running: {}'.format(cmd))
retval = subprocess.call(cmd, shell=True)
if retval == 0:
log.debug('BLASTed {} vs {}'.format(g_name, r_name))
else:
log.error('Error running {}, exit code {}'.format(command, retval))
# Genome vs reference
g_vs_r = g_name + '_vs_' + r_name + '_blast.out'
g_vs_r = op.join(outdir, g_vs_r)
if op.exists(g_vs_r) and os.stat(g_vs_r).st_size != 0:
log.debug('{} vs {} BLAST already run'.format(g_name, r_name))
else:
cmd = '{} -query {} -db {} -outfmt 6 -out {}'.format(command, other_genome, op.join(r_folder, r_name), g_vs_r)
log.debug('Running: {}'.format(cmd))
retval = subprocess.call(cmd, shell=True)
if retval == 0:
log.debug('BLASTed {} vs {}'.format(g_name, r_name))
else:
log.error('Error running {}, exit code {}'.format(command, retval))
return r_vs_g, g_vs_r | python | def run_bidirectional_blast(reference, other_genome, dbtype, outdir=''):
"""BLAST a genome against another, and vice versa.
This function requires BLAST to be installed, do so by running:
sudo apt install ncbi-blast+
Args:
reference (str): path to "reference" genome, aka your "base strain"
other_genome (str): path to other genome which will be BLASTed to the reference
dbtype (str): "nucl" or "prot" - what format your genome files are in
outdir (str): path to folder where BLAST outputs should be placed
Returns:
Paths to BLAST output files.
(reference_vs_othergenome.out, othergenome_vs_reference.out)
"""
# TODO: add force_rerun option
if dbtype == 'nucl':
command = 'blastn'
elif dbtype == 'prot':
command = 'blastp'
else:
raise ValueError('dbtype must be "nucl" or "prot"')
r_folder, r_name, r_ext = utils.split_folder_and_path(reference)
g_folder, g_name, g_ext = utils.split_folder_and_path(other_genome)
# make sure BLAST DBs have been made
run_makeblastdb(infile=reference, dbtype=dbtype, outdir=r_folder)
run_makeblastdb(infile=other_genome, dbtype=dbtype, outdir=g_folder)
# Reference vs genome
r_vs_g = r_name + '_vs_' + g_name + '_blast.out'
r_vs_g = op.join(outdir, r_vs_g)
if op.exists(r_vs_g) and os.stat(r_vs_g).st_size != 0:
log.debug('{} vs {} BLAST already run'.format(r_name, g_name))
else:
cmd = '{} -query {} -db {} -outfmt 6 -out {}'.format(command, reference, op.join(g_folder, g_name), r_vs_g)
log.debug('Running: {}'.format(cmd))
retval = subprocess.call(cmd, shell=True)
if retval == 0:
log.debug('BLASTed {} vs {}'.format(g_name, r_name))
else:
log.error('Error running {}, exit code {}'.format(command, retval))
# Genome vs reference
g_vs_r = g_name + '_vs_' + r_name + '_blast.out'
g_vs_r = op.join(outdir, g_vs_r)
if op.exists(g_vs_r) and os.stat(g_vs_r).st_size != 0:
log.debug('{} vs {} BLAST already run'.format(g_name, r_name))
else:
cmd = '{} -query {} -db {} -outfmt 6 -out {}'.format(command, other_genome, op.join(r_folder, r_name), g_vs_r)
log.debug('Running: {}'.format(cmd))
retval = subprocess.call(cmd, shell=True)
if retval == 0:
log.debug('BLASTed {} vs {}'.format(g_name, r_name))
else:
log.error('Error running {}, exit code {}'.format(command, retval))
return r_vs_g, g_vs_r | [
"def",
"run_bidirectional_blast",
"(",
"reference",
",",
"other_genome",
",",
"dbtype",
",",
"outdir",
"=",
"''",
")",
":",
"# TODO: add force_rerun option",
"if",
"dbtype",
"==",
"'nucl'",
":",
"command",
"=",
"'blastn'",
"elif",
"dbtype",
"==",
"'prot'",
":",
... | BLAST a genome against another, and vice versa.
This function requires BLAST to be installed, do so by running:
sudo apt install ncbi-blast+
Args:
reference (str): path to "reference" genome, aka your "base strain"
other_genome (str): path to other genome which will be BLASTed to the reference
dbtype (str): "nucl" or "prot" - what format your genome files are in
outdir (str): path to folder where BLAST outputs should be placed
Returns:
Paths to BLAST output files.
(reference_vs_othergenome.out, othergenome_vs_reference.out) | [
"BLAST",
"a",
"genome",
"against",
"another",
"and",
"vice",
"versa",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/utils/blast.py#L71-L132 | train | 29,124 |
SBRG/ssbio | ssbio/protein/sequence/utils/blast.py | print_run_bidirectional_blast | def print_run_bidirectional_blast(reference, other_genome, dbtype, outdir):
"""Write torque submission files for running bidirectional blast on a server and print execution command.
Args:
reference (str): Path to "reference" genome, aka your "base strain"
other_genome (str): Path to other genome which will be BLASTed to the reference
dbtype (str): "nucl" or "prot" - what format your genome files are in
outdir (str): Path to folder where Torque scripts should be placed
"""
# TODO: add force_rerun option
if dbtype == 'nucl':
command = 'blastn'
elif dbtype == 'prot':
command = 'blastp'
else:
raise ValueError('dbtype must be "nucl" or "prot"')
r_folder, r_name, r_ext = utils.split_folder_and_path(reference)
g_folder, g_name, g_ext = utils.split_folder_and_path(other_genome)
# Reference vs genome
r_vs_g_name = r_name + '_vs_' + g_name
r_vs_g = r_vs_g_name + '_blast.out'
if op.exists(op.join(outdir, r_vs_g)) and os.stat(op.join(outdir, r_vs_g)).st_size != 0:
log.debug('{} vs {} BLAST already run'.format(r_name, g_name))
else:
cmd = '{} -query {} -db {} -outfmt 6 -out {}'.format(command, reference, g_name, r_vs_g)
utils.write_torque_script(command=cmd, err=r_vs_g_name, out=r_vs_g_name, name=r_vs_g_name,
outfile=op.join(outdir, r_vs_g_name) + '.sh',
walltime='00:15:00', queue='regular')
# Genome vs reference
g_vs_r_name = g_name + '_vs_' + r_name
g_vs_r = g_vs_r_name + '_blast.out'
if op.exists(op.join(outdir, g_vs_r)) and os.stat(op.join(outdir, g_vs_r)).st_size != 0:
log.debug('{} vs {} BLAST already run'.format(g_name, r_name))
else:
cmd = '{} -query {} -db {} -outfmt 6 -out {}'.format(command, other_genome, r_name, g_vs_r)
utils.write_torque_script(command=cmd, err=g_vs_r_name, out=g_vs_r_name, name=g_vs_r_name,
outfile=op.join(outdir, g_vs_r_name) + '.sh',
walltime='00:15:00', queue='regular') | python | def print_run_bidirectional_blast(reference, other_genome, dbtype, outdir):
"""Write torque submission files for running bidirectional blast on a server and print execution command.
Args:
reference (str): Path to "reference" genome, aka your "base strain"
other_genome (str): Path to other genome which will be BLASTed to the reference
dbtype (str): "nucl" or "prot" - what format your genome files are in
outdir (str): Path to folder where Torque scripts should be placed
"""
# TODO: add force_rerun option
if dbtype == 'nucl':
command = 'blastn'
elif dbtype == 'prot':
command = 'blastp'
else:
raise ValueError('dbtype must be "nucl" or "prot"')
r_folder, r_name, r_ext = utils.split_folder_and_path(reference)
g_folder, g_name, g_ext = utils.split_folder_and_path(other_genome)
# Reference vs genome
r_vs_g_name = r_name + '_vs_' + g_name
r_vs_g = r_vs_g_name + '_blast.out'
if op.exists(op.join(outdir, r_vs_g)) and os.stat(op.join(outdir, r_vs_g)).st_size != 0:
log.debug('{} vs {} BLAST already run'.format(r_name, g_name))
else:
cmd = '{} -query {} -db {} -outfmt 6 -out {}'.format(command, reference, g_name, r_vs_g)
utils.write_torque_script(command=cmd, err=r_vs_g_name, out=r_vs_g_name, name=r_vs_g_name,
outfile=op.join(outdir, r_vs_g_name) + '.sh',
walltime='00:15:00', queue='regular')
# Genome vs reference
g_vs_r_name = g_name + '_vs_' + r_name
g_vs_r = g_vs_r_name + '_blast.out'
if op.exists(op.join(outdir, g_vs_r)) and os.stat(op.join(outdir, g_vs_r)).st_size != 0:
log.debug('{} vs {} BLAST already run'.format(g_name, r_name))
else:
cmd = '{} -query {} -db {} -outfmt 6 -out {}'.format(command, other_genome, r_name, g_vs_r)
utils.write_torque_script(command=cmd, err=g_vs_r_name, out=g_vs_r_name, name=g_vs_r_name,
outfile=op.join(outdir, g_vs_r_name) + '.sh',
walltime='00:15:00', queue='regular') | [
"def",
"print_run_bidirectional_blast",
"(",
"reference",
",",
"other_genome",
",",
"dbtype",
",",
"outdir",
")",
":",
"# TODO: add force_rerun option",
"if",
"dbtype",
"==",
"'nucl'",
":",
"command",
"=",
"'blastn'",
"elif",
"dbtype",
"==",
"'prot'",
":",
"comman... | Write torque submission files for running bidirectional blast on a server and print execution command.
Args:
reference (str): Path to "reference" genome, aka your "base strain"
other_genome (str): Path to other genome which will be BLASTed to the reference
dbtype (str): "nucl" or "prot" - what format your genome files are in
outdir (str): Path to folder where Torque scripts should be placed | [
"Write",
"torque",
"submission",
"files",
"for",
"running",
"bidirectional",
"blast",
"on",
"a",
"server",
"and",
"print",
"execution",
"command",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/utils/blast.py#L135-L177 | train | 29,125 |
SBRG/ssbio | ssbio/protein/structure/utils/structureio.py | StructureIO.write_pdb | def write_pdb(self, custom_name='', out_suffix='', out_dir=None, custom_selection=None, force_rerun=False):
"""Write a new PDB file for the Structure's FIRST MODEL.
Set custom_selection to a PDB.Select class for custom SMCRA selections.
Args:
custom_name: Filename of the new file (without extension)
out_suffix: Optional string to append to new PDB file
out_dir: Optional directory to output the file
custom_selection: Optional custom selection class
force_rerun: If existing file should be overwritten
Returns:
out_file: filepath of new PDB file
"""
if not custom_selection:
custom_selection = ModelSelection([0])
# If no output directory, custom name, or suffix is specified, add a suffix "_new"
if not out_dir or not custom_name:
if not out_suffix:
out_suffix = '_new'
# Prepare the output file path
outfile = ssbio.utils.outfile_maker(inname=self.structure_file,
outname=custom_name,
append_to_name=out_suffix,
outdir=out_dir,
outext='.pdb')
try:
if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
self.save(outfile, custom_selection)
except TypeError as e:
# If trying to save something that can't be saved as a PDB (example: 5iqr.cif), log an error and return None
# The error thrown by PDBIO.py is "TypeError: %c requires int or char"
log.error('{}: unable to save structure in PDB file format'.format(self.structure_file))
raise TypeError(e)
return outfile | python | def write_pdb(self, custom_name='', out_suffix='', out_dir=None, custom_selection=None, force_rerun=False):
"""Write a new PDB file for the Structure's FIRST MODEL.
Set custom_selection to a PDB.Select class for custom SMCRA selections.
Args:
custom_name: Filename of the new file (without extension)
out_suffix: Optional string to append to new PDB file
out_dir: Optional directory to output the file
custom_selection: Optional custom selection class
force_rerun: If existing file should be overwritten
Returns:
out_file: filepath of new PDB file
"""
if not custom_selection:
custom_selection = ModelSelection([0])
# If no output directory, custom name, or suffix is specified, add a suffix "_new"
if not out_dir or not custom_name:
if not out_suffix:
out_suffix = '_new'
# Prepare the output file path
outfile = ssbio.utils.outfile_maker(inname=self.structure_file,
outname=custom_name,
append_to_name=out_suffix,
outdir=out_dir,
outext='.pdb')
try:
if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
self.save(outfile, custom_selection)
except TypeError as e:
# If trying to save something that can't be saved as a PDB (example: 5iqr.cif), log an error and return None
# The error thrown by PDBIO.py is "TypeError: %c requires int or char"
log.error('{}: unable to save structure in PDB file format'.format(self.structure_file))
raise TypeError(e)
return outfile | [
"def",
"write_pdb",
"(",
"self",
",",
"custom_name",
"=",
"''",
",",
"out_suffix",
"=",
"''",
",",
"out_dir",
"=",
"None",
",",
"custom_selection",
"=",
"None",
",",
"force_rerun",
"=",
"False",
")",
":",
"if",
"not",
"custom_selection",
":",
"custom_selec... | Write a new PDB file for the Structure's FIRST MODEL.
Set custom_selection to a PDB.Select class for custom SMCRA selections.
Args:
custom_name: Filename of the new file (without extension)
out_suffix: Optional string to append to new PDB file
out_dir: Optional directory to output the file
custom_selection: Optional custom selection class
force_rerun: If existing file should be overwritten
Returns:
out_file: filepath of new PDB file | [
"Write",
"a",
"new",
"PDB",
"file",
"for",
"the",
"Structure",
"s",
"FIRST",
"MODEL",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/utils/structureio.py#L80-L119 | train | 29,126 |
SBRG/ssbio | ssbio/biopython/Bio/Struct/WWW/WHATIFXML.py | XMLParser._handle_builder_exception | def _handle_builder_exception(self, message, residue):
"""
Makes a PDB Construction Error a bit more verbose and informative
"""
message = "%s. Error when parsing residue %s:%s" %(message, residue['number'], residue['name'])
raise PDBConstructionException(message) | python | def _handle_builder_exception(self, message, residue):
"""
Makes a PDB Construction Error a bit more verbose and informative
"""
message = "%s. Error when parsing residue %s:%s" %(message, residue['number'], residue['name'])
raise PDBConstructionException(message) | [
"def",
"_handle_builder_exception",
"(",
"self",
",",
"message",
",",
"residue",
")",
":",
"message",
"=",
"\"%s. Error when parsing residue %s:%s\"",
"%",
"(",
"message",
",",
"residue",
"[",
"'number'",
"]",
",",
"residue",
"[",
"'name'",
"]",
")",
"raise",
... | Makes a PDB Construction Error a bit more verbose and informative | [
"Makes",
"a",
"PDB",
"Construction",
"Error",
"a",
"bit",
"more",
"verbose",
"and",
"informative"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/biopython/Bio/Struct/WWW/WHATIFXML.py#L72-L79 | train | 29,127 |
SBRG/ssbio | ssbio/biopython/Bio/Struct/WWW/WHATIFXML.py | XMLParser._parse | def _parse(self):
"""
Parse atomic data of the XML file.
"""
atom_counter = 0
structure_build = self.structure_builder
residues = self._extract_residues()
cur_model = None
cur_chain = None
structure_build.init_seg(' ') # There is never a SEGID present
for r in residues:
# New model?
if cur_model != r['model']:
cur_model = r['model']
try:
structure_build.init_model(cur_model)
except PDBConstructionException, message:
self._handle_builder_exception(message, r)
# New chain?
if cur_chain != r['chain']:
cur_chain = r['chain']
try:
structure_build.init_chain(cur_chain)
except PDBConstructionException, message:
self._handle_builder_exception(message, r)
# Create residue
if r['name'] in AA_LIST: # Get residue type crudely since there is no HETATM / ATOM
hetero_flag = ' '
elif r['name'] == 'WAT' or r['name'] == 'HOH':
hetero_flag = 'W'
else:
hetero_flag = 'H'
# Some terminal atoms are added at residue 0. This residue has a small number of atoms.
# Protonated non-terminal glycine has 7 atoms. Any of these residues is smaller.
# HETATMs have only a couple of atoms (3 for water for example) and they are ok.
if (len(r['atoms']) >= 7) or (hetero_flag != " "):
try:
structure_build.init_residue(r['name'], hetero_flag, r['number'], r['icode'])
except PDBConstructionException, message:
self._handle_builder_exception(message, r)
# Create Atoms
for atom in r['atoms']:
a = self._parse_atom(atom)
if not sum(a['coord']): # e.g. HG of metal bound CYS coords are 0,0,0.
continue
try:
atom_counter += 1
# fullname = name; altloc is empty;
structure_build.init_atom(a['name'], a['coord'], a['bfactor'], a['occupancy'], ' ',
a['name'], atom_counter, a['element'], hetero_flag)
except PDBConstructionException, message:
self._handle_builder_exception(message, r)
elif len(r['atoms']) < 7: # Terminal Residues
for atom in r['atoms']:
a = self._parse_atom(atom)
if not sum(a['coord']): # e.g. HG of metal bound CYS coords are 0,0,0.
continue
atom_counter += 1
ter_atom = Atom(a['name'], a['coord'], a['bfactor'], a['occupancy'], ' ',
a['name'], atom_counter, a['element'], hetero_flag)
if a['name'] in N_TERMINAL_ATOMS:
inc_struct = self.structure_builder.get_structure()
for model in inc_struct:
for chain in model:
if chain.id == r['chain']:
for residue in chain: # Find First residue matching name
if residue.resname == r['name']:
residue.add(ter_atom)
break
elif a['name'] in C_TERMINAL_ATOMS:
inc_struct = self.structure_builder.get_structure()
c_ter = None
for model in inc_struct:
for chain in model:
if chain.id == r['chain']:
for residue in chain: # Find Last residue matching name
if residue.resname == r['name']:
c_ter = residue
if c_ter:
c_ter.add(ter_atom) | python | def _parse(self):
"""
Parse atomic data of the XML file.
"""
atom_counter = 0
structure_build = self.structure_builder
residues = self._extract_residues()
cur_model = None
cur_chain = None
structure_build.init_seg(' ') # There is never a SEGID present
for r in residues:
# New model?
if cur_model != r['model']:
cur_model = r['model']
try:
structure_build.init_model(cur_model)
except PDBConstructionException, message:
self._handle_builder_exception(message, r)
# New chain?
if cur_chain != r['chain']:
cur_chain = r['chain']
try:
structure_build.init_chain(cur_chain)
except PDBConstructionException, message:
self._handle_builder_exception(message, r)
# Create residue
if r['name'] in AA_LIST: # Get residue type crudely since there is no HETATM / ATOM
hetero_flag = ' '
elif r['name'] == 'WAT' or r['name'] == 'HOH':
hetero_flag = 'W'
else:
hetero_flag = 'H'
# Some terminal atoms are added at residue 0. This residue has a small number of atoms.
# Protonated non-terminal glycine has 7 atoms. Any of these residues is smaller.
# HETATMs have only a couple of atoms (3 for water for example) and they are ok.
if (len(r['atoms']) >= 7) or (hetero_flag != " "):
try:
structure_build.init_residue(r['name'], hetero_flag, r['number'], r['icode'])
except PDBConstructionException, message:
self._handle_builder_exception(message, r)
# Create Atoms
for atom in r['atoms']:
a = self._parse_atom(atom)
if not sum(a['coord']): # e.g. HG of metal bound CYS coords are 0,0,0.
continue
try:
atom_counter += 1
# fullname = name; altloc is empty;
structure_build.init_atom(a['name'], a['coord'], a['bfactor'], a['occupancy'], ' ',
a['name'], atom_counter, a['element'], hetero_flag)
except PDBConstructionException, message:
self._handle_builder_exception(message, r)
elif len(r['atoms']) < 7: # Terminal Residues
for atom in r['atoms']:
a = self._parse_atom(atom)
if not sum(a['coord']): # e.g. HG of metal bound CYS coords are 0,0,0.
continue
atom_counter += 1
ter_atom = Atom(a['name'], a['coord'], a['bfactor'], a['occupancy'], ' ',
a['name'], atom_counter, a['element'], hetero_flag)
if a['name'] in N_TERMINAL_ATOMS:
inc_struct = self.structure_builder.get_structure()
for model in inc_struct:
for chain in model:
if chain.id == r['chain']:
for residue in chain: # Find First residue matching name
if residue.resname == r['name']:
residue.add(ter_atom)
break
elif a['name'] in C_TERMINAL_ATOMS:
inc_struct = self.structure_builder.get_structure()
c_ter = None
for model in inc_struct:
for chain in model:
if chain.id == r['chain']:
for residue in chain: # Find Last residue matching name
if residue.resname == r['name']:
c_ter = residue
if c_ter:
c_ter.add(ter_atom) | [
"def",
"_parse",
"(",
"self",
")",
":",
"atom_counter",
"=",
"0",
"structure_build",
"=",
"self",
".",
"structure_builder",
"residues",
"=",
"self",
".",
"_extract_residues",
"(",
")",
"cur_model",
"=",
"None",
"cur_chain",
"=",
"None",
"structure_build",
".",... | Parse atomic data of the XML file. | [
"Parse",
"atomic",
"data",
"of",
"the",
"XML",
"file",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/biopython/Bio/Struct/WWW/WHATIFXML.py#L81-L182 | train | 29,128 |
SBRG/ssbio | ssbio/biopython/Bio/Struct/WWW/WHATIFXML.py | XMLParser._extract_residues | def _extract_residues(self):
"""
WHAT IF puts terminal atoms in new residues at the end for some reason..
"""
r_list = self.handle.getElementsByTagName("response")
r_data = {}
for r in r_list:
data = self._parse_residue(r)
res_id = (data['model'], data['chain'], data['number']) # (A, 1, 1), (A, 1, 2), ...
if not r_data.has_key(res_id):
r_data[res_id] = data
else: # Some atoms get repeated at the end with TER Hydrogens/oxygens
r_data[res_id]['atoms'] += data['atoms'] # Append Atoms
for key in sorted(r_data.keys()):
yield r_data[key] | python | def _extract_residues(self):
"""
WHAT IF puts terminal atoms in new residues at the end for some reason..
"""
r_list = self.handle.getElementsByTagName("response")
r_data = {}
for r in r_list:
data = self._parse_residue(r)
res_id = (data['model'], data['chain'], data['number']) # (A, 1, 1), (A, 1, 2), ...
if not r_data.has_key(res_id):
r_data[res_id] = data
else: # Some atoms get repeated at the end with TER Hydrogens/oxygens
r_data[res_id]['atoms'] += data['atoms'] # Append Atoms
for key in sorted(r_data.keys()):
yield r_data[key] | [
"def",
"_extract_residues",
"(",
"self",
")",
":",
"r_list",
"=",
"self",
".",
"handle",
".",
"getElementsByTagName",
"(",
"\"response\"",
")",
"r_data",
"=",
"{",
"}",
"for",
"r",
"in",
"r_list",
":",
"data",
"=",
"self",
".",
"_parse_residue",
"(",
"r"... | WHAT IF puts terminal atoms in new residues at the end for some reason.. | [
"WHAT",
"IF",
"puts",
"terminal",
"atoms",
"in",
"new",
"residues",
"at",
"the",
"end",
"for",
"some",
"reason",
".."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/biopython/Bio/Struct/WWW/WHATIFXML.py#L187-L205 | train | 29,129 |
SBRG/ssbio | ssbio/pipeline/atlas2.py | calculate_residue_counts_perstrain | def calculate_residue_counts_perstrain(protein_pickle_path, outdir, pdbflex_keys_file, wt_pid_cutoff=None, force_rerun=False):
"""Writes out a feather file for a PROTEIN counting amino acid occurences for ALL STRAINS along with SUBSEQUENCES"""
from collections import defaultdict
from ssbio.protein.sequence.seqprop import SeqProp
from ssbio.protein.sequence.properties.residues import _aa_property_dict_one
log = logging.getLogger(__name__)
protein_id = op.splitext(op.basename(protein_pickle_path))[0].split('_')[0]
protein_df_outfile = op.join(outdir, '{}_protein_strain_properties.fthr'.format(protein_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=protein_df_outfile):
protein = ssbio.io.load_pickle(protein_pickle_path)
# First calculate disorder cuz i forgot to
protein.get_all_disorder_predictions(representative_only=True)
# Then get all subsequences
all_protein_subseqs = protein.get_all_subsequences(pdbflex_keys_file=pdbflex_keys_file)
if not all_protein_subseqs:
log.error('{}: cannot run subsequence calculator'.format(protein.id))
return
# Each strain gets a dictionary
strain_to_infodict = defaultdict(dict)
for seqprop_to_analyze in protein.sequences:
if seqprop_to_analyze.id == protein.representative_sequence.id:
strain_id = 'K12'
elif type(seqprop_to_analyze) == SeqProp and seqprop_to_analyze.id != protein.id: # This is to filter out other KEGGProps or UniProtProps
strain_id = seqprop_to_analyze.id.split('_', 1)[1] # This split should work for all strains
else:
continue
## Additional filtering for genes marked as orthologous but actually have large deletions or something
## TODO: experiment with other cutoffs?
if wt_pid_cutoff:
aln = protein.sequence_alignments.get_by_id('{0}_{0}_{1}'.format(protein.id, seqprop_to_analyze.id))
if aln.annotations['percent_identity'] < wt_pid_cutoff:
continue
###### Calculate "all" properties ######
seqprop_to_analyze.get_biopython_pepstats()
# [ALL] aa_count
if 'amino_acids_percent-biop' not in seqprop_to_analyze.annotations: # May not run if weird amino acids in the sequence
log.warning('Protein {}, sequence {}: skipping, unable to run Biopython ProteinAnalysis'.format(protein.id,
seqprop_to_analyze.id))
continue
strain_to_infodict[strain_id].update({'aa_count_{}'.format(k): v for k, v in seqprop_to_analyze.annotations['amino_acids_content-biop'].items()})
# [ALL] aa_count_total
strain_to_infodict[strain_id]['aa_count_total'] = seqprop_to_analyze.seq_len
###### Calculate subsequence properties ######
for prop, propdict in all_protein_subseqs.items():
strain_to_infodict[strain_id].update(protein.get_subseq_props(property_dict=propdict, property_name=prop,
seqprop=seqprop_to_analyze))
protein_df = pd.DataFrame(strain_to_infodict)
protein_df.reset_index().to_feather(protein_df_outfile)
return protein_pickle_path, protein_df_outfile | python | def calculate_residue_counts_perstrain(protein_pickle_path, outdir, pdbflex_keys_file, wt_pid_cutoff=None, force_rerun=False):
"""Writes out a feather file for a PROTEIN counting amino acid occurences for ALL STRAINS along with SUBSEQUENCES"""
from collections import defaultdict
from ssbio.protein.sequence.seqprop import SeqProp
from ssbio.protein.sequence.properties.residues import _aa_property_dict_one
log = logging.getLogger(__name__)
protein_id = op.splitext(op.basename(protein_pickle_path))[0].split('_')[0]
protein_df_outfile = op.join(outdir, '{}_protein_strain_properties.fthr'.format(protein_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=protein_df_outfile):
protein = ssbio.io.load_pickle(protein_pickle_path)
# First calculate disorder cuz i forgot to
protein.get_all_disorder_predictions(representative_only=True)
# Then get all subsequences
all_protein_subseqs = protein.get_all_subsequences(pdbflex_keys_file=pdbflex_keys_file)
if not all_protein_subseqs:
log.error('{}: cannot run subsequence calculator'.format(protein.id))
return
# Each strain gets a dictionary
strain_to_infodict = defaultdict(dict)
for seqprop_to_analyze in protein.sequences:
if seqprop_to_analyze.id == protein.representative_sequence.id:
strain_id = 'K12'
elif type(seqprop_to_analyze) == SeqProp and seqprop_to_analyze.id != protein.id: # This is to filter out other KEGGProps or UniProtProps
strain_id = seqprop_to_analyze.id.split('_', 1)[1] # This split should work for all strains
else:
continue
## Additional filtering for genes marked as orthologous but actually have large deletions or something
## TODO: experiment with other cutoffs?
if wt_pid_cutoff:
aln = protein.sequence_alignments.get_by_id('{0}_{0}_{1}'.format(protein.id, seqprop_to_analyze.id))
if aln.annotations['percent_identity'] < wt_pid_cutoff:
continue
###### Calculate "all" properties ######
seqprop_to_analyze.get_biopython_pepstats()
# [ALL] aa_count
if 'amino_acids_percent-biop' not in seqprop_to_analyze.annotations: # May not run if weird amino acids in the sequence
log.warning('Protein {}, sequence {}: skipping, unable to run Biopython ProteinAnalysis'.format(protein.id,
seqprop_to_analyze.id))
continue
strain_to_infodict[strain_id].update({'aa_count_{}'.format(k): v for k, v in seqprop_to_analyze.annotations['amino_acids_content-biop'].items()})
# [ALL] aa_count_total
strain_to_infodict[strain_id]['aa_count_total'] = seqprop_to_analyze.seq_len
###### Calculate subsequence properties ######
for prop, propdict in all_protein_subseqs.items():
strain_to_infodict[strain_id].update(protein.get_subseq_props(property_dict=propdict, property_name=prop,
seqprop=seqprop_to_analyze))
protein_df = pd.DataFrame(strain_to_infodict)
protein_df.reset_index().to_feather(protein_df_outfile)
return protein_pickle_path, protein_df_outfile | [
"def",
"calculate_residue_counts_perstrain",
"(",
"protein_pickle_path",
",",
"outdir",
",",
"pdbflex_keys_file",
",",
"wt_pid_cutoff",
"=",
"None",
",",
"force_rerun",
"=",
"False",
")",
":",
"from",
"collections",
"import",
"defaultdict",
"from",
"ssbio",
".",
"pr... | Writes out a feather file for a PROTEIN counting amino acid occurences for ALL STRAINS along with SUBSEQUENCES | [
"Writes",
"out",
"a",
"feather",
"file",
"for",
"a",
"PROTEIN",
"counting",
"amino",
"acid",
"occurences",
"for",
"ALL",
"STRAINS",
"along",
"with",
"SUBSEQUENCES"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas2.py#L722-L785 | train | 29,130 |
SBRG/ssbio | ssbio/pipeline/atlas2.py | ATLAS2.filter_genes_and_strains | def filter_genes_and_strains(self, remove_genes_not_in_reference_model=True,
remove_strains_with_no_orthology=True, remove_strains_with_no_differences=False,
custom_keep_strains=None, custom_keep_genes=None):
"""Filters the analysis by keeping a subset of strains or genes based on certain criteria.
Args:
remove_genes_not_in_reference_model (bool): Remove genes from reference model not in orthology matrix
remove_strains_with_no_orthology (bool): Remove strains which have no orthologous genes found
remove_strains_with_no_differences (bool): Remove strains which have all the same genes as the base model.
Default is False because since orthology is found using a PID cutoff, all genes may be present but
differences may be on the sequence level.
custom_keep_genes (list): List of gene IDs to keep in analysis
custom_keep_strains (list): List of strain IDs to keep in analysis
"""
if len(self.df_orthology_matrix) == 0:
raise RuntimeError('Empty orthology matrix, please calculate first!')
reference_strain_gene_ids = [x.id for x in self.reference_gempro.genes]
initial_num_genes = len(reference_strain_gene_ids)
initial_num_strains = len(self.strain_ids)
# Gene filtering
to_remove_genes = []
if custom_keep_genes:
to_remove_genes.extend([x for x in reference_strain_gene_ids if x not in custom_keep_genes])
if remove_genes_not_in_reference_model:
to_remove_genes.extend([x for x in reference_strain_gene_ids if x not in self.df_orthology_matrix.index.tolist()])
to_remove_genes = list(set(to_remove_genes))
if self.reference_gempro.model:
cobra.manipulation.delete_model_genes(self.reference_gempro.model, to_remove_genes)
else:
for g_id in to_remove_genes:
self.reference_gempro.genes.get_by_id(g_id).functional = False
# Create new orthology matrix with only our genes of interest
new_gene_subset = [x.id for x in self.reference_gempro.functional_genes]
tmp_new_orthology_matrix = self.df_orthology_matrix[self.df_orthology_matrix.index.isin(new_gene_subset)]
# Strain filtering
if custom_keep_strains or remove_strains_with_no_orthology or remove_strains_with_no_differences:
for strain_id in self.strain_ids:
if custom_keep_strains:
if strain_id not in custom_keep_strains:
self.strain_ids.remove(strain_id)
continue
if remove_strains_with_no_orthology:
if strain_id not in tmp_new_orthology_matrix.columns:
self.strain_ids.remove(strain_id)
log.info('{}: no orthologous genes found for this strain, removed from analysis.'.format(strain_id))
continue
elif tmp_new_orthology_matrix[strain_id].isnull().all():
self.strain_ids.remove(strain_id)
log.info('{}: no orthologous genes found for this strain, removed from analysis.'.format(strain_id))
continue
if remove_strains_with_no_differences:
not_in_strain = tmp_new_orthology_matrix[pd.isnull(tmp_new_orthology_matrix[strain_id])][strain_id].index.tolist()
if len(not_in_strain) == 0:
self.strain_ids.remove(strain_id)
log.info('{}: strain has no differences from the base, removed from analysis.')
continue
log.info('{} genes to be analyzed, originally {}'.format(len(self.reference_gempro.functional_genes), initial_num_genes))
log.info('{} strains to be analyzed, originally {}'.format(len(self.strain_ids), initial_num_strains)) | python | def filter_genes_and_strains(self, remove_genes_not_in_reference_model=True,
remove_strains_with_no_orthology=True, remove_strains_with_no_differences=False,
custom_keep_strains=None, custom_keep_genes=None):
"""Filters the analysis by keeping a subset of strains or genes based on certain criteria.
Args:
remove_genes_not_in_reference_model (bool): Remove genes from reference model not in orthology matrix
remove_strains_with_no_orthology (bool): Remove strains which have no orthologous genes found
remove_strains_with_no_differences (bool): Remove strains which have all the same genes as the base model.
Default is False because since orthology is found using a PID cutoff, all genes may be present but
differences may be on the sequence level.
custom_keep_genes (list): List of gene IDs to keep in analysis
custom_keep_strains (list): List of strain IDs to keep in analysis
"""
if len(self.df_orthology_matrix) == 0:
raise RuntimeError('Empty orthology matrix, please calculate first!')
reference_strain_gene_ids = [x.id for x in self.reference_gempro.genes]
initial_num_genes = len(reference_strain_gene_ids)
initial_num_strains = len(self.strain_ids)
# Gene filtering
to_remove_genes = []
if custom_keep_genes:
to_remove_genes.extend([x for x in reference_strain_gene_ids if x not in custom_keep_genes])
if remove_genes_not_in_reference_model:
to_remove_genes.extend([x for x in reference_strain_gene_ids if x not in self.df_orthology_matrix.index.tolist()])
to_remove_genes = list(set(to_remove_genes))
if self.reference_gempro.model:
cobra.manipulation.delete_model_genes(self.reference_gempro.model, to_remove_genes)
else:
for g_id in to_remove_genes:
self.reference_gempro.genes.get_by_id(g_id).functional = False
# Create new orthology matrix with only our genes of interest
new_gene_subset = [x.id for x in self.reference_gempro.functional_genes]
tmp_new_orthology_matrix = self.df_orthology_matrix[self.df_orthology_matrix.index.isin(new_gene_subset)]
# Strain filtering
if custom_keep_strains or remove_strains_with_no_orthology or remove_strains_with_no_differences:
for strain_id in self.strain_ids:
if custom_keep_strains:
if strain_id not in custom_keep_strains:
self.strain_ids.remove(strain_id)
continue
if remove_strains_with_no_orthology:
if strain_id not in tmp_new_orthology_matrix.columns:
self.strain_ids.remove(strain_id)
log.info('{}: no orthologous genes found for this strain, removed from analysis.'.format(strain_id))
continue
elif tmp_new_orthology_matrix[strain_id].isnull().all():
self.strain_ids.remove(strain_id)
log.info('{}: no orthologous genes found for this strain, removed from analysis.'.format(strain_id))
continue
if remove_strains_with_no_differences:
not_in_strain = tmp_new_orthology_matrix[pd.isnull(tmp_new_orthology_matrix[strain_id])][strain_id].index.tolist()
if len(not_in_strain) == 0:
self.strain_ids.remove(strain_id)
log.info('{}: strain has no differences from the base, removed from analysis.')
continue
log.info('{} genes to be analyzed, originally {}'.format(len(self.reference_gempro.functional_genes), initial_num_genes))
log.info('{} strains to be analyzed, originally {}'.format(len(self.strain_ids), initial_num_strains)) | [
"def",
"filter_genes_and_strains",
"(",
"self",
",",
"remove_genes_not_in_reference_model",
"=",
"True",
",",
"remove_strains_with_no_orthology",
"=",
"True",
",",
"remove_strains_with_no_differences",
"=",
"False",
",",
"custom_keep_strains",
"=",
"None",
",",
"custom_keep... | Filters the analysis by keeping a subset of strains or genes based on certain criteria.
Args:
remove_genes_not_in_reference_model (bool): Remove genes from reference model not in orthology matrix
remove_strains_with_no_orthology (bool): Remove strains which have no orthologous genes found
remove_strains_with_no_differences (bool): Remove strains which have all the same genes as the base model.
Default is False because since orthology is found using a PID cutoff, all genes may be present but
differences may be on the sequence level.
custom_keep_genes (list): List of gene IDs to keep in analysis
custom_keep_strains (list): List of strain IDs to keep in analysis | [
"Filters",
"the",
"analysis",
"by",
"keeping",
"a",
"subset",
"of",
"strains",
"or",
"genes",
"based",
"on",
"certain",
"criteria",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas2.py#L242-L310 | train | 29,131 |
SBRG/ssbio | ssbio/pipeline/atlas2.py | ATLAS2._write_strain_functional_genes | def _write_strain_functional_genes(self, strain_id, ref_functional_genes, orth_matrix, force_rerun=False):
"""Create strain functional genes json file"""
func_genes_path = op.join(self.model_dir, '{}_funcgenes.json'.format(strain_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=func_genes_path):
gene_to_func = {k:True for k in ref_functional_genes}
# Get a list of genes which do not have orthology in the strain
genes_to_remove = orth_matrix[pd.isnull(orth_matrix[strain_id])][strain_id].index.tolist()
# Mark genes non-functional
genes_to_remove = list(set(genes_to_remove).intersection(set(ref_functional_genes)))
if len(genes_to_remove) > 0:
for g in genes_to_remove:
gene_to_func[g] = False
with open(func_genes_path, 'w') as f:
json.dump(gene_to_func, f)
else:
with open(func_genes_path, 'r') as f:
gene_to_func = json.load(f)
return strain_id, gene_to_func | python | def _write_strain_functional_genes(self, strain_id, ref_functional_genes, orth_matrix, force_rerun=False):
"""Create strain functional genes json file"""
func_genes_path = op.join(self.model_dir, '{}_funcgenes.json'.format(strain_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=func_genes_path):
gene_to_func = {k:True for k in ref_functional_genes}
# Get a list of genes which do not have orthology in the strain
genes_to_remove = orth_matrix[pd.isnull(orth_matrix[strain_id])][strain_id].index.tolist()
# Mark genes non-functional
genes_to_remove = list(set(genes_to_remove).intersection(set(ref_functional_genes)))
if len(genes_to_remove) > 0:
for g in genes_to_remove:
gene_to_func[g] = False
with open(func_genes_path, 'w') as f:
json.dump(gene_to_func, f)
else:
with open(func_genes_path, 'r') as f:
gene_to_func = json.load(f)
return strain_id, gene_to_func | [
"def",
"_write_strain_functional_genes",
"(",
"self",
",",
"strain_id",
",",
"ref_functional_genes",
",",
"orth_matrix",
",",
"force_rerun",
"=",
"False",
")",
":",
"func_genes_path",
"=",
"op",
".",
"join",
"(",
"self",
".",
"model_dir",
",",
"'{}_funcgenes.json'... | Create strain functional genes json file | [
"Create",
"strain",
"functional",
"genes",
"json",
"file"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas2.py#L312-L334 | train | 29,132 |
SBRG/ssbio | ssbio/pipeline/atlas2.py | ATLAS2.write_strain_functional_genes | def write_strain_functional_genes(self, force_rerun=False):
"""Wrapper function for _write_strain_functional_genes"""
if len(self.df_orthology_matrix) == 0:
raise RuntimeError('Empty orthology matrix, please calculate first!')
ref_functional_genes = [g.id for g in self.reference_gempro.functional_genes]
log.info('Building strain specific models...')
result = []
for s in tqdm(self.strain_ids):
result.append(self._write_strain_functional_genes(s, ref_functional_genes, self.df_orthology_matrix, force_rerun=force_rerun))
for strain_id, functional_genes in result:
self.strain_infodict[strain_id]['functional_genes'] = functional_genes | python | def write_strain_functional_genes(self, force_rerun=False):
"""Wrapper function for _write_strain_functional_genes"""
if len(self.df_orthology_matrix) == 0:
raise RuntimeError('Empty orthology matrix, please calculate first!')
ref_functional_genes = [g.id for g in self.reference_gempro.functional_genes]
log.info('Building strain specific models...')
result = []
for s in tqdm(self.strain_ids):
result.append(self._write_strain_functional_genes(s, ref_functional_genes, self.df_orthology_matrix, force_rerun=force_rerun))
for strain_id, functional_genes in result:
self.strain_infodict[strain_id]['functional_genes'] = functional_genes | [
"def",
"write_strain_functional_genes",
"(",
"self",
",",
"force_rerun",
"=",
"False",
")",
":",
"if",
"len",
"(",
"self",
".",
"df_orthology_matrix",
")",
"==",
"0",
":",
"raise",
"RuntimeError",
"(",
"'Empty orthology matrix, please calculate first!'",
")",
"ref_f... | Wrapper function for _write_strain_functional_genes | [
"Wrapper",
"function",
"for",
"_write_strain_functional_genes"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas2.py#L336-L347 | train | 29,133 |
SBRG/ssbio | ssbio/pipeline/atlas2.py | ATLAS2._build_strain_specific_model | def _build_strain_specific_model(self, strain_id, ref_functional_genes, orth_matrix, force_rerun=False):
"""Create strain GEMPRO, set functional genes"""
gp_noseqs_path = op.join(self.model_dir, '{}_gp.pckl'.format(strain_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=gp_noseqs_path):
logging.disable(logging.WARNING)
strain_gp = GEMPRO(gem_name=strain_id)
# if self.reference_gempro.model:
# strain_gp.load_cobra_model(deepcopy(self.reference_gempro.model))
# # Reset the GenePro attributes
# for x in strain_gp.genes:
# x.reset_protein()
# else:
# Otherwise, just copy the list of genes over and rename the IDs
strain_genes = [x for x in ref_functional_genes]
strain_gp.add_gene_ids(strain_genes)
logging.disable(logging.NOTSET)
# Get a list of genes which do not have orthology in the strain
genes_to_remove = orth_matrix[pd.isnull(orth_matrix[strain_id])][strain_id].index.tolist()
# Mark genes non-functional
strain_genes = [x.id for x in strain_gp.genes]
genes_to_remove = list(set(genes_to_remove).intersection(set(strain_genes)))
if len(genes_to_remove) > 0:
# If a COBRApy model exists, utilize the delete_model_genes method
# if strain_gp.model:
# cobra.manipulation.delete_model_genes(strain_gp.model, genes_to_remove)
# # Otherwise, just mark the genes as non-functional
# else:
for g in genes_to_remove:
strain_gp.genes.get_by_id(g).functional = False
strain_gp.save_pickle(outfile=gp_noseqs_path)
return strain_id, gp_noseqs_path | python | def _build_strain_specific_model(self, strain_id, ref_functional_genes, orth_matrix, force_rerun=False):
"""Create strain GEMPRO, set functional genes"""
gp_noseqs_path = op.join(self.model_dir, '{}_gp.pckl'.format(strain_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=gp_noseqs_path):
logging.disable(logging.WARNING)
strain_gp = GEMPRO(gem_name=strain_id)
# if self.reference_gempro.model:
# strain_gp.load_cobra_model(deepcopy(self.reference_gempro.model))
# # Reset the GenePro attributes
# for x in strain_gp.genes:
# x.reset_protein()
# else:
# Otherwise, just copy the list of genes over and rename the IDs
strain_genes = [x for x in ref_functional_genes]
strain_gp.add_gene_ids(strain_genes)
logging.disable(logging.NOTSET)
# Get a list of genes which do not have orthology in the strain
genes_to_remove = orth_matrix[pd.isnull(orth_matrix[strain_id])][strain_id].index.tolist()
# Mark genes non-functional
strain_genes = [x.id for x in strain_gp.genes]
genes_to_remove = list(set(genes_to_remove).intersection(set(strain_genes)))
if len(genes_to_remove) > 0:
# If a COBRApy model exists, utilize the delete_model_genes method
# if strain_gp.model:
# cobra.manipulation.delete_model_genes(strain_gp.model, genes_to_remove)
# # Otherwise, just mark the genes as non-functional
# else:
for g in genes_to_remove:
strain_gp.genes.get_by_id(g).functional = False
strain_gp.save_pickle(outfile=gp_noseqs_path)
return strain_id, gp_noseqs_path | [
"def",
"_build_strain_specific_model",
"(",
"self",
",",
"strain_id",
",",
"ref_functional_genes",
",",
"orth_matrix",
",",
"force_rerun",
"=",
"False",
")",
":",
"gp_noseqs_path",
"=",
"op",
".",
"join",
"(",
"self",
".",
"model_dir",
",",
"'{}_gp.pckl'",
".",
... | Create strain GEMPRO, set functional genes | [
"Create",
"strain",
"GEMPRO",
"set",
"functional",
"genes"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas2.py#L349-L388 | train | 29,134 |
SBRG/ssbio | ssbio/pipeline/atlas2.py | ATLAS2.build_strain_specific_models | def build_strain_specific_models(self, joblib=False, cores=1, force_rerun=False):
"""Wrapper function for _build_strain_specific_model"""
if len(self.df_orthology_matrix) == 0:
raise RuntimeError('Empty orthology matrix, please calculate first!')
ref_functional_genes = [g.id for g in self.reference_gempro.functional_genes]
log.info('Building strain specific models...')
if joblib:
result = DictList(Parallel(n_jobs=cores)(delayed(self._build_strain_specific_model)(s, ref_functional_genes, self.df_orthology_matrix, force_rerun=force_rerun) for s in self.strain_ids))
# if sc:
# strains_rdd = sc.parallelize(self.strain_ids)
# result = strains_rdd.map(self._build_strain_specific_model).collect()
else:
result = []
for s in tqdm(self.strain_ids):
result.append(self._build_strain_specific_model(s, ref_functional_genes, self.df_orthology_matrix, force_rerun=force_rerun))
for strain_id, gp_noseqs_path in result:
self.strain_infodict[strain_id]['gp_noseqs_path'] = gp_noseqs_path | python | def build_strain_specific_models(self, joblib=False, cores=1, force_rerun=False):
"""Wrapper function for _build_strain_specific_model"""
if len(self.df_orthology_matrix) == 0:
raise RuntimeError('Empty orthology matrix, please calculate first!')
ref_functional_genes = [g.id for g in self.reference_gempro.functional_genes]
log.info('Building strain specific models...')
if joblib:
result = DictList(Parallel(n_jobs=cores)(delayed(self._build_strain_specific_model)(s, ref_functional_genes, self.df_orthology_matrix, force_rerun=force_rerun) for s in self.strain_ids))
# if sc:
# strains_rdd = sc.parallelize(self.strain_ids)
# result = strains_rdd.map(self._build_strain_specific_model).collect()
else:
result = []
for s in tqdm(self.strain_ids):
result.append(self._build_strain_specific_model(s, ref_functional_genes, self.df_orthology_matrix, force_rerun=force_rerun))
for strain_id, gp_noseqs_path in result:
self.strain_infodict[strain_id]['gp_noseqs_path'] = gp_noseqs_path | [
"def",
"build_strain_specific_models",
"(",
"self",
",",
"joblib",
"=",
"False",
",",
"cores",
"=",
"1",
",",
"force_rerun",
"=",
"False",
")",
":",
"if",
"len",
"(",
"self",
".",
"df_orthology_matrix",
")",
"==",
"0",
":",
"raise",
"RuntimeError",
"(",
... | Wrapper function for _build_strain_specific_model | [
"Wrapper",
"function",
"for",
"_build_strain_specific_model"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas2.py#L390-L407 | train | 29,135 |
SBRG/ssbio | ssbio/pipeline/atlas2.py | ATLAS2._load_sequences_to_strain | def _load_sequences_to_strain(self, strain_id, force_rerun=False):
"""Load strain GEMPRO with functional genes defined, load sequences to it, save as new GEMPRO"""
gp_seqs_path = op.join(self.model_dir, '{}_gp_withseqs.pckl'.format(strain_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=gp_seqs_path):
gp_noseqs = ssbio.io.load_pickle(self.strain_infodict[strain_id]['gp_noseqs_path'])
strain_sequences = SeqIO.index(self.strain_infodict[strain_id]['genome_path'], 'fasta')
for strain_gene in gp_noseqs.functional_genes:
# Pull the gene ID of the strain from the orthology matrix
strain_gene_key = self.df_orthology_matrix.at[strain_gene.id, strain_id]
# Load into the strain GEM-PRO
new_id = '{}_{}'.format(strain_gene.id, strain_id)
if strain_gene.protein.sequences.has_id(new_id):
continue
strain_gene.protein.load_manual_sequence(seq=strain_sequences[strain_gene_key], ident=new_id,
set_as_representative=True)
gp_noseqs.save_pickle(outfile=gp_seqs_path)
return strain_id, gp_seqs_path | python | def _load_sequences_to_strain(self, strain_id, force_rerun=False):
"""Load strain GEMPRO with functional genes defined, load sequences to it, save as new GEMPRO"""
gp_seqs_path = op.join(self.model_dir, '{}_gp_withseqs.pckl'.format(strain_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=gp_seqs_path):
gp_noseqs = ssbio.io.load_pickle(self.strain_infodict[strain_id]['gp_noseqs_path'])
strain_sequences = SeqIO.index(self.strain_infodict[strain_id]['genome_path'], 'fasta')
for strain_gene in gp_noseqs.functional_genes:
# Pull the gene ID of the strain from the orthology matrix
strain_gene_key = self.df_orthology_matrix.at[strain_gene.id, strain_id]
# Load into the strain GEM-PRO
new_id = '{}_{}'.format(strain_gene.id, strain_id)
if strain_gene.protein.sequences.has_id(new_id):
continue
strain_gene.protein.load_manual_sequence(seq=strain_sequences[strain_gene_key], ident=new_id,
set_as_representative=True)
gp_noseqs.save_pickle(outfile=gp_seqs_path)
return strain_id, gp_seqs_path | [
"def",
"_load_sequences_to_strain",
"(",
"self",
",",
"strain_id",
",",
"force_rerun",
"=",
"False",
")",
":",
"gp_seqs_path",
"=",
"op",
".",
"join",
"(",
"self",
".",
"model_dir",
",",
"'{}_gp_withseqs.pckl'",
".",
"format",
"(",
"strain_id",
")",
")",
"if... | Load strain GEMPRO with functional genes defined, load sequences to it, save as new GEMPRO | [
"Load",
"strain",
"GEMPRO",
"with",
"functional",
"genes",
"defined",
"load",
"sequences",
"to",
"it",
"save",
"as",
"new",
"GEMPRO"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas2.py#L409-L427 | train | 29,136 |
SBRG/ssbio | ssbio/pipeline/atlas2.py | ATLAS2.load_sequences_to_strains | def load_sequences_to_strains(self, joblib=False, cores=1, force_rerun=False):
"""Wrapper function for _load_sequences_to_strain"""
log.info('Loading sequences to strain GEM-PROs...')
if joblib:
result = DictList(Parallel(n_jobs=cores)(delayed(self._load_sequences_to_strain)(s, force_rerun) for s in self.strain_ids))
else:
result = []
for s in tqdm(self.strain_ids):
result.append(self._load_sequences_to_strain(s, force_rerun))
for strain_id, gp_seqs_path in result:
self.strain_infodict[strain_id]['gp_seqs_path'] = gp_seqs_path | python | def load_sequences_to_strains(self, joblib=False, cores=1, force_rerun=False):
"""Wrapper function for _load_sequences_to_strain"""
log.info('Loading sequences to strain GEM-PROs...')
if joblib:
result = DictList(Parallel(n_jobs=cores)(delayed(self._load_sequences_to_strain)(s, force_rerun) for s in self.strain_ids))
else:
result = []
for s in tqdm(self.strain_ids):
result.append(self._load_sequences_to_strain(s, force_rerun))
for strain_id, gp_seqs_path in result:
self.strain_infodict[strain_id]['gp_seqs_path'] = gp_seqs_path | [
"def",
"load_sequences_to_strains",
"(",
"self",
",",
"joblib",
"=",
"False",
",",
"cores",
"=",
"1",
",",
"force_rerun",
"=",
"False",
")",
":",
"log",
".",
"info",
"(",
"'Loading sequences to strain GEM-PROs...'",
")",
"if",
"joblib",
":",
"result",
"=",
"... | Wrapper function for _load_sequences_to_strain | [
"Wrapper",
"function",
"for",
"_load_sequences_to_strain"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas2.py#L429-L440 | train | 29,137 |
SBRG/ssbio | ssbio/pipeline/atlas2.py | ATLAS2._load_sequences_to_reference_gene | def _load_sequences_to_reference_gene(self, g_id, force_rerun=False):
"""Load orthologous strain sequences to reference Protein object, save as new pickle"""
protein_seqs_pickle_path = op.join(self.sequences_by_gene_dir, '{}_protein_withseqs.pckl'.format(g_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=protein_seqs_pickle_path):
protein_pickle_path = self.gene_protein_pickles[g_id]
protein_pickle = ssbio.io.load_pickle(protein_pickle_path)
for strain, info in self.strain_infodict.items():
strain_sequences = SeqIO.index(info['genome_path'], 'fasta')
strain_gene_functional = info['functional_genes'][g_id]
if strain_gene_functional:
# Pull the gene ID of the strain from the orthology matrix
strain_gene_key = self.df_orthology_matrix.at[g_id, strain]
new_id = '{}_{}'.format(g_id, strain)
if protein_pickle.sequences.has_id(new_id):
continue
protein_pickle.load_manual_sequence(seq=strain_sequences[strain_gene_key],
ident=new_id,
set_as_representative=False)
protein_pickle.save_pickle(outfile=protein_seqs_pickle_path)
return g_id, protein_seqs_pickle_path | python | def _load_sequences_to_reference_gene(self, g_id, force_rerun=False):
"""Load orthologous strain sequences to reference Protein object, save as new pickle"""
protein_seqs_pickle_path = op.join(self.sequences_by_gene_dir, '{}_protein_withseqs.pckl'.format(g_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=protein_seqs_pickle_path):
protein_pickle_path = self.gene_protein_pickles[g_id]
protein_pickle = ssbio.io.load_pickle(protein_pickle_path)
for strain, info in self.strain_infodict.items():
strain_sequences = SeqIO.index(info['genome_path'], 'fasta')
strain_gene_functional = info['functional_genes'][g_id]
if strain_gene_functional:
# Pull the gene ID of the strain from the orthology matrix
strain_gene_key = self.df_orthology_matrix.at[g_id, strain]
new_id = '{}_{}'.format(g_id, strain)
if protein_pickle.sequences.has_id(new_id):
continue
protein_pickle.load_manual_sequence(seq=strain_sequences[strain_gene_key],
ident=new_id,
set_as_representative=False)
protein_pickle.save_pickle(outfile=protein_seqs_pickle_path)
return g_id, protein_seqs_pickle_path | [
"def",
"_load_sequences_to_reference_gene",
"(",
"self",
",",
"g_id",
",",
"force_rerun",
"=",
"False",
")",
":",
"protein_seqs_pickle_path",
"=",
"op",
".",
"join",
"(",
"self",
".",
"sequences_by_gene_dir",
",",
"'{}_protein_withseqs.pckl'",
".",
"format",
"(",
... | Load orthologous strain sequences to reference Protein object, save as new pickle | [
"Load",
"orthologous",
"strain",
"sequences",
"to",
"reference",
"Protein",
"object",
"save",
"as",
"new",
"pickle"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas2.py#L442-L464 | train | 29,138 |
SBRG/ssbio | ssbio/pipeline/atlas2.py | ATLAS2.load_sequences_to_reference | def load_sequences_to_reference(self, sc=None, force_rerun=False):
"""Wrapper for _load_sequences_to_reference_gene"""
log.info('Loading sequences to reference GEM-PRO...')
from random import shuffle
g_ids = [g.id for g in self.reference_gempro.functional_genes]
shuffle(g_ids)
def _load_sequences_to_reference_gene_sc(g_id, outdir=self.sequences_by_gene_dir,
g_to_pickle=self.gene_protein_pickles,
strain_infodict=self.strain_infodict,
orth_matrix=self.df_orthology_matrix, force_rerun=force_rerun):
"""Load orthologous strain sequences to reference Protein object, save as new pickle"""
import ssbio.utils
import ssbio.io
from Bio import SeqIO
import os.path as op
protein_seqs_pickle_path = op.join(outdir, '{}_protein_withseqs.pckl'.format(g_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=protein_seqs_pickle_path):
protein_pickle_path = g_to_pickle[g_id]
protein_pickle = ssbio.io.load_pickle(protein_pickle_path)
for strain, info in strain_infodict.items():
strain_sequences = SeqIO.index(info['genome_path'], 'fasta')
strain_gene_functional = info['functional_genes'][g_id]
if strain_gene_functional:
# Pull the gene ID of the strain from the orthology matrix
strain_gene_key = orth_matrix.at[g_id, strain]
new_id = '{}_{}'.format(g_id, strain)
if protein_pickle.sequences.has_id(new_id):
continue
protein_pickle.load_manual_sequence(seq=strain_sequences[strain_gene_key],
ident=new_id,
set_as_representative=False)
protein_pickle.save_pickle(outfile=protein_seqs_pickle_path)
return g_id, protein_seqs_pickle_path
if sc:
genes_rdd = sc.parallelize(g_ids)
result = genes_rdd.map(_load_sequences_to_reference_gene_sc).collect()
else:
result = []
for g in tqdm(g_ids):
result.append(self._load_sequences_to_reference_gene(g, force_rerun))
log.info('Storing paths to new Protein objects in self.gene_protein_pickles...')
updated = []
for g_id, protein_pickle in result:
self.gene_protein_pickles[g_id] = protein_pickle
updated.append(g_id)
not_updated = set(list(self.gene_protein_pickles.keys())).difference(updated)
log.info('No change to {} genes, removing from gene_protein_pickles'.format(len(not_updated)))
log.debug(not_updated)
for rem in not_updated:
del self.gene_protein_pickles[rem] | python | def load_sequences_to_reference(self, sc=None, force_rerun=False):
"""Wrapper for _load_sequences_to_reference_gene"""
log.info('Loading sequences to reference GEM-PRO...')
from random import shuffle
g_ids = [g.id for g in self.reference_gempro.functional_genes]
shuffle(g_ids)
def _load_sequences_to_reference_gene_sc(g_id, outdir=self.sequences_by_gene_dir,
g_to_pickle=self.gene_protein_pickles,
strain_infodict=self.strain_infodict,
orth_matrix=self.df_orthology_matrix, force_rerun=force_rerun):
"""Load orthologous strain sequences to reference Protein object, save as new pickle"""
import ssbio.utils
import ssbio.io
from Bio import SeqIO
import os.path as op
protein_seqs_pickle_path = op.join(outdir, '{}_protein_withseqs.pckl'.format(g_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=protein_seqs_pickle_path):
protein_pickle_path = g_to_pickle[g_id]
protein_pickle = ssbio.io.load_pickle(protein_pickle_path)
for strain, info in strain_infodict.items():
strain_sequences = SeqIO.index(info['genome_path'], 'fasta')
strain_gene_functional = info['functional_genes'][g_id]
if strain_gene_functional:
# Pull the gene ID of the strain from the orthology matrix
strain_gene_key = orth_matrix.at[g_id, strain]
new_id = '{}_{}'.format(g_id, strain)
if protein_pickle.sequences.has_id(new_id):
continue
protein_pickle.load_manual_sequence(seq=strain_sequences[strain_gene_key],
ident=new_id,
set_as_representative=False)
protein_pickle.save_pickle(outfile=protein_seqs_pickle_path)
return g_id, protein_seqs_pickle_path
if sc:
genes_rdd = sc.parallelize(g_ids)
result = genes_rdd.map(_load_sequences_to_reference_gene_sc).collect()
else:
result = []
for g in tqdm(g_ids):
result.append(self._load_sequences_to_reference_gene(g, force_rerun))
log.info('Storing paths to new Protein objects in self.gene_protein_pickles...')
updated = []
for g_id, protein_pickle in result:
self.gene_protein_pickles[g_id] = protein_pickle
updated.append(g_id)
not_updated = set(list(self.gene_protein_pickles.keys())).difference(updated)
log.info('No change to {} genes, removing from gene_protein_pickles'.format(len(not_updated)))
log.debug(not_updated)
for rem in not_updated:
del self.gene_protein_pickles[rem] | [
"def",
"load_sequences_to_reference",
"(",
"self",
",",
"sc",
"=",
"None",
",",
"force_rerun",
"=",
"False",
")",
":",
"log",
".",
"info",
"(",
"'Loading sequences to reference GEM-PRO...'",
")",
"from",
"random",
"import",
"shuffle",
"g_ids",
"=",
"[",
"g",
"... | Wrapper for _load_sequences_to_reference_gene | [
"Wrapper",
"for",
"_load_sequences_to_reference_gene"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas2.py#L466-L522 | train | 29,139 |
SBRG/ssbio | ssbio/pipeline/atlas2.py | ATLAS2.store_disorder | def store_disorder(self, sc=None, force_rerun=False):
"""Wrapper for _store_disorder"""
log.info('Loading sequences to reference GEM-PRO...')
from random import shuffle
g_ids = [g.id for g in self.reference_gempro.functional_genes]
shuffle(g_ids)
def _store_disorder_sc(g_id, outdir=self.sequences_by_gene_dir,
g_to_pickle=self.gene_protein_pickles, force_rerun=force_rerun):
"""Load orthologous strain sequences to reference Protein object, save as new pickle"""
import ssbio.utils
import ssbio.io
import os.path as op
protein_seqs_pickle_path = op.join(outdir, '{}_protein_withseqs_dis.pckl'.format(g_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=protein_seqs_pickle_path):
protein_pickle_path = g_to_pickle[g_id]
protein_pickle = ssbio.io.load_pickle(protein_pickle_path)
protein_pickle.get_all_disorder_predictions(representative_only=False)
protein_pickle.save_pickle(outfile=protein_seqs_pickle_path)
return g_id, protein_seqs_pickle_path
if sc:
genes_rdd = sc.parallelize(g_ids)
result = genes_rdd.map(_store_disorder_sc).collect()
else:
result = []
for g in tqdm(g_ids):
result.append(self._load_sequences_to_reference_gene(g, force_rerun))
log.info('Storing paths to new Protein objects in self.gene_protein_pickles...')
for g_id, protein_pickle in result:
self.gene_protein_pickles[g_id] = protein_pickle | python | def store_disorder(self, sc=None, force_rerun=False):
"""Wrapper for _store_disorder"""
log.info('Loading sequences to reference GEM-PRO...')
from random import shuffle
g_ids = [g.id for g in self.reference_gempro.functional_genes]
shuffle(g_ids)
def _store_disorder_sc(g_id, outdir=self.sequences_by_gene_dir,
g_to_pickle=self.gene_protein_pickles, force_rerun=force_rerun):
"""Load orthologous strain sequences to reference Protein object, save as new pickle"""
import ssbio.utils
import ssbio.io
import os.path as op
protein_seqs_pickle_path = op.join(outdir, '{}_protein_withseqs_dis.pckl'.format(g_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=protein_seqs_pickle_path):
protein_pickle_path = g_to_pickle[g_id]
protein_pickle = ssbio.io.load_pickle(protein_pickle_path)
protein_pickle.get_all_disorder_predictions(representative_only=False)
protein_pickle.save_pickle(outfile=protein_seqs_pickle_path)
return g_id, protein_seqs_pickle_path
if sc:
genes_rdd = sc.parallelize(g_ids)
result = genes_rdd.map(_store_disorder_sc).collect()
else:
result = []
for g in tqdm(g_ids):
result.append(self._load_sequences_to_reference_gene(g, force_rerun))
log.info('Storing paths to new Protein objects in self.gene_protein_pickles...')
for g_id, protein_pickle in result:
self.gene_protein_pickles[g_id] = protein_pickle | [
"def",
"store_disorder",
"(",
"self",
",",
"sc",
"=",
"None",
",",
"force_rerun",
"=",
"False",
")",
":",
"log",
".",
"info",
"(",
"'Loading sequences to reference GEM-PRO...'",
")",
"from",
"random",
"import",
"shuffle",
"g_ids",
"=",
"[",
"g",
".",
"id",
... | Wrapper for _store_disorder | [
"Wrapper",
"for",
"_store_disorder"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas2.py#L524-L558 | train | 29,140 |
SBRG/ssbio | ssbio/pipeline/atlas2.py | ATLAS2._align_orthologous_gene_pairwise | def _align_orthologous_gene_pairwise(self, g_id, gapopen=10, gapextend=0.5, engine='needle', parse=True, force_rerun=False):
"""Align orthologous strain sequences to representative Protein sequence, save as new pickle"""
protein_seqs_aln_pickle_path = op.join(self.sequences_by_gene_dir, '{}_protein_withseqs_dis_aln.pckl'.format(g_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=protein_seqs_aln_pickle_path):
protein_seqs_pickle_path = self.gene_protein_pickles[g_id]
protein_pickle = ssbio.io.load_pickle(protein_seqs_pickle_path)
if not protein_pickle.representative_sequence:
log.error('{}: no representative sequence to align to'.format(g_id))
return
if len(protein_pickle.sequences) < 1:
log.error('{}: no other sequences to align to'.format(g_id))
return
alignment_dir = op.join(self.sequences_by_gene_dir, g_id)
ssbio.utils.make_dir(alignment_dir)
protein_pickle.pairwise_align_sequences_to_representative(gapopen=gapopen, gapextend=gapextend,
engine=engine, outdir=alignment_dir,
parse=parse, force_rerun=force_rerun)
protein_pickle.save_pickle(outfile=protein_seqs_aln_pickle_path)
return g_id, protein_seqs_aln_pickle_path | python | def _align_orthologous_gene_pairwise(self, g_id, gapopen=10, gapextend=0.5, engine='needle', parse=True, force_rerun=False):
"""Align orthologous strain sequences to representative Protein sequence, save as new pickle"""
protein_seqs_aln_pickle_path = op.join(self.sequences_by_gene_dir, '{}_protein_withseqs_dis_aln.pckl'.format(g_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=protein_seqs_aln_pickle_path):
protein_seqs_pickle_path = self.gene_protein_pickles[g_id]
protein_pickle = ssbio.io.load_pickle(protein_seqs_pickle_path)
if not protein_pickle.representative_sequence:
log.error('{}: no representative sequence to align to'.format(g_id))
return
if len(protein_pickle.sequences) < 1:
log.error('{}: no other sequences to align to'.format(g_id))
return
alignment_dir = op.join(self.sequences_by_gene_dir, g_id)
ssbio.utils.make_dir(alignment_dir)
protein_pickle.pairwise_align_sequences_to_representative(gapopen=gapopen, gapextend=gapextend,
engine=engine, outdir=alignment_dir,
parse=parse, force_rerun=force_rerun)
protein_pickle.save_pickle(outfile=protein_seqs_aln_pickle_path)
return g_id, protein_seqs_aln_pickle_path | [
"def",
"_align_orthologous_gene_pairwise",
"(",
"self",
",",
"g_id",
",",
"gapopen",
"=",
"10",
",",
"gapextend",
"=",
"0.5",
",",
"engine",
"=",
"'needle'",
",",
"parse",
"=",
"True",
",",
"force_rerun",
"=",
"False",
")",
":",
"protein_seqs_aln_pickle_path",... | Align orthologous strain sequences to representative Protein sequence, save as new pickle | [
"Align",
"orthologous",
"strain",
"sequences",
"to",
"representative",
"Protein",
"sequence",
"save",
"as",
"new",
"pickle"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas2.py#L560-L583 | train | 29,141 |
SBRG/ssbio | ssbio/pipeline/atlas2.py | ATLAS2.align_orthologous_genes_pairwise | def align_orthologous_genes_pairwise(self, sc=None, joblib=False, cores=1, gapopen=10, gapextend=0.5,
engine='needle', parse=True, force_rerun=False):
"""Wrapper for _align_orthologous_gene_pairwise"""
log.info('Aligning sequences to reference GEM-PRO...')
from random import shuffle
g_ids = [g.id for g in self.reference_gempro.functional_genes]
shuffle(g_ids)
def _align_orthologous_gene_pairwise_sc(g_id, g_to_pickle=self.gene_protein_pickles,
gapopen=gapopen, gapextend=gapextend, engine=engine, parse=parse,
outdir=self.sequences_by_gene_dir,
force_rerun=force_rerun):
"""Align orthologous strain sequences to representative Protein sequence, save as new pickle"""
import ssbio.utils
import ssbio.io
import os.path as op
protein_seqs_aln_pickle_path = op.join(outdir, '{}_protein_withseqs_dis_aln.pckl'.format(g_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=protein_seqs_aln_pickle_path):
protein_seqs_pickle_path = g_to_pickle[g_id]
protein_pickle = ssbio.io.load_pickle(protein_seqs_pickle_path)
if not protein_pickle.representative_sequence:
return
if len(protein_pickle.sequences) < 1:
return
alignment_dir = op.join(outdir, g_id)
ssbio.utils.make_dir(alignment_dir)
protein_pickle.pairwise_align_sequences_to_representative(gapopen=gapopen, gapextend=gapextend,
engine=engine, outdir=alignment_dir,
parse=parse, force_rerun=force_rerun)
protein_pickle.save_pickle(outfile=protein_seqs_aln_pickle_path)
return g_id, protein_seqs_aln_pickle_path
if sc:
genes_rdd = sc.parallelize(g_ids)
result_raw = genes_rdd.map(_align_orthologous_gene_pairwise_sc).collect()
else:
result_raw = []
for g in tqdm(g_ids):
result_raw.append(self._align_orthologous_gene_pairwise(g, gapopen=gapopen, gapextend=gapextend,
engine=engine, parse=parse,
force_rerun=force_rerun))
result = [x for x in result_raw if x is not None]
log.info('Storing paths to new Protein objects in self.gene_protein_pickles...')
for g_id, protein_pickle in result:
self.gene_protein_pickles[g_id] = protein_pickle | python | def align_orthologous_genes_pairwise(self, sc=None, joblib=False, cores=1, gapopen=10, gapextend=0.5,
engine='needle', parse=True, force_rerun=False):
"""Wrapper for _align_orthologous_gene_pairwise"""
log.info('Aligning sequences to reference GEM-PRO...')
from random import shuffle
g_ids = [g.id for g in self.reference_gempro.functional_genes]
shuffle(g_ids)
def _align_orthologous_gene_pairwise_sc(g_id, g_to_pickle=self.gene_protein_pickles,
gapopen=gapopen, gapextend=gapextend, engine=engine, parse=parse,
outdir=self.sequences_by_gene_dir,
force_rerun=force_rerun):
"""Align orthologous strain sequences to representative Protein sequence, save as new pickle"""
import ssbio.utils
import ssbio.io
import os.path as op
protein_seqs_aln_pickle_path = op.join(outdir, '{}_protein_withseqs_dis_aln.pckl'.format(g_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=protein_seqs_aln_pickle_path):
protein_seqs_pickle_path = g_to_pickle[g_id]
protein_pickle = ssbio.io.load_pickle(protein_seqs_pickle_path)
if not protein_pickle.representative_sequence:
return
if len(protein_pickle.sequences) < 1:
return
alignment_dir = op.join(outdir, g_id)
ssbio.utils.make_dir(alignment_dir)
protein_pickle.pairwise_align_sequences_to_representative(gapopen=gapopen, gapextend=gapextend,
engine=engine, outdir=alignment_dir,
parse=parse, force_rerun=force_rerun)
protein_pickle.save_pickle(outfile=protein_seqs_aln_pickle_path)
return g_id, protein_seqs_aln_pickle_path
if sc:
genes_rdd = sc.parallelize(g_ids)
result_raw = genes_rdd.map(_align_orthologous_gene_pairwise_sc).collect()
else:
result_raw = []
for g in tqdm(g_ids):
result_raw.append(self._align_orthologous_gene_pairwise(g, gapopen=gapopen, gapextend=gapextend,
engine=engine, parse=parse,
force_rerun=force_rerun))
result = [x for x in result_raw if x is not None]
log.info('Storing paths to new Protein objects in self.gene_protein_pickles...')
for g_id, protein_pickle in result:
self.gene_protein_pickles[g_id] = protein_pickle | [
"def",
"align_orthologous_genes_pairwise",
"(",
"self",
",",
"sc",
"=",
"None",
",",
"joblib",
"=",
"False",
",",
"cores",
"=",
"1",
",",
"gapopen",
"=",
"10",
",",
"gapextend",
"=",
"0.5",
",",
"engine",
"=",
"'needle'",
",",
"parse",
"=",
"True",
","... | Wrapper for _align_orthologous_gene_pairwise | [
"Wrapper",
"for",
"_align_orthologous_gene_pairwise"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas2.py#L585-L636 | train | 29,142 |
SBRG/ssbio | ssbio/protein/sequence/utils/utils.py | cast_to_str | def cast_to_str(obj):
"""Return a string representation of a Seq or SeqRecord.
Args:
obj (str, Seq, SeqRecord): Biopython Seq or SeqRecord
Returns:
str: String representation of the sequence
"""
if isinstance(obj, str):
return obj
if isinstance(obj, Seq):
return str(obj)
if isinstance(obj, SeqRecord):
return str(obj.seq)
else:
raise ValueError('Must provide a string, Seq, or SeqRecord object.') | python | def cast_to_str(obj):
"""Return a string representation of a Seq or SeqRecord.
Args:
obj (str, Seq, SeqRecord): Biopython Seq or SeqRecord
Returns:
str: String representation of the sequence
"""
if isinstance(obj, str):
return obj
if isinstance(obj, Seq):
return str(obj)
if isinstance(obj, SeqRecord):
return str(obj.seq)
else:
raise ValueError('Must provide a string, Seq, or SeqRecord object.') | [
"def",
"cast_to_str",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"return",
"obj",
"if",
"isinstance",
"(",
"obj",
",",
"Seq",
")",
":",
"return",
"str",
"(",
"obj",
")",
"if",
"isinstance",
"(",
"obj",
",",
"SeqReco... | Return a string representation of a Seq or SeqRecord.
Args:
obj (str, Seq, SeqRecord): Biopython Seq or SeqRecord
Returns:
str: String representation of the sequence | [
"Return",
"a",
"string",
"representation",
"of",
"a",
"Seq",
"or",
"SeqRecord",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/utils/utils.py#L6-L24 | train | 29,143 |
SBRG/ssbio | ssbio/protein/sequence/utils/utils.py | cast_to_seq | def cast_to_seq(obj, alphabet=IUPAC.extended_protein):
"""Return a Seq representation of a string or SeqRecord object.
Args:
obj (str, Seq, SeqRecord): Sequence string or Biopython SeqRecord object
alphabet: See Biopython SeqRecord docs
Returns:
Seq: Seq representation of the sequence
"""
if isinstance(obj, Seq):
return obj
if isinstance(obj, SeqRecord):
return obj.seq
if isinstance(obj, str):
obj = obj.upper()
return Seq(obj, alphabet)
else:
raise ValueError('Must provide a string, Seq, or SeqRecord object.') | python | def cast_to_seq(obj, alphabet=IUPAC.extended_protein):
"""Return a Seq representation of a string or SeqRecord object.
Args:
obj (str, Seq, SeqRecord): Sequence string or Biopython SeqRecord object
alphabet: See Biopython SeqRecord docs
Returns:
Seq: Seq representation of the sequence
"""
if isinstance(obj, Seq):
return obj
if isinstance(obj, SeqRecord):
return obj.seq
if isinstance(obj, str):
obj = obj.upper()
return Seq(obj, alphabet)
else:
raise ValueError('Must provide a string, Seq, or SeqRecord object.') | [
"def",
"cast_to_seq",
"(",
"obj",
",",
"alphabet",
"=",
"IUPAC",
".",
"extended_protein",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Seq",
")",
":",
"return",
"obj",
"if",
"isinstance",
"(",
"obj",
",",
"SeqRecord",
")",
":",
"return",
"obj",
".",... | Return a Seq representation of a string or SeqRecord object.
Args:
obj (str, Seq, SeqRecord): Sequence string or Biopython SeqRecord object
alphabet: See Biopython SeqRecord docs
Returns:
Seq: Seq representation of the sequence | [
"Return",
"a",
"Seq",
"representation",
"of",
"a",
"string",
"or",
"SeqRecord",
"object",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/utils/utils.py#L27-L47 | train | 29,144 |
SBRG/ssbio | ssbio/protein/sequence/utils/utils.py | cast_to_seq_record | def cast_to_seq_record(obj, alphabet=IUPAC.extended_protein, id="<unknown id>", name="<unknown name>",
description="<unknown description>", dbxrefs=None,
features=None, annotations=None,
letter_annotations=None):
"""Return a SeqRecord representation of a string or Seq object.
Args:
obj (str, Seq, SeqRecord): Sequence string or Biopython Seq object
alphabet: See Biopython SeqRecord docs
id: See Biopython SeqRecord docs
name: See Biopython SeqRecord docs
description: See Biopython SeqRecord docs
dbxrefs: See Biopython SeqRecord docs
features: See Biopython SeqRecord docs
annotations: See Biopython SeqRecord docs
letter_annotations: See Biopython SeqRecord docs
Returns:
SeqRecord: SeqRecord representation of the sequence
"""
if isinstance(obj, SeqRecord):
return obj
if isinstance(obj, Seq):
return SeqRecord(obj, id, name, description, dbxrefs, features, annotations, letter_annotations)
if isinstance(obj, str):
obj = obj.upper()
return SeqRecord(Seq(obj, alphabet), id, name, description, dbxrefs, features, annotations, letter_annotations)
else:
raise ValueError('Must provide a string, Seq, or SeqRecord object.') | python | def cast_to_seq_record(obj, alphabet=IUPAC.extended_protein, id="<unknown id>", name="<unknown name>",
description="<unknown description>", dbxrefs=None,
features=None, annotations=None,
letter_annotations=None):
"""Return a SeqRecord representation of a string or Seq object.
Args:
obj (str, Seq, SeqRecord): Sequence string or Biopython Seq object
alphabet: See Biopython SeqRecord docs
id: See Biopython SeqRecord docs
name: See Biopython SeqRecord docs
description: See Biopython SeqRecord docs
dbxrefs: See Biopython SeqRecord docs
features: See Biopython SeqRecord docs
annotations: See Biopython SeqRecord docs
letter_annotations: See Biopython SeqRecord docs
Returns:
SeqRecord: SeqRecord representation of the sequence
"""
if isinstance(obj, SeqRecord):
return obj
if isinstance(obj, Seq):
return SeqRecord(obj, id, name, description, dbxrefs, features, annotations, letter_annotations)
if isinstance(obj, str):
obj = obj.upper()
return SeqRecord(Seq(obj, alphabet), id, name, description, dbxrefs, features, annotations, letter_annotations)
else:
raise ValueError('Must provide a string, Seq, or SeqRecord object.') | [
"def",
"cast_to_seq_record",
"(",
"obj",
",",
"alphabet",
"=",
"IUPAC",
".",
"extended_protein",
",",
"id",
"=",
"\"<unknown id>\"",
",",
"name",
"=",
"\"<unknown name>\"",
",",
"description",
"=",
"\"<unknown description>\"",
",",
"dbxrefs",
"=",
"None",
",",
"... | Return a SeqRecord representation of a string or Seq object.
Args:
obj (str, Seq, SeqRecord): Sequence string or Biopython Seq object
alphabet: See Biopython SeqRecord docs
id: See Biopython SeqRecord docs
name: See Biopython SeqRecord docs
description: See Biopython SeqRecord docs
dbxrefs: See Biopython SeqRecord docs
features: See Biopython SeqRecord docs
annotations: See Biopython SeqRecord docs
letter_annotations: See Biopython SeqRecord docs
Returns:
SeqRecord: SeqRecord representation of the sequence | [
"Return",
"a",
"SeqRecord",
"representation",
"of",
"a",
"string",
"or",
"Seq",
"object",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/utils/utils.py#L50-L80 | train | 29,145 |
SBRG/ssbio | ssbio/protein/sequence/utils/fasta.py | write_fasta_file | def write_fasta_file(seq_records, outname, outdir=None, outext='.faa', force_rerun=False):
"""Write a FASTA file for a SeqRecord or a list of SeqRecord objects.
Args:
seq_records (SeqRecord, list): SeqRecord or a list of SeqRecord objects
outname: Name of the output file which will have outext appended to it
outdir: Path to directory to output sequences to
outext: Extension of FASTA file, default ".faa"
force_rerun: If file should be overwritten if it exists
Returns:
str: Path to output FASTA file.
"""
if not outdir:
outdir = ''
outfile = ssbio.utils.outfile_maker(inname='', outname=outname, outdir=outdir, outext=outext)
if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
SeqIO.write(seq_records, outfile, "fasta")
return outfile | python | def write_fasta_file(seq_records, outname, outdir=None, outext='.faa', force_rerun=False):
"""Write a FASTA file for a SeqRecord or a list of SeqRecord objects.
Args:
seq_records (SeqRecord, list): SeqRecord or a list of SeqRecord objects
outname: Name of the output file which will have outext appended to it
outdir: Path to directory to output sequences to
outext: Extension of FASTA file, default ".faa"
force_rerun: If file should be overwritten if it exists
Returns:
str: Path to output FASTA file.
"""
if not outdir:
outdir = ''
outfile = ssbio.utils.outfile_maker(inname='', outname=outname, outdir=outdir, outext=outext)
if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
SeqIO.write(seq_records, outfile, "fasta")
return outfile | [
"def",
"write_fasta_file",
"(",
"seq_records",
",",
"outname",
",",
"outdir",
"=",
"None",
",",
"outext",
"=",
"'.faa'",
",",
"force_rerun",
"=",
"False",
")",
":",
"if",
"not",
"outdir",
":",
"outdir",
"=",
"''",
"outfile",
"=",
"ssbio",
".",
"utils",
... | Write a FASTA file for a SeqRecord or a list of SeqRecord objects.
Args:
seq_records (SeqRecord, list): SeqRecord or a list of SeqRecord objects
outname: Name of the output file which will have outext appended to it
outdir: Path to directory to output sequences to
outext: Extension of FASTA file, default ".faa"
force_rerun: If file should be overwritten if it exists
Returns:
str: Path to output FASTA file. | [
"Write",
"a",
"FASTA",
"file",
"for",
"a",
"SeqRecord",
"or",
"a",
"list",
"of",
"SeqRecord",
"objects",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/utils/fasta.py#L9-L31 | train | 29,146 |
SBRG/ssbio | ssbio/protein/sequence/utils/fasta.py | write_fasta_file_from_dict | def write_fasta_file_from_dict(indict, outname, outdir=None, outext='.faa', force_rerun=False):
"""Write a FASTA file for a dictionary of IDs and their sequence strings.
Args:
indict: Input dictionary with keys as IDs and values as sequence strings
outname: Name of the output file which will have outext appended to it
outdir: Path to directory to output sequences to
outext: Extension of FASTA file, default ".faa"
force_rerun: If file should be overwritten if it exists
Returns:
str: Path to output FASTA file.
"""
if not outdir:
outdir = ''
outfile = ssbio.utils.outfile_maker(inname='', outname=outname, outdir=outdir, outext=outext)
if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
seqs = []
for i, s in indict.items():
seq = ssbio.protein.sequence.utils.cast_to_seq_record(s, id=i)
seqs.append(seq)
SeqIO.write(seqs, outfile, "fasta")
return outfile | python | def write_fasta_file_from_dict(indict, outname, outdir=None, outext='.faa', force_rerun=False):
"""Write a FASTA file for a dictionary of IDs and their sequence strings.
Args:
indict: Input dictionary with keys as IDs and values as sequence strings
outname: Name of the output file which will have outext appended to it
outdir: Path to directory to output sequences to
outext: Extension of FASTA file, default ".faa"
force_rerun: If file should be overwritten if it exists
Returns:
str: Path to output FASTA file.
"""
if not outdir:
outdir = ''
outfile = ssbio.utils.outfile_maker(inname='', outname=outname, outdir=outdir, outext=outext)
if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
seqs = []
for i, s in indict.items():
seq = ssbio.protein.sequence.utils.cast_to_seq_record(s, id=i)
seqs.append(seq)
SeqIO.write(seqs, outfile, "fasta")
return outfile | [
"def",
"write_fasta_file_from_dict",
"(",
"indict",
",",
"outname",
",",
"outdir",
"=",
"None",
",",
"outext",
"=",
"'.faa'",
",",
"force_rerun",
"=",
"False",
")",
":",
"if",
"not",
"outdir",
":",
"outdir",
"=",
"''",
"outfile",
"=",
"ssbio",
".",
"util... | Write a FASTA file for a dictionary of IDs and their sequence strings.
Args:
indict: Input dictionary with keys as IDs and values as sequence strings
outname: Name of the output file which will have outext appended to it
outdir: Path to directory to output sequences to
outext: Extension of FASTA file, default ".faa"
force_rerun: If file should be overwritten if it exists
Returns:
str: Path to output FASTA file. | [
"Write",
"a",
"FASTA",
"file",
"for",
"a",
"dictionary",
"of",
"IDs",
"and",
"their",
"sequence",
"strings",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/utils/fasta.py#L34-L60 | train | 29,147 |
SBRG/ssbio | ssbio/protein/sequence/utils/fasta.py | write_seq_as_temp_fasta | def write_seq_as_temp_fasta(seq):
"""Write a sequence as a temporary FASTA file
Args:
seq (str, Seq, SeqRecord): Sequence string, Biopython Seq or SeqRecord object
Returns:
str: Path to temporary FASTA file (located in system temporary files directory)
"""
sr = ssbio.protein.sequence.utils.cast_to_seq_record(seq, id='tempfasta')
return write_fasta_file(seq_records=sr, outname='temp', outdir=tempfile.gettempdir(), force_rerun=True) | python | def write_seq_as_temp_fasta(seq):
"""Write a sequence as a temporary FASTA file
Args:
seq (str, Seq, SeqRecord): Sequence string, Biopython Seq or SeqRecord object
Returns:
str: Path to temporary FASTA file (located in system temporary files directory)
"""
sr = ssbio.protein.sequence.utils.cast_to_seq_record(seq, id='tempfasta')
return write_fasta_file(seq_records=sr, outname='temp', outdir=tempfile.gettempdir(), force_rerun=True) | [
"def",
"write_seq_as_temp_fasta",
"(",
"seq",
")",
":",
"sr",
"=",
"ssbio",
".",
"protein",
".",
"sequence",
".",
"utils",
".",
"cast_to_seq_record",
"(",
"seq",
",",
"id",
"=",
"'tempfasta'",
")",
"return",
"write_fasta_file",
"(",
"seq_records",
"=",
"sr",... | Write a sequence as a temporary FASTA file
Args:
seq (str, Seq, SeqRecord): Sequence string, Biopython Seq or SeqRecord object
Returns:
str: Path to temporary FASTA file (located in system temporary files directory) | [
"Write",
"a",
"sequence",
"as",
"a",
"temporary",
"FASTA",
"file"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/utils/fasta.py#L63-L74 | train | 29,148 |
SBRG/ssbio | ssbio/protein/sequence/utils/fasta.py | load_fasta_file | def load_fasta_file(filename):
"""Load a FASTA file and return the sequences as a list of SeqRecords
Args:
filename (str): Path to the FASTA file to load
Returns:
list: list of all sequences in the FASTA file as Biopython SeqRecord objects
"""
with open(filename, "r") as handle:
records = list(SeqIO.parse(handle, "fasta"))
return records | python | def load_fasta_file(filename):
"""Load a FASTA file and return the sequences as a list of SeqRecords
Args:
filename (str): Path to the FASTA file to load
Returns:
list: list of all sequences in the FASTA file as Biopython SeqRecord objects
"""
with open(filename, "r") as handle:
records = list(SeqIO.parse(handle, "fasta"))
return records | [
"def",
"load_fasta_file",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"handle",
":",
"records",
"=",
"list",
"(",
"SeqIO",
".",
"parse",
"(",
"handle",
",",
"\"fasta\"",
")",
")",
"return",
"records"
] | Load a FASTA file and return the sequences as a list of SeqRecords
Args:
filename (str): Path to the FASTA file to load
Returns:
list: list of all sequences in the FASTA file as Biopython SeqRecord objects | [
"Load",
"a",
"FASTA",
"file",
"and",
"return",
"the",
"sequences",
"as",
"a",
"list",
"of",
"SeqRecords"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/utils/fasta.py#L77-L90 | train | 29,149 |
SBRG/ssbio | ssbio/protein/sequence/utils/fasta.py | fasta_files_equal | def fasta_files_equal(seq_file1, seq_file2):
"""Check equality of a FASTA file to another FASTA file
Args:
seq_file1: Path to a FASTA file
seq_file2: Path to another FASTA file
Returns:
bool: If the sequences are the same
"""
# Load already set representative sequence
seq1 = SeqIO.read(open(seq_file1), 'fasta')
# Load kegg sequence
seq2 = SeqIO.read(open(seq_file2), 'fasta')
# Test equality
if str(seq1.seq) == str(seq2.seq):
return True
else:
return False | python | def fasta_files_equal(seq_file1, seq_file2):
"""Check equality of a FASTA file to another FASTA file
Args:
seq_file1: Path to a FASTA file
seq_file2: Path to another FASTA file
Returns:
bool: If the sequences are the same
"""
# Load already set representative sequence
seq1 = SeqIO.read(open(seq_file1), 'fasta')
# Load kegg sequence
seq2 = SeqIO.read(open(seq_file2), 'fasta')
# Test equality
if str(seq1.seq) == str(seq2.seq):
return True
else:
return False | [
"def",
"fasta_files_equal",
"(",
"seq_file1",
",",
"seq_file2",
")",
":",
"# Load already set representative sequence",
"seq1",
"=",
"SeqIO",
".",
"read",
"(",
"open",
"(",
"seq_file1",
")",
",",
"'fasta'",
")",
"# Load kegg sequence",
"seq2",
"=",
"SeqIO",
".",
... | Check equality of a FASTA file to another FASTA file
Args:
seq_file1: Path to a FASTA file
seq_file2: Path to another FASTA file
Returns:
bool: If the sequences are the same | [
"Check",
"equality",
"of",
"a",
"FASTA",
"file",
"to",
"another",
"FASTA",
"file"
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/utils/fasta.py#L131-L153 | train | 29,150 |
SBRG/ssbio | ssbio/biopython/Bio/Struct/Protein.py | Protein.from_structure | def from_structure(cls, original, filter_residues):
"""
Loads structure as a protein, exposing
protein-specific methods.
"""
P = cls(original.id)
P.full_id = original.full_id
for child in original.child_dict.values():
copycat = deepcopy(child)
P.add(copycat)
# Discriminate non-residues (is_aa function)
remove_list = []
if filter_residues:
for model in P:
for chain in model:
for residue in chain:
if residue.get_id()[0] != ' ' or not is_aa(residue):
remove_list.append(residue)
for residue in remove_list:
residue.parent.detach_child(residue.id)
for chain in P.get_chains(): # Remove empty chains
if not len(chain.child_list):
model.detach_child(chain.id)
P.header = deepcopy(original.header)
P.xtra = deepcopy(original.xtra)
return P | python | def from_structure(cls, original, filter_residues):
"""
Loads structure as a protein, exposing
protein-specific methods.
"""
P = cls(original.id)
P.full_id = original.full_id
for child in original.child_dict.values():
copycat = deepcopy(child)
P.add(copycat)
# Discriminate non-residues (is_aa function)
remove_list = []
if filter_residues:
for model in P:
for chain in model:
for residue in chain:
if residue.get_id()[0] != ' ' or not is_aa(residue):
remove_list.append(residue)
for residue in remove_list:
residue.parent.detach_child(residue.id)
for chain in P.get_chains(): # Remove empty chains
if not len(chain.child_list):
model.detach_child(chain.id)
P.header = deepcopy(original.header)
P.xtra = deepcopy(original.xtra)
return P | [
"def",
"from_structure",
"(",
"cls",
",",
"original",
",",
"filter_residues",
")",
":",
"P",
"=",
"cls",
"(",
"original",
".",
"id",
")",
"P",
".",
"full_id",
"=",
"original",
".",
"full_id",
"for",
"child",
"in",
"original",
".",
"child_dict",
".",
"v... | Loads structure as a protein, exposing
protein-specific methods. | [
"Loads",
"structure",
"as",
"a",
"protein",
"exposing",
"protein",
"-",
"specific",
"methods",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/biopython/Bio/Struct/Protein.py#L18-L49 | train | 29,151 |
SBRG/ssbio | ssbio/protein/sequence/properties/aggregation_propensity.py | AMYLPRED.get_aggregation_propensity | def get_aggregation_propensity(self, seq, outdir, cutoff_v=5, cutoff_n=5, run_amylmuts=False):
"""Run the AMYLPRED2 web server for a protein sequence and get the consensus result for aggregation propensity.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
outdir (str): Directory to where output files should be saved
cutoff_v (int): The minimal number of methods that agree on a residue being a aggregation-prone residue
cutoff_n (int): The minimal number of consecutive residues to be considered as a 'stretch' of
aggregation-prone region
run_amylmuts (bool): If AMYLMUTS method should be run, default False. AMYLMUTS is optional as it is the most
time consuming and generates a slightly different result every submission.
Returns:
int: Aggregation propensity - the number of aggregation-prone segments on an unfolded protein sequence
"""
seq = ssbio.protein.sequence.utils.cast_to_str(seq)
results = self.run_amylpred2(seq=seq, outdir=outdir, run_amylmuts=run_amylmuts)
agg_index, agg_conf = self.parse_for_consensus_aggregation(N=len(seq), results=results, cutoff_v=cutoff_v, cutoff_n=cutoff_n)
return agg_index | python | def get_aggregation_propensity(self, seq, outdir, cutoff_v=5, cutoff_n=5, run_amylmuts=False):
"""Run the AMYLPRED2 web server for a protein sequence and get the consensus result for aggregation propensity.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
outdir (str): Directory to where output files should be saved
cutoff_v (int): The minimal number of methods that agree on a residue being a aggregation-prone residue
cutoff_n (int): The minimal number of consecutive residues to be considered as a 'stretch' of
aggregation-prone region
run_amylmuts (bool): If AMYLMUTS method should be run, default False. AMYLMUTS is optional as it is the most
time consuming and generates a slightly different result every submission.
Returns:
int: Aggregation propensity - the number of aggregation-prone segments on an unfolded protein sequence
"""
seq = ssbio.protein.sequence.utils.cast_to_str(seq)
results = self.run_amylpred2(seq=seq, outdir=outdir, run_amylmuts=run_amylmuts)
agg_index, agg_conf = self.parse_for_consensus_aggregation(N=len(seq), results=results, cutoff_v=cutoff_v, cutoff_n=cutoff_n)
return agg_index | [
"def",
"get_aggregation_propensity",
"(",
"self",
",",
"seq",
",",
"outdir",
",",
"cutoff_v",
"=",
"5",
",",
"cutoff_n",
"=",
"5",
",",
"run_amylmuts",
"=",
"False",
")",
":",
"seq",
"=",
"ssbio",
".",
"protein",
".",
"sequence",
".",
"utils",
".",
"ca... | Run the AMYLPRED2 web server for a protein sequence and get the consensus result for aggregation propensity.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
outdir (str): Directory to where output files should be saved
cutoff_v (int): The minimal number of methods that agree on a residue being a aggregation-prone residue
cutoff_n (int): The minimal number of consecutive residues to be considered as a 'stretch' of
aggregation-prone region
run_amylmuts (bool): If AMYLMUTS method should be run, default False. AMYLMUTS is optional as it is the most
time consuming and generates a slightly different result every submission.
Returns:
int: Aggregation propensity - the number of aggregation-prone segments on an unfolded protein sequence | [
"Run",
"the",
"AMYLPRED2",
"web",
"server",
"for",
"a",
"protein",
"sequence",
"and",
"get",
"the",
"consensus",
"result",
"for",
"aggregation",
"propensity",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/properties/aggregation_propensity.py#L66-L88 | train | 29,152 |
SBRG/ssbio | ssbio/protein/sequence/properties/aggregation_propensity.py | AMYLPRED.run_amylpred2 | def run_amylpred2(self, seq, outdir, run_amylmuts=False):
"""Run all methods on the AMYLPRED2 web server for an amino acid sequence and gather results.
Result files are cached in ``/path/to/outdir/AMYLPRED2_results``.
Args:
seq (str): Amino acid sequence as a string
outdir (str): Directory to where output files should be saved
run_amylmuts (bool): If AMYLMUTS method should be run, default False
Returns:
dict: Result for each method run
"""
outdir_amylpred = op.join(outdir, 'AMYLPRED2_results')
if not op.exists(outdir_amylpred):
os.mkdir(outdir_amylpred)
url = "http://aias.biol.uoa.gr/AMYLPRED2/login.php"
cj = CookieJar()
opener = build_opener(HTTPCookieProcessor(cj))
formdata = {"email": self.email, "password": self.password}
data_encoded = urlencode(formdata)
data_encoded = data_encoded.encode('ASCII')
response = opener.open(url, data_encoded)
# AMYLMUTS is most time consuming and generates a slightly different result every submission
methods = ['AGGRESCAN', 'NETCSSP', 'PAFIG', 'APD', 'AMYLPATTERN',
'SECSTR', 'BSC', 'WALTZ', 'CONFENERGY', 'TANGO']
if run_amylmuts:
methods.append('AMYLMUTS')
output = {}
timeCounts = 0
for met in methods:
# First check if there is an existing results file
existing_results = glob.glob(op.join(outdir_amylpred, '*_{}.txt'.format(met)))
if existing_results:
results_file = existing_results[0]
else:
values = {'seq_data': seq, 'method': met}
data = urlencode(values)
data = data.encode('ASCII')
url_input = "http://aias.biol.uoa.gr/cgi-bin/AMYLPRED2/amylpred2.pl"
response = opener.open(url_input, data)
result = str(response.read())
ind = str.find(result, 'Job ID')
result2 = result[ind:ind + 50]
ind1 = str.find(result2, ':')
ind2 = str.find(result2, '<BR>')
job_id = result2[ind1 + 2:ind2]
# Waiting for the calculation to complete
url_result = 'http://aias.biol.uoa.gr/AMYLPRED2/tmp/' + job_id + '.txt'
print(url_result)
print("Waiting for %s results" % met, end='.')
while True:
result = urlopen(url_result).read()
if not result:
time.sleep(1)
timeCounts += 1
print('.', end='')
else:
response = requests.get(url_result)
break
results_file = op.join(outdir_amylpred, "{}_{}.txt".format(url_result.split('/')[-1].strip('.txt'), met))
with open(results_file, "wb") as handle:
for data in response.iter_content():
handle.write(data)
print("")
method, hits = self.parse_method_results(results_file, met)
# if method.lower() == met.lower():
output[met] = hits
# elif method == 'Beta-strand contiguity' and met == 'BSC':
# output[met]=hits
# elif method == 'Hexapeptide Conf. Energy' and met == 'CONFENERGY':
if timeCounts != 0:
print("Time spent: %d seconds" % timeCounts)
return output | python | def run_amylpred2(self, seq, outdir, run_amylmuts=False):
"""Run all methods on the AMYLPRED2 web server for an amino acid sequence and gather results.
Result files are cached in ``/path/to/outdir/AMYLPRED2_results``.
Args:
seq (str): Amino acid sequence as a string
outdir (str): Directory to where output files should be saved
run_amylmuts (bool): If AMYLMUTS method should be run, default False
Returns:
dict: Result for each method run
"""
outdir_amylpred = op.join(outdir, 'AMYLPRED2_results')
if not op.exists(outdir_amylpred):
os.mkdir(outdir_amylpred)
url = "http://aias.biol.uoa.gr/AMYLPRED2/login.php"
cj = CookieJar()
opener = build_opener(HTTPCookieProcessor(cj))
formdata = {"email": self.email, "password": self.password}
data_encoded = urlencode(formdata)
data_encoded = data_encoded.encode('ASCII')
response = opener.open(url, data_encoded)
# AMYLMUTS is most time consuming and generates a slightly different result every submission
methods = ['AGGRESCAN', 'NETCSSP', 'PAFIG', 'APD', 'AMYLPATTERN',
'SECSTR', 'BSC', 'WALTZ', 'CONFENERGY', 'TANGO']
if run_amylmuts:
methods.append('AMYLMUTS')
output = {}
timeCounts = 0
for met in methods:
# First check if there is an existing results file
existing_results = glob.glob(op.join(outdir_amylpred, '*_{}.txt'.format(met)))
if existing_results:
results_file = existing_results[0]
else:
values = {'seq_data': seq, 'method': met}
data = urlencode(values)
data = data.encode('ASCII')
url_input = "http://aias.biol.uoa.gr/cgi-bin/AMYLPRED2/amylpred2.pl"
response = opener.open(url_input, data)
result = str(response.read())
ind = str.find(result, 'Job ID')
result2 = result[ind:ind + 50]
ind1 = str.find(result2, ':')
ind2 = str.find(result2, '<BR>')
job_id = result2[ind1 + 2:ind2]
# Waiting for the calculation to complete
url_result = 'http://aias.biol.uoa.gr/AMYLPRED2/tmp/' + job_id + '.txt'
print(url_result)
print("Waiting for %s results" % met, end='.')
while True:
result = urlopen(url_result).read()
if not result:
time.sleep(1)
timeCounts += 1
print('.', end='')
else:
response = requests.get(url_result)
break
results_file = op.join(outdir_amylpred, "{}_{}.txt".format(url_result.split('/')[-1].strip('.txt'), met))
with open(results_file, "wb") as handle:
for data in response.iter_content():
handle.write(data)
print("")
method, hits = self.parse_method_results(results_file, met)
# if method.lower() == met.lower():
output[met] = hits
# elif method == 'Beta-strand contiguity' and met == 'BSC':
# output[met]=hits
# elif method == 'Hexapeptide Conf. Energy' and met == 'CONFENERGY':
if timeCounts != 0:
print("Time spent: %d seconds" % timeCounts)
return output | [
"def",
"run_amylpred2",
"(",
"self",
",",
"seq",
",",
"outdir",
",",
"run_amylmuts",
"=",
"False",
")",
":",
"outdir_amylpred",
"=",
"op",
".",
"join",
"(",
"outdir",
",",
"'AMYLPRED2_results'",
")",
"if",
"not",
"op",
".",
"exists",
"(",
"outdir_amylpred"... | Run all methods on the AMYLPRED2 web server for an amino acid sequence and gather results.
Result files are cached in ``/path/to/outdir/AMYLPRED2_results``.
Args:
seq (str): Amino acid sequence as a string
outdir (str): Directory to where output files should be saved
run_amylmuts (bool): If AMYLMUTS method should be run, default False
Returns:
dict: Result for each method run | [
"Run",
"all",
"methods",
"on",
"the",
"AMYLPRED2",
"web",
"server",
"for",
"an",
"amino",
"acid",
"sequence",
"and",
"gather",
"results",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/properties/aggregation_propensity.py#L90-L171 | train | 29,153 |
SBRG/ssbio | ssbio/protein/sequence/properties/aggregation_propensity.py | AMYLPRED.parse_method_results | def parse_method_results(self, results_file, met):
"""Parse the output of a AMYLPRED2 result file."""
result = str(open(results_file).read())
ind_s = str.find(result, 'HITS')
ind_e = str.find(result, '**NOTE')
tmp = result[ind_s + 10:ind_e].strip(" ")
hits_resid = []
method = None
if ":" in tmp:
method = tmp.split(":")[0]
hits = tmp.split(":")[1]
if "-" in hits:
for ele in hits.split(","):
ele = ele.replace('\\r\\n\\r\\n', '')
res_s = ele.split("-")[0]
res_e = ele.split("-")[1]
for i in range(int(res_s), int(res_e) + 1):
hits_resid.append(i)
if method:
return method, hits_resid
else:
return met, hits_resid | python | def parse_method_results(self, results_file, met):
"""Parse the output of a AMYLPRED2 result file."""
result = str(open(results_file).read())
ind_s = str.find(result, 'HITS')
ind_e = str.find(result, '**NOTE')
tmp = result[ind_s + 10:ind_e].strip(" ")
hits_resid = []
method = None
if ":" in tmp:
method = tmp.split(":")[0]
hits = tmp.split(":")[1]
if "-" in hits:
for ele in hits.split(","):
ele = ele.replace('\\r\\n\\r\\n', '')
res_s = ele.split("-")[0]
res_e = ele.split("-")[1]
for i in range(int(res_s), int(res_e) + 1):
hits_resid.append(i)
if method:
return method, hits_resid
else:
return met, hits_resid | [
"def",
"parse_method_results",
"(",
"self",
",",
"results_file",
",",
"met",
")",
":",
"result",
"=",
"str",
"(",
"open",
"(",
"results_file",
")",
".",
"read",
"(",
")",
")",
"ind_s",
"=",
"str",
".",
"find",
"(",
"result",
",",
"'HITS'",
")",
"ind_... | Parse the output of a AMYLPRED2 result file. | [
"Parse",
"the",
"output",
"of",
"a",
"AMYLPRED2",
"result",
"file",
"."
] | e9449e64ffc1a1f5ad07e5849aa12a650095f8a2 | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/properties/aggregation_propensity.py#L173-L195 | train | 29,154 |
brycedrennan/eulerian-magnification | eulerian_magnification/io.py | _load_video | def _load_video(video_filename):
"""Load a video into a numpy array"""
video_filename = str(video_filename)
print("Loading " + video_filename)
if not os.path.isfile(video_filename):
raise Exception("File Not Found: %s" % video_filename)
# noinspection PyArgumentList
capture = cv2.VideoCapture(video_filename)
frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
width, height = get_capture_dimensions(capture)
fps = int(capture.get(cv2.CAP_PROP_FPS))
x = 0
vid_frames = numpy.zeros((frame_count, height, width, 3), dtype='uint8')
while capture.isOpened():
ret, frame = capture.read()
if not ret:
break
vid_frames[x] = frame
x += 1
capture.release()
return vid_frames, fps | python | def _load_video(video_filename):
"""Load a video into a numpy array"""
video_filename = str(video_filename)
print("Loading " + video_filename)
if not os.path.isfile(video_filename):
raise Exception("File Not Found: %s" % video_filename)
# noinspection PyArgumentList
capture = cv2.VideoCapture(video_filename)
frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
width, height = get_capture_dimensions(capture)
fps = int(capture.get(cv2.CAP_PROP_FPS))
x = 0
vid_frames = numpy.zeros((frame_count, height, width, 3), dtype='uint8')
while capture.isOpened():
ret, frame = capture.read()
if not ret:
break
vid_frames[x] = frame
x += 1
capture.release()
return vid_frames, fps | [
"def",
"_load_video",
"(",
"video_filename",
")",
":",
"video_filename",
"=",
"str",
"(",
"video_filename",
")",
"print",
"(",
"\"Loading \"",
"+",
"video_filename",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"video_filename",
")",
":",
"raise"... | Load a video into a numpy array | [
"Load",
"a",
"video",
"into",
"a",
"numpy",
"array"
] | 9ae0651fe3334176300d183f8240ad36d77759a9 | https://github.com/brycedrennan/eulerian-magnification/blob/9ae0651fe3334176300d183f8240ad36d77759a9/eulerian_magnification/io.py#L15-L37 | train | 29,155 |
brycedrennan/eulerian-magnification | eulerian_magnification/io.py | get_capture_dimensions | def get_capture_dimensions(capture):
"""Get the dimensions of a capture"""
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
return width, height | python | def get_capture_dimensions(capture):
"""Get the dimensions of a capture"""
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
return width, height | [
"def",
"get_capture_dimensions",
"(",
"capture",
")",
":",
"width",
"=",
"int",
"(",
"capture",
".",
"get",
"(",
"cv2",
".",
"CAP_PROP_FRAME_WIDTH",
")",
")",
"height",
"=",
"int",
"(",
"capture",
".",
"get",
"(",
"cv2",
".",
"CAP_PROP_FRAME_HEIGHT",
")",
... | Get the dimensions of a capture | [
"Get",
"the",
"dimensions",
"of",
"a",
"capture"
] | 9ae0651fe3334176300d183f8240ad36d77759a9 | https://github.com/brycedrennan/eulerian-magnification/blob/9ae0651fe3334176300d183f8240ad36d77759a9/eulerian_magnification/io.py#L45-L49 | train | 29,156 |
brycedrennan/eulerian-magnification | eulerian_magnification/io.py | save_video | def save_video(video, fps, save_filename='media/output.avi'):
"""Save a video to disk"""
# fourcc = cv2.CAP_PROP_FOURCC('M', 'J', 'P', 'G')
print(save_filename)
video = float_to_uint8(video)
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
writer = cv2.VideoWriter(save_filename, fourcc, fps, (video.shape[2], video.shape[1]), 1)
for x in range(0, video.shape[0]):
res = cv2.convertScaleAbs(video[x])
writer.write(res) | python | def save_video(video, fps, save_filename='media/output.avi'):
"""Save a video to disk"""
# fourcc = cv2.CAP_PROP_FOURCC('M', 'J', 'P', 'G')
print(save_filename)
video = float_to_uint8(video)
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
writer = cv2.VideoWriter(save_filename, fourcc, fps, (video.shape[2], video.shape[1]), 1)
for x in range(0, video.shape[0]):
res = cv2.convertScaleAbs(video[x])
writer.write(res) | [
"def",
"save_video",
"(",
"video",
",",
"fps",
",",
"save_filename",
"=",
"'media/output.avi'",
")",
":",
"# fourcc = cv2.CAP_PROP_FOURCC('M', 'J', 'P', 'G')",
"print",
"(",
"save_filename",
")",
"video",
"=",
"float_to_uint8",
"(",
"video",
")",
"fourcc",
"=",
"cv2... | Save a video to disk | [
"Save",
"a",
"video",
"to",
"disk"
] | 9ae0651fe3334176300d183f8240ad36d77759a9 | https://github.com/brycedrennan/eulerian-magnification/blob/9ae0651fe3334176300d183f8240ad36d77759a9/eulerian_magnification/io.py#L74-L83 | train | 29,157 |
brycedrennan/eulerian-magnification | eulerian_magnification/base.py | show_frequencies | def show_frequencies(vid_data, fps, bounds=None):
"""Graph the average value of the video as well as the frequency strength"""
averages = []
if bounds:
for x in range(1, vid_data.shape[0] - 1):
averages.append(vid_data[x, bounds[2]:bounds[3], bounds[0]:bounds[1], :].sum())
else:
for x in range(1, vid_data.shape[0] - 1):
averages.append(vid_data[x, :, :, :].sum())
averages = averages - min(averages)
charts_x = 1
charts_y = 2
pyplot.figure(figsize=(20, 10))
pyplot.subplots_adjust(hspace=.7)
pyplot.subplot(charts_y, charts_x, 1)
pyplot.title("Pixel Average")
pyplot.xlabel("Time")
pyplot.ylabel("Brightness")
pyplot.plot(averages)
freqs = scipy.fftpack.fftfreq(len(averages), d=1.0 / fps)
fft = abs(scipy.fftpack.fft(averages))
idx = np.argsort(freqs)
pyplot.subplot(charts_y, charts_x, 2)
pyplot.title("FFT")
pyplot.xlabel("Freq (Hz)")
freqs = freqs[idx]
fft = fft[idx]
freqs = freqs[len(freqs) // 2 + 1:]
fft = fft[len(fft) // 2 + 1:]
pyplot.plot(freqs, abs(fft))
pyplot.show() | python | def show_frequencies(vid_data, fps, bounds=None):
"""Graph the average value of the video as well as the frequency strength"""
averages = []
if bounds:
for x in range(1, vid_data.shape[0] - 1):
averages.append(vid_data[x, bounds[2]:bounds[3], bounds[0]:bounds[1], :].sum())
else:
for x in range(1, vid_data.shape[0] - 1):
averages.append(vid_data[x, :, :, :].sum())
averages = averages - min(averages)
charts_x = 1
charts_y = 2
pyplot.figure(figsize=(20, 10))
pyplot.subplots_adjust(hspace=.7)
pyplot.subplot(charts_y, charts_x, 1)
pyplot.title("Pixel Average")
pyplot.xlabel("Time")
pyplot.ylabel("Brightness")
pyplot.plot(averages)
freqs = scipy.fftpack.fftfreq(len(averages), d=1.0 / fps)
fft = abs(scipy.fftpack.fft(averages))
idx = np.argsort(freqs)
pyplot.subplot(charts_y, charts_x, 2)
pyplot.title("FFT")
pyplot.xlabel("Freq (Hz)")
freqs = freqs[idx]
fft = fft[idx]
freqs = freqs[len(freqs) // 2 + 1:]
fft = fft[len(fft) // 2 + 1:]
pyplot.plot(freqs, abs(fft))
pyplot.show() | [
"def",
"show_frequencies",
"(",
"vid_data",
",",
"fps",
",",
"bounds",
"=",
"None",
")",
":",
"averages",
"=",
"[",
"]",
"if",
"bounds",
":",
"for",
"x",
"in",
"range",
"(",
"1",
",",
"vid_data",
".",
"shape",
"[",
"0",
"]",
"-",
"1",
")",
":",
... | Graph the average value of the video as well as the frequency strength | [
"Graph",
"the",
"average",
"value",
"of",
"the",
"video",
"as",
"well",
"as",
"the",
"frequency",
"strength"
] | 9ae0651fe3334176300d183f8240ad36d77759a9 | https://github.com/brycedrennan/eulerian-magnification/blob/9ae0651fe3334176300d183f8240ad36d77759a9/eulerian_magnification/base.py#L31-L69 | train | 29,158 |
brycedrennan/eulerian-magnification | eulerian_magnification/base.py | gaussian_video | def gaussian_video(video, shrink_multiple):
"""Create a gaussian representation of a video"""
vid_data = None
for x in range(0, video.shape[0]):
frame = video[x]
gauss_copy = np.ndarray(shape=frame.shape, dtype="float")
gauss_copy[:] = frame
for i in range(shrink_multiple):
gauss_copy = cv2.pyrDown(gauss_copy)
if x == 0:
vid_data = np.zeros((video.shape[0], gauss_copy.shape[0], gauss_copy.shape[1], 3))
vid_data[x] = gauss_copy
return vid_data | python | def gaussian_video(video, shrink_multiple):
"""Create a gaussian representation of a video"""
vid_data = None
for x in range(0, video.shape[0]):
frame = video[x]
gauss_copy = np.ndarray(shape=frame.shape, dtype="float")
gauss_copy[:] = frame
for i in range(shrink_multiple):
gauss_copy = cv2.pyrDown(gauss_copy)
if x == 0:
vid_data = np.zeros((video.shape[0], gauss_copy.shape[0], gauss_copy.shape[1], 3))
vid_data[x] = gauss_copy
return vid_data | [
"def",
"gaussian_video",
"(",
"video",
",",
"shrink_multiple",
")",
":",
"vid_data",
"=",
"None",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"video",
".",
"shape",
"[",
"0",
"]",
")",
":",
"frame",
"=",
"video",
"[",
"x",
"]",
"gauss_copy",
"=",
"np... | Create a gaussian representation of a video | [
"Create",
"a",
"gaussian",
"representation",
"of",
"a",
"video"
] | 9ae0651fe3334176300d183f8240ad36d77759a9 | https://github.com/brycedrennan/eulerian-magnification/blob/9ae0651fe3334176300d183f8240ad36d77759a9/eulerian_magnification/base.py#L72-L85 | train | 29,159 |
brycedrennan/eulerian-magnification | eulerian_magnification/base.py | combine_pyramid_and_save | def combine_pyramid_and_save(g_video, orig_video, enlarge_multiple, fps, save_filename='media/output.avi'):
"""Combine a gaussian video representation with the original and save to file"""
width, height = get_frame_dimensions(orig_video[0])
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
print("Outputting to %s" % save_filename)
writer = cv2.VideoWriter(save_filename, fourcc, fps, (width, height), 1)
for x in range(0, g_video.shape[0]):
img = np.ndarray(shape=g_video[x].shape, dtype='float')
img[:] = g_video[x]
for i in range(enlarge_multiple):
img = cv2.pyrUp(img)
img[:height, :width] = img[:height, :width] + orig_video[x]
res = cv2.convertScaleAbs(img[:height, :width])
writer.write(res) | python | def combine_pyramid_and_save(g_video, orig_video, enlarge_multiple, fps, save_filename='media/output.avi'):
"""Combine a gaussian video representation with the original and save to file"""
width, height = get_frame_dimensions(orig_video[0])
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
print("Outputting to %s" % save_filename)
writer = cv2.VideoWriter(save_filename, fourcc, fps, (width, height), 1)
for x in range(0, g_video.shape[0]):
img = np.ndarray(shape=g_video[x].shape, dtype='float')
img[:] = g_video[x]
for i in range(enlarge_multiple):
img = cv2.pyrUp(img)
img[:height, :width] = img[:height, :width] + orig_video[x]
res = cv2.convertScaleAbs(img[:height, :width])
writer.write(res) | [
"def",
"combine_pyramid_and_save",
"(",
"g_video",
",",
"orig_video",
",",
"enlarge_multiple",
",",
"fps",
",",
"save_filename",
"=",
"'media/output.avi'",
")",
":",
"width",
",",
"height",
"=",
"get_frame_dimensions",
"(",
"orig_video",
"[",
"0",
"]",
")",
"fou... | Combine a gaussian video representation with the original and save to file | [
"Combine",
"a",
"gaussian",
"video",
"representation",
"with",
"the",
"original",
"and",
"save",
"to",
"file"
] | 9ae0651fe3334176300d183f8240ad36d77759a9 | https://github.com/brycedrennan/eulerian-magnification/blob/9ae0651fe3334176300d183f8240ad36d77759a9/eulerian_magnification/base.py#L108-L122 | train | 29,160 |
textmagic/textmagic-rest-python | textmagic/rest/models/messages.py | Messages.price | def price(self, from_=None, **kwargs):
"""
Check pricing for a new outbound message.
An useful synonym for "message" command with "dummy" parameters set to true.
:Example:
message = client.messages.price(from_="447624800500", phones="999000001", text="Hello!", lists="1909100")
:param str from: One of allowed Sender ID (phone number or alphanumeric sender ID).
:param str text: Message text. Required if templateId is not set.
:param str templateId: Template used instead of message text. Required if text is not set.
:param str sendingTime: Message sending time in unix timestamp format. Default is now.
Optional (required with rrule set).
:param str contacts: Contacts ids, separated by comma, message will be sent to.
:param str lists: Lists ids, separated by comma, message will be sent to.
:param str phones: Phone numbers, separated by comma, message will be sent to.
:param int cutExtra: Should sending method cut extra characters
which not fit supplied partsCount or return 400 Bad request response instead.
Default is false.
:param int partsCount: Maximum message parts count (TextMagic allows sending 1 to 6 message parts).
Default is 6.
:param str referenceId: Custom message reference id which can be used in your application infrastructure.
:param str rrule: iCal RRULE parameter to create recurrent scheduled messages.
When used, sendingTime is mandatory as start point of sending.
:param int dummy: If 1, just return message pricing. Message will not send.
"""
if from_:
kwargs["from"] = from_
uri = "%s/%s" % (self.uri, "price")
response, instance = self.request("GET", uri, params=kwargs)
return instance | python | def price(self, from_=None, **kwargs):
"""
Check pricing for a new outbound message.
An useful synonym for "message" command with "dummy" parameters set to true.
:Example:
message = client.messages.price(from_="447624800500", phones="999000001", text="Hello!", lists="1909100")
:param str from: One of allowed Sender ID (phone number or alphanumeric sender ID).
:param str text: Message text. Required if templateId is not set.
:param str templateId: Template used instead of message text. Required if text is not set.
:param str sendingTime: Message sending time in unix timestamp format. Default is now.
Optional (required with rrule set).
:param str contacts: Contacts ids, separated by comma, message will be sent to.
:param str lists: Lists ids, separated by comma, message will be sent to.
:param str phones: Phone numbers, separated by comma, message will be sent to.
:param int cutExtra: Should sending method cut extra characters
which not fit supplied partsCount or return 400 Bad request response instead.
Default is false.
:param int partsCount: Maximum message parts count (TextMagic allows sending 1 to 6 message parts).
Default is 6.
:param str referenceId: Custom message reference id which can be used in your application infrastructure.
:param str rrule: iCal RRULE parameter to create recurrent scheduled messages.
When used, sendingTime is mandatory as start point of sending.
:param int dummy: If 1, just return message pricing. Message will not send.
"""
if from_:
kwargs["from"] = from_
uri = "%s/%s" % (self.uri, "price")
response, instance = self.request("GET", uri, params=kwargs)
return instance | [
"def",
"price",
"(",
"self",
",",
"from_",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"from_",
":",
"kwargs",
"[",
"\"from\"",
"]",
"=",
"from_",
"uri",
"=",
"\"%s/%s\"",
"%",
"(",
"self",
".",
"uri",
",",
"\"price\"",
")",
"response",
... | Check pricing for a new outbound message.
An useful synonym for "message" command with "dummy" parameters set to true.
:Example:
message = client.messages.price(from_="447624800500", phones="999000001", text="Hello!", lists="1909100")
:param str from: One of allowed Sender ID (phone number or alphanumeric sender ID).
:param str text: Message text. Required if templateId is not set.
:param str templateId: Template used instead of message text. Required if text is not set.
:param str sendingTime: Message sending time in unix timestamp format. Default is now.
Optional (required with rrule set).
:param str contacts: Contacts ids, separated by comma, message will be sent to.
:param str lists: Lists ids, separated by comma, message will be sent to.
:param str phones: Phone numbers, separated by comma, message will be sent to.
:param int cutExtra: Should sending method cut extra characters
which not fit supplied partsCount or return 400 Bad request response instead.
Default is false.
:param int partsCount: Maximum message parts count (TextMagic allows sending 1 to 6 message parts).
Default is 6.
:param str referenceId: Custom message reference id which can be used in your application infrastructure.
:param str rrule: iCal RRULE parameter to create recurrent scheduled messages.
When used, sendingTime is mandatory as start point of sending.
:param int dummy: If 1, just return message pricing. Message will not send. | [
"Check",
"pricing",
"for",
"a",
"new",
"outbound",
"message",
".",
"An",
"useful",
"synonym",
"for",
"message",
"command",
"with",
"dummy",
"parameters",
"set",
"to",
"true",
"."
] | 15d679cb985b88b1cb2153ef2ba80d9749f9e281 | https://github.com/textmagic/textmagic-rest-python/blob/15d679cb985b88b1cb2153ef2ba80d9749f9e281/textmagic/rest/models/messages.py#L93-L124 | train | 29,161 |
textmagic/textmagic-rest-python | textmagic/rest/models/tokens.py | Tokens.refresh | def refresh(self):
"""
Refresh access token. Only non-expired tokens can be renewed.
:Example:
token = client.tokens.refresh()
"""
uri = "%s/%s" % (self.uri, "refresh")
response, instance = self.request("GET", uri)
return response.ok | python | def refresh(self):
"""
Refresh access token. Only non-expired tokens can be renewed.
:Example:
token = client.tokens.refresh()
"""
uri = "%s/%s" % (self.uri, "refresh")
response, instance = self.request("GET", uri)
return response.ok | [
"def",
"refresh",
"(",
"self",
")",
":",
"uri",
"=",
"\"%s/%s\"",
"%",
"(",
"self",
".",
"uri",
",",
"\"refresh\"",
")",
"response",
",",
"instance",
"=",
"self",
".",
"request",
"(",
"\"GET\"",
",",
"uri",
")",
"return",
"response",
".",
"ok"
] | Refresh access token. Only non-expired tokens can be renewed.
:Example:
token = client.tokens.refresh() | [
"Refresh",
"access",
"token",
".",
"Only",
"non",
"-",
"expired",
"tokens",
"can",
"be",
"renewed",
"."
] | 15d679cb985b88b1cb2153ef2ba80d9749f9e281 | https://github.com/textmagic/textmagic-rest-python/blob/15d679cb985b88b1cb2153ef2ba80d9749f9e281/textmagic/rest/models/tokens.py#L38-L48 | train | 29,162 |
textmagic/textmagic-rest-python | textmagic/rest/models/user.py | Users.update | def update(self, **kwargs):
"""
Update an current User via a PUT request.
Returns True if success.
:Example:
client.user.update(firstName="John", lastName="Doe", company="TextMagic")
:param str firstName: User first name. Required.
:param str lastName: User last name. Required.
:param str company: User company. Required.
"""
response, instance = self.request("PUT", self.uri, data=kwargs)
return response.status == 201 | python | def update(self, **kwargs):
"""
Update an current User via a PUT request.
Returns True if success.
:Example:
client.user.update(firstName="John", lastName="Doe", company="TextMagic")
:param str firstName: User first name. Required.
:param str lastName: User last name. Required.
:param str company: User company. Required.
"""
response, instance = self.request("PUT", self.uri, data=kwargs)
return response.status == 201 | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
",",
"instance",
"=",
"self",
".",
"request",
"(",
"\"PUT\"",
",",
"self",
".",
"uri",
",",
"data",
"=",
"kwargs",
")",
"return",
"response",
".",
"status",
"==",
"201"
] | Update an current User via a PUT request.
Returns True if success.
:Example:
client.user.update(firstName="John", lastName="Doe", company="TextMagic")
:param str firstName: User first name. Required.
:param str lastName: User last name. Required.
:param str company: User company. Required. | [
"Update",
"an",
"current",
"User",
"via",
"a",
"PUT",
"request",
".",
"Returns",
"True",
"if",
"success",
"."
] | 15d679cb985b88b1cb2153ef2ba80d9749f9e281 | https://github.com/textmagic/textmagic-rest-python/blob/15d679cb985b88b1cb2153ef2ba80d9749f9e281/textmagic/rest/models/user.py#L61-L75 | train | 29,163 |
textmagic/textmagic-rest-python | textmagic/rest/models/user.py | Subaccounts.send_invite | def send_invite(self, **kwargs):
"""
Invite new subaccount.
Returns True if success.
:Example:
s = client.subaccounts.create(email="johndoe@yahoo.com", role="A")
:param str email: Subaccount email. Required.
:param str role: Subaccount role: `A` for administrator or `U` for regular user. Required.
"""
resp, _ = self.request("POST", self.uri, data=kwargs)
return resp.status == 204 | python | def send_invite(self, **kwargs):
"""
Invite new subaccount.
Returns True if success.
:Example:
s = client.subaccounts.create(email="johndoe@yahoo.com", role="A")
:param str email: Subaccount email. Required.
:param str role: Subaccount role: `A` for administrator or `U` for regular user. Required.
"""
resp, _ = self.request("POST", self.uri, data=kwargs)
return resp.status == 204 | [
"def",
"send_invite",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"resp",
",",
"_",
"=",
"self",
".",
"request",
"(",
"\"POST\"",
",",
"self",
".",
"uri",
",",
"data",
"=",
"kwargs",
")",
"return",
"resp",
".",
"status",
"==",
"204"
] | Invite new subaccount.
Returns True if success.
:Example:
s = client.subaccounts.create(email="johndoe@yahoo.com", role="A")
:param str email: Subaccount email. Required.
:param str role: Subaccount role: `A` for administrator or `U` for regular user. Required. | [
"Invite",
"new",
"subaccount",
".",
"Returns",
"True",
"if",
"success",
"."
] | 15d679cb985b88b1cb2153ef2ba80d9749f9e281 | https://github.com/textmagic/textmagic-rest-python/blob/15d679cb985b88b1cb2153ef2ba80d9749f9e281/textmagic/rest/models/user.py#L97-L110 | train | 29,164 |
textmagic/textmagic-rest-python | textmagic/rest/models/chats.py | Chats.by_phone | def by_phone(self, phone, **kwargs):
"""
Fetch messages from chat with specified phone number.
:Example:
chat = client.chats.by_phone(phone="447624800500")
:param str phone: Phone number in E.164 format.
:param int page: Fetch specified results page. Default=1
:param int limit: How many results on page. Default=10
"""
chat_messages = ChatMessages(self.base_uri, self.auth)
return self.get_subresource_instances(uid=phone, instance=chat_messages, params=kwargs) | python | def by_phone(self, phone, **kwargs):
"""
Fetch messages from chat with specified phone number.
:Example:
chat = client.chats.by_phone(phone="447624800500")
:param str phone: Phone number in E.164 format.
:param int page: Fetch specified results page. Default=1
:param int limit: How many results on page. Default=10
"""
chat_messages = ChatMessages(self.base_uri, self.auth)
return self.get_subresource_instances(uid=phone, instance=chat_messages, params=kwargs) | [
"def",
"by_phone",
"(",
"self",
",",
"phone",
",",
"*",
"*",
"kwargs",
")",
":",
"chat_messages",
"=",
"ChatMessages",
"(",
"self",
".",
"base_uri",
",",
"self",
".",
"auth",
")",
"return",
"self",
".",
"get_subresource_instances",
"(",
"uid",
"=",
"phon... | Fetch messages from chat with specified phone number.
:Example:
chat = client.chats.by_phone(phone="447624800500")
:param str phone: Phone number in E.164 format.
:param int page: Fetch specified results page. Default=1
:param int limit: How many results on page. Default=10 | [
"Fetch",
"messages",
"from",
"chat",
"with",
"specified",
"phone",
"number",
"."
] | 15d679cb985b88b1cb2153ef2ba80d9749f9e281 | https://github.com/textmagic/textmagic-rest-python/blob/15d679cb985b88b1cb2153ef2ba80d9749f9e281/textmagic/rest/models/chats.py#L98-L111 | train | 29,165 |
textmagic/textmagic-rest-python | textmagic/rest/client.py | get_credentials | def get_credentials(env=None):
"""
Gets the TextMagic credentials from current environment
:param env: environment
:return: username, token
"""
environ = env or os.environ
try:
username = environ["TEXTMAGIC_USERNAME"]
token = environ["TEXTMAGIC_AUTH_TOKEN"]
return username, token
except KeyError:
return None, None | python | def get_credentials(env=None):
"""
Gets the TextMagic credentials from current environment
:param env: environment
:return: username, token
"""
environ = env or os.environ
try:
username = environ["TEXTMAGIC_USERNAME"]
token = environ["TEXTMAGIC_AUTH_TOKEN"]
return username, token
except KeyError:
return None, None | [
"def",
"get_credentials",
"(",
"env",
"=",
"None",
")",
":",
"environ",
"=",
"env",
"or",
"os",
".",
"environ",
"try",
":",
"username",
"=",
"environ",
"[",
"\"TEXTMAGIC_USERNAME\"",
"]",
"token",
"=",
"environ",
"[",
"\"TEXTMAGIC_AUTH_TOKEN\"",
"]",
"return... | Gets the TextMagic credentials from current environment
:param env: environment
:return: username, token | [
"Gets",
"the",
"TextMagic",
"credentials",
"from",
"current",
"environment"
] | 15d679cb985b88b1cb2153ef2ba80d9749f9e281 | https://github.com/textmagic/textmagic-rest-python/blob/15d679cb985b88b1cb2153ef2ba80d9749f9e281/textmagic/rest/client.py#L52-L65 | train | 29,166 |
textmagic/textmagic-rest-python | textmagic/rest/models/contacts.py | Lists.put_contacts | def put_contacts(self, uid, **kwargs):
"""
Assign contacts to the specified list.
:Example:
client.lists.put_contacts(uid=1901010, contacts="1723812,1239912")
:param int uid: The unique id of the List. Required.
:param str contacts: Contact ID(s), separated by comma. Required.
"""
return self.update_subresource_instance(uid,
body=kwargs,
subresource=None,
slug="contacts") | python | def put_contacts(self, uid, **kwargs):
"""
Assign contacts to the specified list.
:Example:
client.lists.put_contacts(uid=1901010, contacts="1723812,1239912")
:param int uid: The unique id of the List. Required.
:param str contacts: Contact ID(s), separated by comma. Required.
"""
return self.update_subresource_instance(uid,
body=kwargs,
subresource=None,
slug="contacts") | [
"def",
"put_contacts",
"(",
"self",
",",
"uid",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"update_subresource_instance",
"(",
"uid",
",",
"body",
"=",
"kwargs",
",",
"subresource",
"=",
"None",
",",
"slug",
"=",
"\"contacts\"",
")"
] | Assign contacts to the specified list.
:Example:
client.lists.put_contacts(uid=1901010, contacts="1723812,1239912")
:param int uid: The unique id of the List. Required.
:param str contacts: Contact ID(s), separated by comma. Required. | [
"Assign",
"contacts",
"to",
"the",
"specified",
"list",
"."
] | 15d679cb985b88b1cb2153ef2ba80d9749f9e281 | https://github.com/textmagic/textmagic-rest-python/blob/15d679cb985b88b1cb2153ef2ba80d9749f9e281/textmagic/rest/models/contacts.py#L231-L245 | train | 29,167 |
textmagic/textmagic-rest-python | textmagic/rest/models/contacts.py | Lists.delete_contacts | def delete_contacts(self, uid, **kwargs):
"""
Unassign contacts from the specified list.
If contacts assign only to the specified list, then delete permanently.
Returns True if success.
:Example:
client.lists.delete_contacts(uid=1901010, contacts="1723812,1239912")
:param int uid: The unique id of the List. Required.
:param str contacts: Contact ID(s), separated by comma. Required.
"""
uri = "%s/%s/contacts" % (self.uri, uid)
response, instance = self.request("DELETE", uri, data=kwargs)
return response.status == 204 | python | def delete_contacts(self, uid, **kwargs):
"""
Unassign contacts from the specified list.
If contacts assign only to the specified list, then delete permanently.
Returns True if success.
:Example:
client.lists.delete_contacts(uid=1901010, contacts="1723812,1239912")
:param int uid: The unique id of the List. Required.
:param str contacts: Contact ID(s), separated by comma. Required.
"""
uri = "%s/%s/contacts" % (self.uri, uid)
response, instance = self.request("DELETE", uri, data=kwargs)
return response.status == 204 | [
"def",
"delete_contacts",
"(",
"self",
",",
"uid",
",",
"*",
"*",
"kwargs",
")",
":",
"uri",
"=",
"\"%s/%s/contacts\"",
"%",
"(",
"self",
".",
"uri",
",",
"uid",
")",
"response",
",",
"instance",
"=",
"self",
".",
"request",
"(",
"\"DELETE\"",
",",
"... | Unassign contacts from the specified list.
If contacts assign only to the specified list, then delete permanently.
Returns True if success.
:Example:
client.lists.delete_contacts(uid=1901010, contacts="1723812,1239912")
:param int uid: The unique id of the List. Required.
:param str contacts: Contact ID(s), separated by comma. Required. | [
"Unassign",
"contacts",
"from",
"the",
"specified",
"list",
".",
"If",
"contacts",
"assign",
"only",
"to",
"the",
"specified",
"list",
"then",
"delete",
"permanently",
".",
"Returns",
"True",
"if",
"success",
"."
] | 15d679cb985b88b1cb2153ef2ba80d9749f9e281 | https://github.com/textmagic/textmagic-rest-python/blob/15d679cb985b88b1cb2153ef2ba80d9749f9e281/textmagic/rest/models/contacts.py#L247-L262 | train | 29,168 |
textmagic/textmagic-rest-python | textmagic/rest/models/base.py | get_cert_file | def get_cert_file():
""" Get the certificates file for https"""
try:
current_path = os.path.realpath(__file__)
ca_cert_path = os.path.join(current_path, "..", "..", "..",
"conf", "cacert.pem")
return os.path.abspath(ca_cert_path)
except Exception:
return None | python | def get_cert_file():
""" Get the certificates file for https"""
try:
current_path = os.path.realpath(__file__)
ca_cert_path = os.path.join(current_path, "..", "..", "..",
"conf", "cacert.pem")
return os.path.abspath(ca_cert_path)
except Exception:
return None | [
"def",
"get_cert_file",
"(",
")",
":",
"try",
":",
"current_path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
"ca_cert_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"current_path",
",",
"\"..\"",
",",
"\"..\"",
",",
"\"..\"",
","... | Get the certificates file for https | [
"Get",
"the",
"certificates",
"file",
"for",
"https"
] | 15d679cb985b88b1cb2153ef2ba80d9749f9e281 | https://github.com/textmagic/textmagic-rest-python/blob/15d679cb985b88b1cb2153ef2ba80d9749f9e281/textmagic/rest/models/base.py#L25-L33 | train | 29,169 |
textmagic/textmagic-rest-python | textmagic/rest/models/base.py | make_tm_request | def make_tm_request(method, uri, **kwargs):
"""
Make a request to TextMagic REST APIv2.
:param str method: "POST", "GET", "PUT" or "DELETE"
:param str uri: URI to process request.
:return: :class:`Response`
"""
headers = kwargs.get("headers", {})
user_agent = "textmagic-python/%s (Python %s)" % (
__version__,
platform.python_version()
)
headers["User-agent"] = user_agent
headers["Accept-Charset"] = "utf-8"
if "Accept-Language" not in headers:
headers["Accept-Language"] = "en-us"
if (method == "POST" or method == "PUT") and "Content-Type" not in headers:
headers["Content-Type"] = "application/x-www-form-urlencoded"
kwargs["headers"] = headers
if "Accept" not in headers:
headers["Accept"] = "application/json"
headers["X-TM-Username"], headers["X-TM-Key"] = kwargs["auth"]
response = make_request(method, uri, **kwargs)
if not response.ok:
try:
resp_body = json.loads(response.content)
message = resp_body["message"]
errors = resp_body["errors"]
except:
message = response.content
errors = None
raise TextmagicRestException(status=response.status, method=method, uri=response.url,
msg=message, errors=errors)
return response | python | def make_tm_request(method, uri, **kwargs):
"""
Make a request to TextMagic REST APIv2.
:param str method: "POST", "GET", "PUT" or "DELETE"
:param str uri: URI to process request.
:return: :class:`Response`
"""
headers = kwargs.get("headers", {})
user_agent = "textmagic-python/%s (Python %s)" % (
__version__,
platform.python_version()
)
headers["User-agent"] = user_agent
headers["Accept-Charset"] = "utf-8"
if "Accept-Language" not in headers:
headers["Accept-Language"] = "en-us"
if (method == "POST" or method == "PUT") and "Content-Type" not in headers:
headers["Content-Type"] = "application/x-www-form-urlencoded"
kwargs["headers"] = headers
if "Accept" not in headers:
headers["Accept"] = "application/json"
headers["X-TM-Username"], headers["X-TM-Key"] = kwargs["auth"]
response = make_request(method, uri, **kwargs)
if not response.ok:
try:
resp_body = json.loads(response.content)
message = resp_body["message"]
errors = resp_body["errors"]
except:
message = response.content
errors = None
raise TextmagicRestException(status=response.status, method=method, uri=response.url,
msg=message, errors=errors)
return response | [
"def",
"make_tm_request",
"(",
"method",
",",
"uri",
",",
"*",
"*",
"kwargs",
")",
":",
"headers",
"=",
"kwargs",
".",
"get",
"(",
"\"headers\"",
",",
"{",
"}",
")",
"user_agent",
"=",
"\"textmagic-python/%s (Python %s)\"",
"%",
"(",
"__version__",
",",
"p... | Make a request to TextMagic REST APIv2.
:param str method: "POST", "GET", "PUT" or "DELETE"
:param str uri: URI to process request.
:return: :class:`Response` | [
"Make",
"a",
"request",
"to",
"TextMagic",
"REST",
"APIv2",
"."
] | 15d679cb985b88b1cb2153ef2ba80d9749f9e281 | https://github.com/textmagic/textmagic-rest-python/blob/15d679cb985b88b1cb2153ef2ba80d9749f9e281/textmagic/rest/models/base.py#L92-L135 | train | 29,170 |
textmagic/textmagic-rest-python | textmagic/rest/models/base.py | CollectionModel.update_instance | def update_instance(self, uid, body):
"""
Update an Model via a PUT request
:param str uid: String identifier for the list resource
:param dict body: Dictionary of items to PUT
"""
uri = "%s/%s" % (self.uri, uid)
response, instance = self.request("PUT", uri, data=body)
return self.load_instance(instance) | python | def update_instance(self, uid, body):
"""
Update an Model via a PUT request
:param str uid: String identifier for the list resource
:param dict body: Dictionary of items to PUT
"""
uri = "%s/%s" % (self.uri, uid)
response, instance = self.request("PUT", uri, data=body)
return self.load_instance(instance) | [
"def",
"update_instance",
"(",
"self",
",",
"uid",
",",
"body",
")",
":",
"uri",
"=",
"\"%s/%s\"",
"%",
"(",
"self",
".",
"uri",
",",
"uid",
")",
"response",
",",
"instance",
"=",
"self",
".",
"request",
"(",
"\"PUT\"",
",",
"uri",
",",
"data",
"="... | Update an Model via a PUT request
:param str uid: String identifier for the list resource
:param dict body: Dictionary of items to PUT | [
"Update",
"an",
"Model",
"via",
"a",
"PUT",
"request"
] | 15d679cb985b88b1cb2153ef2ba80d9749f9e281 | https://github.com/textmagic/textmagic-rest-python/blob/15d679cb985b88b1cb2153ef2ba80d9749f9e281/textmagic/rest/models/base.py#L217-L226 | train | 29,171 |
textmagic/textmagic-rest-python | textmagic/rest/models/base.py | CollectionModel.delete_instance | def delete_instance(self, uid):
"""
Delete an ObjectModel via a DELETE request
:param int uid: Unique id for the Model resource
"""
uri = "%s/%s" % (self.uri, uid)
response, instance = self.request("DELETE", uri)
return response.status == 204 | python | def delete_instance(self, uid):
"""
Delete an ObjectModel via a DELETE request
:param int uid: Unique id for the Model resource
"""
uri = "%s/%s" % (self.uri, uid)
response, instance = self.request("DELETE", uri)
return response.status == 204 | [
"def",
"delete_instance",
"(",
"self",
",",
"uid",
")",
":",
"uri",
"=",
"\"%s/%s\"",
"%",
"(",
"self",
".",
"uri",
",",
"uid",
")",
"response",
",",
"instance",
"=",
"self",
".",
"request",
"(",
"\"DELETE\"",
",",
"uri",
")",
"return",
"response",
"... | Delete an ObjectModel via a DELETE request
:param int uid: Unique id for the Model resource | [
"Delete",
"an",
"ObjectModel",
"via",
"a",
"DELETE",
"request"
] | 15d679cb985b88b1cb2153ef2ba80d9749f9e281 | https://github.com/textmagic/textmagic-rest-python/blob/15d679cb985b88b1cb2153ef2ba80d9749f9e281/textmagic/rest/models/base.py#L237-L245 | train | 29,172 |
adafruit/Adafruit_CircuitPython_Register | adafruit_register/i2c_struct_array.py | _BoundStructArray._get_buffer | def _get_buffer(self, index):
"""Shared bounds checking and buffer creation."""
if not 0 <= index < self.count:
raise IndexError()
size = struct.calcsize(self.format)
# We create the buffer every time instead of keeping the buffer (which is 32 bytes at least)
# around forever.
buf = bytearray(size + 1)
buf[0] = self.first_register + size * index
return buf | python | def _get_buffer(self, index):
"""Shared bounds checking and buffer creation."""
if not 0 <= index < self.count:
raise IndexError()
size = struct.calcsize(self.format)
# We create the buffer every time instead of keeping the buffer (which is 32 bytes at least)
# around forever.
buf = bytearray(size + 1)
buf[0] = self.first_register + size * index
return buf | [
"def",
"_get_buffer",
"(",
"self",
",",
"index",
")",
":",
"if",
"not",
"0",
"<=",
"index",
"<",
"self",
".",
"count",
":",
"raise",
"IndexError",
"(",
")",
"size",
"=",
"struct",
".",
"calcsize",
"(",
"self",
".",
"format",
")",
"# We create the buffe... | Shared bounds checking and buffer creation. | [
"Shared",
"bounds",
"checking",
"and",
"buffer",
"creation",
"."
] | 51f53825061630a3d50e2208096656e5ffdd5caa | https://github.com/adafruit/Adafruit_CircuitPython_Register/blob/51f53825061630a3d50e2208096656e5ffdd5caa/adafruit_register/i2c_struct_array.py#L55-L64 | train | 29,173 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI._unzip_file | def _unzip_file(self, src_path, dest_path, filename):
"""unzips file located at src_path into destination_path"""
self.logger.info("unzipping file...")
# construct full path (including file name) for unzipping
unzip_path = os.path.join(dest_path, filename)
utils.ensure_directory_exists(unzip_path)
# extract data
with zipfile.ZipFile(src_path, "r") as z:
z.extractall(unzip_path)
return True | python | def _unzip_file(self, src_path, dest_path, filename):
"""unzips file located at src_path into destination_path"""
self.logger.info("unzipping file...")
# construct full path (including file name) for unzipping
unzip_path = os.path.join(dest_path, filename)
utils.ensure_directory_exists(unzip_path)
# extract data
with zipfile.ZipFile(src_path, "r") as z:
z.extractall(unzip_path)
return True | [
"def",
"_unzip_file",
"(",
"self",
",",
"src_path",
",",
"dest_path",
",",
"filename",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"unzipping file...\"",
")",
"# construct full path (including file name) for unzipping",
"unzip_path",
"=",
"os",
".",
"path",... | unzips file located at src_path into destination_path | [
"unzips",
"file",
"located",
"at",
"src_path",
"into",
"destination_path"
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L76-L88 | train | 29,174 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.get_dataset_url | def get_dataset_url(self, tournament=1):
"""Fetch url of the current dataset.
Args:
tournament (int, optional): ID of the tournament, defaults to 1
Returns:
str: url of the current dataset
Example:
>>> NumerAPI().get_dataset_url()
https://numerai-datasets.s3.amazonaws.com/t1/104/numerai_datasets.zip?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIYNVLTPMU6QILOHA%2F20180424%2Fus-west-1%2Fs3%2Faws4_request&X-Amz-Date=20180424T084911Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=83863db44689c9907da6d3c8ac28160cd5e2d17aa90f12c7eee6811810e4b8d3
"""
query = """
query($tournament: Int!) {
dataset(tournament: $tournament)
}"""
arguments = {'tournament': tournament}
url = self.raw_query(query, arguments)['data']['dataset']
return url | python | def get_dataset_url(self, tournament=1):
"""Fetch url of the current dataset.
Args:
tournament (int, optional): ID of the tournament, defaults to 1
Returns:
str: url of the current dataset
Example:
>>> NumerAPI().get_dataset_url()
https://numerai-datasets.s3.amazonaws.com/t1/104/numerai_datasets.zip?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIYNVLTPMU6QILOHA%2F20180424%2Fus-west-1%2Fs3%2Faws4_request&X-Amz-Date=20180424T084911Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=83863db44689c9907da6d3c8ac28160cd5e2d17aa90f12c7eee6811810e4b8d3
"""
query = """
query($tournament: Int!) {
dataset(tournament: $tournament)
}"""
arguments = {'tournament': tournament}
url = self.raw_query(query, arguments)['data']['dataset']
return url | [
"def",
"get_dataset_url",
"(",
"self",
",",
"tournament",
"=",
"1",
")",
":",
"query",
"=",
"\"\"\"\n query($tournament: Int!) {\n dataset(tournament: $tournament)\n }\"\"\"",
"arguments",
"=",
"{",
"'tournament'",
":",
"tournament",
"}",
... | Fetch url of the current dataset.
Args:
tournament (int, optional): ID of the tournament, defaults to 1
Returns:
str: url of the current dataset
Example:
>>> NumerAPI().get_dataset_url()
https://numerai-datasets.s3.amazonaws.com/t1/104/numerai_datasets.zip?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIYNVLTPMU6QILOHA%2F20180424%2Fus-west-1%2Fs3%2Faws4_request&X-Amz-Date=20180424T084911Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=83863db44689c9907da6d3c8ac28160cd5e2d17aa90f12c7eee6811810e4b8d3 | [
"Fetch",
"url",
"of",
"the",
"current",
"dataset",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L90-L109 | train | 29,175 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.raw_query | def raw_query(self, query, variables=None, authorization=False):
"""Send a raw request to the Numerai's GraphQL API.
This function allows to build your own queries and fetch results from
Numerai's GraphQL API. Checkout
https://medium.com/numerai/getting-started-with-numerais-new-tournament-api-77396e895e72
for an introduction and https://api-tournament.numer.ai/ for the
documentation.
Args:
query (str): your query
variables (dict, optional): dict of variables
authorization (bool, optional): does the request require
authorization, defaults to `False`
Returns:
dict: Result of the request
Raises:
ValueError: if something went wrong with the requests. For example,
this could be a wrongly formatted query or a problem at
Numerai's end. Have a look at the error messages, in most cases
the problem is obvious.
Example:
>>> query = '''query($tournament: Int!)
{rounds(tournament: $tournament number: 0)
{number}}'''
>>> args = {'tournament': 1}
>>> NumerAPI().raw_query(query, args)
{'data': {'rounds': [{'number': 104}]}}
"""
body = {'query': query,
'variables': variables}
headers = {'Content-type': 'application/json',
'Accept': 'application/json'}
if authorization:
if self.token:
public_id, secret_key = self.token
headers['Authorization'] = \
'Token {}${}'.format(public_id, secret_key)
else:
raise ValueError("API keys required for this action.")
result = utils.post_with_err_handling(
API_TOURNAMENT_URL, body, headers)
if result and "errors" in result:
err = self._handle_call_error(result['errors'])
# fail!
raise ValueError(err)
return result | python | def raw_query(self, query, variables=None, authorization=False):
"""Send a raw request to the Numerai's GraphQL API.
This function allows to build your own queries and fetch results from
Numerai's GraphQL API. Checkout
https://medium.com/numerai/getting-started-with-numerais-new-tournament-api-77396e895e72
for an introduction and https://api-tournament.numer.ai/ for the
documentation.
Args:
query (str): your query
variables (dict, optional): dict of variables
authorization (bool, optional): does the request require
authorization, defaults to `False`
Returns:
dict: Result of the request
Raises:
ValueError: if something went wrong with the requests. For example,
this could be a wrongly formatted query or a problem at
Numerai's end. Have a look at the error messages, in most cases
the problem is obvious.
Example:
>>> query = '''query($tournament: Int!)
{rounds(tournament: $tournament number: 0)
{number}}'''
>>> args = {'tournament': 1}
>>> NumerAPI().raw_query(query, args)
{'data': {'rounds': [{'number': 104}]}}
"""
body = {'query': query,
'variables': variables}
headers = {'Content-type': 'application/json',
'Accept': 'application/json'}
if authorization:
if self.token:
public_id, secret_key = self.token
headers['Authorization'] = \
'Token {}${}'.format(public_id, secret_key)
else:
raise ValueError("API keys required for this action.")
result = utils.post_with_err_handling(
API_TOURNAMENT_URL, body, headers)
if result and "errors" in result:
err = self._handle_call_error(result['errors'])
# fail!
raise ValueError(err)
return result | [
"def",
"raw_query",
"(",
"self",
",",
"query",
",",
"variables",
"=",
"None",
",",
"authorization",
"=",
"False",
")",
":",
"body",
"=",
"{",
"'query'",
":",
"query",
",",
"'variables'",
":",
"variables",
"}",
"headers",
"=",
"{",
"'Content-type'",
":",
... | Send a raw request to the Numerai's GraphQL API.
This function allows to build your own queries and fetch results from
Numerai's GraphQL API. Checkout
https://medium.com/numerai/getting-started-with-numerais-new-tournament-api-77396e895e72
for an introduction and https://api-tournament.numer.ai/ for the
documentation.
Args:
query (str): your query
variables (dict, optional): dict of variables
authorization (bool, optional): does the request require
authorization, defaults to `False`
Returns:
dict: Result of the request
Raises:
ValueError: if something went wrong with the requests. For example,
this could be a wrongly formatted query or a problem at
Numerai's end. Have a look at the error messages, in most cases
the problem is obvious.
Example:
>>> query = '''query($tournament: Int!)
{rounds(tournament: $tournament number: 0)
{number}}'''
>>> args = {'tournament': 1}
>>> NumerAPI().raw_query(query, args)
{'data': {'rounds': [{'number': 104}]}} | [
"Send",
"a",
"raw",
"request",
"to",
"the",
"Numerai",
"s",
"GraphQL",
"API",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L170-L222 | train | 29,176 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.get_staking_leaderboard | def get_staking_leaderboard(self, round_num=0, tournament=1):
"""Retrieves the leaderboard of the staking competition for the given
round.
Args:
round_num (int, optional): The round you are interested in,
defaults to current round.
tournament (int, optional): ID of the tournament, defaults to 1
Returns:
list: list of stakers (`dict`)
Each stake in the list as the following structure:
* username (`str`)
* consistency (`float`)
* liveLogloss (`float` or `None`)
* liveAuroc (`float` or `None`)
* validationLogloss (`float`)
* validationAuroc (`float` or `None`)
* stake (`dict`)
* confidence (`decimal.Decimal`)
* insertedAt (`datetime`)
* soc (`decimal.Decimal`)
* txHash (`str`)
* value (`decimal.Decimal`)
Example:
>>> NumerAPI().get_staking_leaderboard(99)
[{'consistency': 83.33333333333334,
'liveLogloss': 0.6941153941722517,
'liveAuroc': 0.5241153941722517,
'stake': {'confidence': Decimal('0.055'),
'insertedAt': datetime.datetime(2018, 3, 18, 0, 20, 31, 724728, tzinfo=tzutc()),
'soc': Decimal('18.18'),
'txHash': '0xf1460c7fe08e7920d3e61492501337db5c89bff22af9fd88b9ff1ad604939f61',
'value': Decimal('1.00')},
'username': 'ci_wp',
'validationLogloss': 0.692269984475575},
'validationAuroc': 0.512269984475575},
..
]
"""
msg = "getting stakes for tournament {} round {}"
self.logger.info(msg.format(tournament, round_num))
query = '''
query($number: Int!
$tournament: Int!) {
rounds(number: $number
tournament: $tournament) {
leaderboard {
consistency
liveLogloss
liveAuroc
username
validationLogloss
validationAuroc
stake {
insertedAt
soc
confidence
value
txHash
}
}
}
}
'''
arguments = {'number': round_num, 'tournament': tournament}
result = self.raw_query(query, arguments)['data']['rounds'][0]
if result is None:
return None
stakes = result['leaderboard']
# filter those with actual stakes
stakes = [item for item in stakes if item["stake"] is not None]
# convert strings to python objects
for s in stakes:
utils.replace(s["stake"], "insertedAt",
utils.parse_datetime_string)
utils.replace(s["stake"], "confidence", utils.parse_float_string)
utils.replace(s["stake"], "soc", utils.parse_float_string)
utils.replace(s["stake"], "value", utils.parse_float_string)
return stakes | python | def get_staking_leaderboard(self, round_num=0, tournament=1):
"""Retrieves the leaderboard of the staking competition for the given
round.
Args:
round_num (int, optional): The round you are interested in,
defaults to current round.
tournament (int, optional): ID of the tournament, defaults to 1
Returns:
list: list of stakers (`dict`)
Each stake in the list as the following structure:
* username (`str`)
* consistency (`float`)
* liveLogloss (`float` or `None`)
* liveAuroc (`float` or `None`)
* validationLogloss (`float`)
* validationAuroc (`float` or `None`)
* stake (`dict`)
* confidence (`decimal.Decimal`)
* insertedAt (`datetime`)
* soc (`decimal.Decimal`)
* txHash (`str`)
* value (`decimal.Decimal`)
Example:
>>> NumerAPI().get_staking_leaderboard(99)
[{'consistency': 83.33333333333334,
'liveLogloss': 0.6941153941722517,
'liveAuroc': 0.5241153941722517,
'stake': {'confidence': Decimal('0.055'),
'insertedAt': datetime.datetime(2018, 3, 18, 0, 20, 31, 724728, tzinfo=tzutc()),
'soc': Decimal('18.18'),
'txHash': '0xf1460c7fe08e7920d3e61492501337db5c89bff22af9fd88b9ff1ad604939f61',
'value': Decimal('1.00')},
'username': 'ci_wp',
'validationLogloss': 0.692269984475575},
'validationAuroc': 0.512269984475575},
..
]
"""
msg = "getting stakes for tournament {} round {}"
self.logger.info(msg.format(tournament, round_num))
query = '''
query($number: Int!
$tournament: Int!) {
rounds(number: $number
tournament: $tournament) {
leaderboard {
consistency
liveLogloss
liveAuroc
username
validationLogloss
validationAuroc
stake {
insertedAt
soc
confidence
value
txHash
}
}
}
}
'''
arguments = {'number': round_num, 'tournament': tournament}
result = self.raw_query(query, arguments)['data']['rounds'][0]
if result is None:
return None
stakes = result['leaderboard']
# filter those with actual stakes
stakes = [item for item in stakes if item["stake"] is not None]
# convert strings to python objects
for s in stakes:
utils.replace(s["stake"], "insertedAt",
utils.parse_datetime_string)
utils.replace(s["stake"], "confidence", utils.parse_float_string)
utils.replace(s["stake"], "soc", utils.parse_float_string)
utils.replace(s["stake"], "value", utils.parse_float_string)
return stakes | [
"def",
"get_staking_leaderboard",
"(",
"self",
",",
"round_num",
"=",
"0",
",",
"tournament",
"=",
"1",
")",
":",
"msg",
"=",
"\"getting stakes for tournament {} round {}\"",
"self",
".",
"logger",
".",
"info",
"(",
"msg",
".",
"format",
"(",
"tournament",
","... | Retrieves the leaderboard of the staking competition for the given
round.
Args:
round_num (int, optional): The round you are interested in,
defaults to current round.
tournament (int, optional): ID of the tournament, defaults to 1
Returns:
list: list of stakers (`dict`)
Each stake in the list as the following structure:
* username (`str`)
* consistency (`float`)
* liveLogloss (`float` or `None`)
* liveAuroc (`float` or `None`)
* validationLogloss (`float`)
* validationAuroc (`float` or `None`)
* stake (`dict`)
* confidence (`decimal.Decimal`)
* insertedAt (`datetime`)
* soc (`decimal.Decimal`)
* txHash (`str`)
* value (`decimal.Decimal`)
Example:
>>> NumerAPI().get_staking_leaderboard(99)
[{'consistency': 83.33333333333334,
'liveLogloss': 0.6941153941722517,
'liveAuroc': 0.5241153941722517,
'stake': {'confidence': Decimal('0.055'),
'insertedAt': datetime.datetime(2018, 3, 18, 0, 20, 31, 724728, tzinfo=tzutc()),
'soc': Decimal('18.18'),
'txHash': '0xf1460c7fe08e7920d3e61492501337db5c89bff22af9fd88b9ff1ad604939f61',
'value': Decimal('1.00')},
'username': 'ci_wp',
'validationLogloss': 0.692269984475575},
'validationAuroc': 0.512269984475575},
..
] | [
"Retrieves",
"the",
"leaderboard",
"of",
"the",
"staking",
"competition",
"for",
"the",
"given",
"round",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L328-L410 | train | 29,177 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.get_nmr_prize_pool | def get_nmr_prize_pool(self, round_num=0, tournament=1):
"""Get NMR prize pool for the given round and tournament.
Args:
round_num (int, optional): The round you are interested in,
defaults to current round.
tournament (int, optional): ID of the tournament, defaults to 1
Returns:
decimal.Decimal: prize pool in NMR
Raises:
Value Error: in case of invalid round number
"""
tournaments = self.get_competitions(tournament)
tournaments.sort(key=lambda t: t['number'])
if round_num == 0:
t = tournaments[-1]
else:
tournaments = [t for t in tournaments if t['number'] == round_num]
if len(tournaments) == 0:
raise ValueError("invalid round number")
t = tournaments[0]
return t['prizePoolNmr'] | python | def get_nmr_prize_pool(self, round_num=0, tournament=1):
"""Get NMR prize pool for the given round and tournament.
Args:
round_num (int, optional): The round you are interested in,
defaults to current round.
tournament (int, optional): ID of the tournament, defaults to 1
Returns:
decimal.Decimal: prize pool in NMR
Raises:
Value Error: in case of invalid round number
"""
tournaments = self.get_competitions(tournament)
tournaments.sort(key=lambda t: t['number'])
if round_num == 0:
t = tournaments[-1]
else:
tournaments = [t for t in tournaments if t['number'] == round_num]
if len(tournaments) == 0:
raise ValueError("invalid round number")
t = tournaments[0]
return t['prizePoolNmr'] | [
"def",
"get_nmr_prize_pool",
"(",
"self",
",",
"round_num",
"=",
"0",
",",
"tournament",
"=",
"1",
")",
":",
"tournaments",
"=",
"self",
".",
"get_competitions",
"(",
"tournament",
")",
"tournaments",
".",
"sort",
"(",
"key",
"=",
"lambda",
"t",
":",
"t"... | Get NMR prize pool for the given round and tournament.
Args:
round_num (int, optional): The round you are interested in,
defaults to current round.
tournament (int, optional): ID of the tournament, defaults to 1
Returns:
decimal.Decimal: prize pool in NMR
Raises:
Value Error: in case of invalid round number | [
"Get",
"NMR",
"prize",
"pool",
"for",
"the",
"given",
"round",
"and",
"tournament",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L412-L435 | train | 29,178 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.get_competitions | def get_competitions(self, tournament=1):
"""Retrieves information about all competitions
Args:
tournament (int, optional): ID of the tournament, defaults to 1
Returns:
list of dicts: list of rounds
Each round's dict contains the following items:
* datasetId (`str`)
* number (`int`)
* openTime (`datetime`)
* resolveTime (`datetime`)
* participants (`int`): number of participants
* prizePoolNmr (`decimal.Decimal`)
* prizePoolUsd (`decimal.Decimal`)
* resolvedGeneral (`bool`)
* resolvedStaking (`bool`)
* ruleset (`string`)
Example:
>>> NumerAPI().get_competitions()
[
{'datasetId': '59a70840ca11173c8b2906ac',
'number': 71,
'openTime': datetime.datetime(2017, 8, 31, 0, 0),
'resolveTime': datetime.datetime(2017, 9, 27, 21, 0),
'participants': 1287,
'prizePoolNmr': Decimal('0.00'),
'prizePoolUsd': Decimal('6000.00'),
'resolvedGeneral': True,
'resolvedStaking': True,
'ruleset': 'p_auction'
},
..
]
"""
self.logger.info("getting rounds...")
query = '''
query($tournament: Int!) {
rounds(tournament: $tournament) {
number
resolveTime
datasetId
openTime
resolvedGeneral
resolvedStaking
participants
prizePoolNmr
prizePoolUsd
ruleset
}
}
'''
arguments = {'tournament': tournament}
result = self.raw_query(query, arguments)
rounds = result['data']['rounds']
# convert datetime strings to datetime.datetime objects
for r in rounds:
utils.replace(r, "openTime", utils.parse_datetime_string)
utils.replace(r, "resolveTime", utils.parse_datetime_string)
utils.replace(r, "prizePoolNmr", utils.parse_float_string)
utils.replace(r, "prizePoolUsd", utils.parse_float_string)
return rounds | python | def get_competitions(self, tournament=1):
"""Retrieves information about all competitions
Args:
tournament (int, optional): ID of the tournament, defaults to 1
Returns:
list of dicts: list of rounds
Each round's dict contains the following items:
* datasetId (`str`)
* number (`int`)
* openTime (`datetime`)
* resolveTime (`datetime`)
* participants (`int`): number of participants
* prizePoolNmr (`decimal.Decimal`)
* prizePoolUsd (`decimal.Decimal`)
* resolvedGeneral (`bool`)
* resolvedStaking (`bool`)
* ruleset (`string`)
Example:
>>> NumerAPI().get_competitions()
[
{'datasetId': '59a70840ca11173c8b2906ac',
'number': 71,
'openTime': datetime.datetime(2017, 8, 31, 0, 0),
'resolveTime': datetime.datetime(2017, 9, 27, 21, 0),
'participants': 1287,
'prizePoolNmr': Decimal('0.00'),
'prizePoolUsd': Decimal('6000.00'),
'resolvedGeneral': True,
'resolvedStaking': True,
'ruleset': 'p_auction'
},
..
]
"""
self.logger.info("getting rounds...")
query = '''
query($tournament: Int!) {
rounds(tournament: $tournament) {
number
resolveTime
datasetId
openTime
resolvedGeneral
resolvedStaking
participants
prizePoolNmr
prizePoolUsd
ruleset
}
}
'''
arguments = {'tournament': tournament}
result = self.raw_query(query, arguments)
rounds = result['data']['rounds']
# convert datetime strings to datetime.datetime objects
for r in rounds:
utils.replace(r, "openTime", utils.parse_datetime_string)
utils.replace(r, "resolveTime", utils.parse_datetime_string)
utils.replace(r, "prizePoolNmr", utils.parse_float_string)
utils.replace(r, "prizePoolUsd", utils.parse_float_string)
return rounds | [
"def",
"get_competitions",
"(",
"self",
",",
"tournament",
"=",
"1",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"getting rounds...\"",
")",
"query",
"=",
"'''\n query($tournament: Int!) {\n rounds(tournament: $tournament) {\n n... | Retrieves information about all competitions
Args:
tournament (int, optional): ID of the tournament, defaults to 1
Returns:
list of dicts: list of rounds
Each round's dict contains the following items:
* datasetId (`str`)
* number (`int`)
* openTime (`datetime`)
* resolveTime (`datetime`)
* participants (`int`): number of participants
* prizePoolNmr (`decimal.Decimal`)
* prizePoolUsd (`decimal.Decimal`)
* resolvedGeneral (`bool`)
* resolvedStaking (`bool`)
* ruleset (`string`)
Example:
>>> NumerAPI().get_competitions()
[
{'datasetId': '59a70840ca11173c8b2906ac',
'number': 71,
'openTime': datetime.datetime(2017, 8, 31, 0, 0),
'resolveTime': datetime.datetime(2017, 9, 27, 21, 0),
'participants': 1287,
'prizePoolNmr': Decimal('0.00'),
'prizePoolUsd': Decimal('6000.00'),
'resolvedGeneral': True,
'resolvedStaking': True,
'ruleset': 'p_auction'
},
..
] | [
"Retrieves",
"information",
"about",
"all",
"competitions"
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L470-L536 | train | 29,179 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.get_current_round | def get_current_round(self, tournament=1):
"""Get number of the current active round.
Args:
tournament (int): ID of the tournament (optional, defaults to 1)
Returns:
int: number of the current active round
Example:
>>> NumerAPI().get_current_round()
104
"""
# zero is an alias for the current round!
query = '''
query($tournament: Int!) {
rounds(tournament: $tournament
number: 0) {
number
}
}
'''
arguments = {'tournament': tournament}
data = self.raw_query(query, arguments)['data']['rounds'][0]
if data is None:
return None
round_num = data["number"]
return round_num | python | def get_current_round(self, tournament=1):
"""Get number of the current active round.
Args:
tournament (int): ID of the tournament (optional, defaults to 1)
Returns:
int: number of the current active round
Example:
>>> NumerAPI().get_current_round()
104
"""
# zero is an alias for the current round!
query = '''
query($tournament: Int!) {
rounds(tournament: $tournament
number: 0) {
number
}
}
'''
arguments = {'tournament': tournament}
data = self.raw_query(query, arguments)['data']['rounds'][0]
if data is None:
return None
round_num = data["number"]
return round_num | [
"def",
"get_current_round",
"(",
"self",
",",
"tournament",
"=",
"1",
")",
":",
"# zero is an alias for the current round!",
"query",
"=",
"'''\n query($tournament: Int!) {\n rounds(tournament: $tournament\n number: 0) {\n number\n... | Get number of the current active round.
Args:
tournament (int): ID of the tournament (optional, defaults to 1)
Returns:
int: number of the current active round
Example:
>>> NumerAPI().get_current_round()
104 | [
"Get",
"number",
"of",
"the",
"current",
"active",
"round",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L538-L565 | train | 29,180 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.get_tournaments | def get_tournaments(self, only_active=True):
"""Get all tournaments
Args:
only_active (bool): Flag to indicate of only active tournaments
should be returned or all of them. Defaults
to True.
Returns:
list of dicts: list of tournaments
Each tournaments' dict contains the following items:
* id (`str`)
* name (`str`)
* tournament (`int`)
* active (`bool`)
Example:
>>> NumerAPI().get_tournaments()
[ { 'id': '2ecf30f4-4b4f-42e9-8e72-cc5bd61c2733',
'name': 'alpha',
'tournament': 1,
'active': True},
{ 'id': '6ff44cca-263d-40bd-b029-a1ab8f42798f',
'name': 'bravo',
'tournament': 2,
'active': True},
{ 'id': 'ebf0d62b-0f60-4550-bcec-c737b168c65d',
'name': 'charlie',
'tournament': 3
'active': False},
{ 'id': '5fac6ece-2726-4b66-9790-95866b3a77fc',
'name': 'delta',
'tournament': 4,
'active': True}]
"""
query = """
query {
tournaments {
id
name
tournament
active
}
}
"""
data = self.raw_query(query)['data']['tournaments']
if only_active:
data = [d for d in data if d['active']]
return data | python | def get_tournaments(self, only_active=True):
"""Get all tournaments
Args:
only_active (bool): Flag to indicate of only active tournaments
should be returned or all of them. Defaults
to True.
Returns:
list of dicts: list of tournaments
Each tournaments' dict contains the following items:
* id (`str`)
* name (`str`)
* tournament (`int`)
* active (`bool`)
Example:
>>> NumerAPI().get_tournaments()
[ { 'id': '2ecf30f4-4b4f-42e9-8e72-cc5bd61c2733',
'name': 'alpha',
'tournament': 1,
'active': True},
{ 'id': '6ff44cca-263d-40bd-b029-a1ab8f42798f',
'name': 'bravo',
'tournament': 2,
'active': True},
{ 'id': 'ebf0d62b-0f60-4550-bcec-c737b168c65d',
'name': 'charlie',
'tournament': 3
'active': False},
{ 'id': '5fac6ece-2726-4b66-9790-95866b3a77fc',
'name': 'delta',
'tournament': 4,
'active': True}]
"""
query = """
query {
tournaments {
id
name
tournament
active
}
}
"""
data = self.raw_query(query)['data']['tournaments']
if only_active:
data = [d for d in data if d['active']]
return data | [
"def",
"get_tournaments",
"(",
"self",
",",
"only_active",
"=",
"True",
")",
":",
"query",
"=",
"\"\"\"\n query {\n tournaments {\n id\n name\n tournament\n active\n }\n }\n \"\"\"",
... | Get all tournaments
Args:
only_active (bool): Flag to indicate of only active tournaments
should be returned or all of them. Defaults
to True.
Returns:
list of dicts: list of tournaments
Each tournaments' dict contains the following items:
* id (`str`)
* name (`str`)
* tournament (`int`)
* active (`bool`)
Example:
>>> NumerAPI().get_tournaments()
[ { 'id': '2ecf30f4-4b4f-42e9-8e72-cc5bd61c2733',
'name': 'alpha',
'tournament': 1,
'active': True},
{ 'id': '6ff44cca-263d-40bd-b029-a1ab8f42798f',
'name': 'bravo',
'tournament': 2,
'active': True},
{ 'id': 'ebf0d62b-0f60-4550-bcec-c737b168c65d',
'name': 'charlie',
'tournament': 3
'active': False},
{ 'id': '5fac6ece-2726-4b66-9790-95866b3a77fc',
'name': 'delta',
'tournament': 4,
'active': True}] | [
"Get",
"all",
"tournaments"
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L567-L617 | train | 29,181 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.get_submission_filenames | def get_submission_filenames(self, tournament=None, round_num=None):
"""Get filenames of the submission of the user.
Args:
tournament (int): optionally filter by ID of the tournament
round_num (int): optionally filter round number
Returns:
list: list of user filenames (`dict`)
Each filenames in the list as the following structure:
* filename (`str`)
* round_num (`int`)
* tournament (`int`)
Example:
>>> NumerAPI().get_submission_filenames(3, 111)
[{'filename': 'model57-dMpHpYMPIUAF.csv',
'round_num': 111,
'tournament': 3}]
"""
query = '''
query {
user {
submissions {
filename
selected
round {
tournament
number
}
}
}
}
'''
data = self.raw_query(query, authorization=True)['data']['user']
filenames = [{"round_num": item['round']['number'],
"tournament": item['round']['tournament'],
"filename": item['filename']}
for item in data['submissions'] if item['selected']]
if round_num is not None:
filenames = [f for f in filenames if f['round_num'] == round_num]
if tournament is not None:
filenames = [f for f in filenames if f['tournament'] == tournament]
filenames.sort(key=lambda f: (f['round_num'], f['tournament']))
return filenames | python | def get_submission_filenames(self, tournament=None, round_num=None):
"""Get filenames of the submission of the user.
Args:
tournament (int): optionally filter by ID of the tournament
round_num (int): optionally filter round number
Returns:
list: list of user filenames (`dict`)
Each filenames in the list as the following structure:
* filename (`str`)
* round_num (`int`)
* tournament (`int`)
Example:
>>> NumerAPI().get_submission_filenames(3, 111)
[{'filename': 'model57-dMpHpYMPIUAF.csv',
'round_num': 111,
'tournament': 3}]
"""
query = '''
query {
user {
submissions {
filename
selected
round {
tournament
number
}
}
}
}
'''
data = self.raw_query(query, authorization=True)['data']['user']
filenames = [{"round_num": item['round']['number'],
"tournament": item['round']['tournament'],
"filename": item['filename']}
for item in data['submissions'] if item['selected']]
if round_num is not None:
filenames = [f for f in filenames if f['round_num'] == round_num]
if tournament is not None:
filenames = [f for f in filenames if f['tournament'] == tournament]
filenames.sort(key=lambda f: (f['round_num'], f['tournament']))
return filenames | [
"def",
"get_submission_filenames",
"(",
"self",
",",
"tournament",
"=",
"None",
",",
"round_num",
"=",
"None",
")",
":",
"query",
"=",
"'''\n query {\n user {\n submissions {\n filename\n selected\n round {... | Get filenames of the submission of the user.
Args:
tournament (int): optionally filter by ID of the tournament
round_num (int): optionally filter round number
Returns:
list: list of user filenames (`dict`)
Each filenames in the list as the following structure:
* filename (`str`)
* round_num (`int`)
* tournament (`int`)
Example:
>>> NumerAPI().get_submission_filenames(3, 111)
[{'filename': 'model57-dMpHpYMPIUAF.csv',
'round_num': 111,
'tournament': 3}] | [
"Get",
"filenames",
"of",
"the",
"submission",
"of",
"the",
"user",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L728-L777 | train | 29,182 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.get_rankings | def get_rankings(self, limit=50, offset=0):
"""Get the overall ranking
Args:
limit (int): number of items to return (optional, defaults to 50)
offset (int): number of items to skip (optional, defaults to 0)
Returns:
list of dicts: list of ranking items
Each dict contains the following items:
* id (`str`)
* username (`str`)
* nmrBurned (`decimal.Decimal`)
* nmrPaid (`decimal.Decimal`)
* nmrStaked (`decimal.Decimal`)
* rep (`int`)
* stakeCount (`int`)
* usdEarned (`decimal.Decimal`)
Example:
>>> numerapi.NumerAPI().get_rankings(1)
[{'username': 'glasperlenspiel',
'usdEarned': Decimal('16347.12'),
'stakeCount': 41,
'rep': 14,
'nmrStaked': Decimal('250.000000000000000000'),
'nmrPaid': Decimal('16061.37'),
'nmrBurned': Decimal('295.400000000000000000'),
'id': 'bbee4f0e-f238-4d8a-8f1b-5eb384cdcbfc'}]
"""
query = '''
query($limit: Int!
$offset: Int!) {
rankings(limit: $limit
offset: $offset) {
username
id
nmrBurned
nmrPaid
nmrStaked
rep
stakeCount
usdEarned
}
}
'''
arguments = {'limit': limit, 'offset': offset}
data = self.raw_query(query, arguments)['data']['rankings']
for item in data:
for p in ["nmrBurned", "nmrPaid", "nmrStaked", "usdEarned"]:
utils.replace(item, p, utils.parse_float_string)
return data | python | def get_rankings(self, limit=50, offset=0):
"""Get the overall ranking
Args:
limit (int): number of items to return (optional, defaults to 50)
offset (int): number of items to skip (optional, defaults to 0)
Returns:
list of dicts: list of ranking items
Each dict contains the following items:
* id (`str`)
* username (`str`)
* nmrBurned (`decimal.Decimal`)
* nmrPaid (`decimal.Decimal`)
* nmrStaked (`decimal.Decimal`)
* rep (`int`)
* stakeCount (`int`)
* usdEarned (`decimal.Decimal`)
Example:
>>> numerapi.NumerAPI().get_rankings(1)
[{'username': 'glasperlenspiel',
'usdEarned': Decimal('16347.12'),
'stakeCount': 41,
'rep': 14,
'nmrStaked': Decimal('250.000000000000000000'),
'nmrPaid': Decimal('16061.37'),
'nmrBurned': Decimal('295.400000000000000000'),
'id': 'bbee4f0e-f238-4d8a-8f1b-5eb384cdcbfc'}]
"""
query = '''
query($limit: Int!
$offset: Int!) {
rankings(limit: $limit
offset: $offset) {
username
id
nmrBurned
nmrPaid
nmrStaked
rep
stakeCount
usdEarned
}
}
'''
arguments = {'limit': limit, 'offset': offset}
data = self.raw_query(query, arguments)['data']['rankings']
for item in data:
for p in ["nmrBurned", "nmrPaid", "nmrStaked", "usdEarned"]:
utils.replace(item, p, utils.parse_float_string)
return data | [
"def",
"get_rankings",
"(",
"self",
",",
"limit",
"=",
"50",
",",
"offset",
"=",
"0",
")",
":",
"query",
"=",
"'''\n query($limit: Int!\n $offset: Int!) {\n rankings(limit: $limit\n offset: $offset) {\n use... | Get the overall ranking
Args:
limit (int): number of items to return (optional, defaults to 50)
offset (int): number of items to skip (optional, defaults to 0)
Returns:
list of dicts: list of ranking items
Each dict contains the following items:
* id (`str`)
* username (`str`)
* nmrBurned (`decimal.Decimal`)
* nmrPaid (`decimal.Decimal`)
* nmrStaked (`decimal.Decimal`)
* rep (`int`)
* stakeCount (`int`)
* usdEarned (`decimal.Decimal`)
Example:
>>> numerapi.NumerAPI().get_rankings(1)
[{'username': 'glasperlenspiel',
'usdEarned': Decimal('16347.12'),
'stakeCount': 41,
'rep': 14,
'nmrStaked': Decimal('250.000000000000000000'),
'nmrPaid': Decimal('16061.37'),
'nmrBurned': Decimal('295.400000000000000000'),
'id': 'bbee4f0e-f238-4d8a-8f1b-5eb384cdcbfc'}] | [
"Get",
"the",
"overall",
"ranking"
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L779-L832 | train | 29,183 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.get_submission_ids | def get_submission_ids(self, tournament=1):
"""Get dict with username->submission_id mapping.
Args:
tournament (int): ID of the tournament (optional, defaults to 1)
Returns:
dict: username->submission_id mapping, string->string
Example:
>>> NumerAPI().get_submission_ids()
{'1337ai': '93c46857-fed9-4594-981e-82db2b358daf',
'1x0r': '108c7601-822c-4910-835d-241da93e2e24',
...
}
"""
query = """
query($tournament: Int!) {
rounds(tournament: $tournament
number: 0) {
leaderboard {
username
submissionId
}
}
}
"""
arguments = {'tournament': tournament}
data = self.raw_query(query, arguments)['data']['rounds'][0]
if data is None:
return None
mapping = {item['username']: item['submissionId']
for item in data['leaderboard']}
return mapping | python | def get_submission_ids(self, tournament=1):
"""Get dict with username->submission_id mapping.
Args:
tournament (int): ID of the tournament (optional, defaults to 1)
Returns:
dict: username->submission_id mapping, string->string
Example:
>>> NumerAPI().get_submission_ids()
{'1337ai': '93c46857-fed9-4594-981e-82db2b358daf',
'1x0r': '108c7601-822c-4910-835d-241da93e2e24',
...
}
"""
query = """
query($tournament: Int!) {
rounds(tournament: $tournament
number: 0) {
leaderboard {
username
submissionId
}
}
}
"""
arguments = {'tournament': tournament}
data = self.raw_query(query, arguments)['data']['rounds'][0]
if data is None:
return None
mapping = {item['username']: item['submissionId']
for item in data['leaderboard']}
return mapping | [
"def",
"get_submission_ids",
"(",
"self",
",",
"tournament",
"=",
"1",
")",
":",
"query",
"=",
"\"\"\"\n query($tournament: Int!) {\n rounds(tournament: $tournament\n number: 0) {\n leaderboard {\n username\n ... | Get dict with username->submission_id mapping.
Args:
tournament (int): ID of the tournament (optional, defaults to 1)
Returns:
dict: username->submission_id mapping, string->string
Example:
>>> NumerAPI().get_submission_ids()
{'1337ai': '93c46857-fed9-4594-981e-82db2b358daf',
'1x0r': '108c7601-822c-4910-835d-241da93e2e24',
...
} | [
"Get",
"dict",
"with",
"username",
"-",
">",
"submission_id",
"mapping",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L834-L867 | train | 29,184 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.get_user | def get_user(self):
"""Get all information about you!
Returns:
dict: user information including the following fields:
* assignedEthAddress (`str`)
* availableNmr (`decimal.Decimal`)
* availableUsd (`decimal.Decimal`)
* banned (`bool`)
* email (`str`)
* id (`str`)
* insertedAt (`datetime`)
* mfaEnabled (`bool`)
* status (`str`)
* username (`str`)
* country (`str)
* phoneNumber (`str`)
* apiTokens (`list`) each with the following fields:
* name (`str`)
* public_id (`str`)
* scopes (`list of str`)
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.get_user()
{'apiTokens': [
{'name': 'tokenname',
'public_id': 'BLABLA',
'scopes': ['upload_submission', 'stake', ..]
}, ..],
'assignedEthAddress': '0x0000000000000000000000000001',
'availableNmr': Decimal('99.01'),
'availableUsd': Decimal('9.47'),
'banned': False,
'email': 'username@example.com',
'phoneNumber': '0123456',
'country': 'US',
'id': '1234-ABC..',
'insertedAt': datetime.datetime(2018, 1, 1, 2, 16, 48),
'mfaEnabled': False,
'status': 'VERIFIED',
'username': 'cool username'
}
"""
query = """
query {
user {
username
banned
assignedEthAddress
availableNmr
availableUsd
email
id
mfaEnabled
status
country
phoneNumber
insertedAt
apiTokens {
name
public_id
scopes
}
}
}
"""
data = self.raw_query(query, authorization=True)['data']['user']
# convert strings to python objects
utils.replace(data, "insertedAt", utils.parse_datetime_string)
utils.replace(data, "availableUsd", utils.parse_float_string)
utils.replace(data, "availableNmr", utils.parse_float_string)
return data | python | def get_user(self):
"""Get all information about you!
Returns:
dict: user information including the following fields:
* assignedEthAddress (`str`)
* availableNmr (`decimal.Decimal`)
* availableUsd (`decimal.Decimal`)
* banned (`bool`)
* email (`str`)
* id (`str`)
* insertedAt (`datetime`)
* mfaEnabled (`bool`)
* status (`str`)
* username (`str`)
* country (`str)
* phoneNumber (`str`)
* apiTokens (`list`) each with the following fields:
* name (`str`)
* public_id (`str`)
* scopes (`list of str`)
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.get_user()
{'apiTokens': [
{'name': 'tokenname',
'public_id': 'BLABLA',
'scopes': ['upload_submission', 'stake', ..]
}, ..],
'assignedEthAddress': '0x0000000000000000000000000001',
'availableNmr': Decimal('99.01'),
'availableUsd': Decimal('9.47'),
'banned': False,
'email': 'username@example.com',
'phoneNumber': '0123456',
'country': 'US',
'id': '1234-ABC..',
'insertedAt': datetime.datetime(2018, 1, 1, 2, 16, 48),
'mfaEnabled': False,
'status': 'VERIFIED',
'username': 'cool username'
}
"""
query = """
query {
user {
username
banned
assignedEthAddress
availableNmr
availableUsd
email
id
mfaEnabled
status
country
phoneNumber
insertedAt
apiTokens {
name
public_id
scopes
}
}
}
"""
data = self.raw_query(query, authorization=True)['data']['user']
# convert strings to python objects
utils.replace(data, "insertedAt", utils.parse_datetime_string)
utils.replace(data, "availableUsd", utils.parse_float_string)
utils.replace(data, "availableNmr", utils.parse_float_string)
return data | [
"def",
"get_user",
"(",
"self",
")",
":",
"query",
"=",
"\"\"\"\n query {\n user {\n username\n banned\n assignedEthAddress\n availableNmr\n availableUsd\n email\n id\n mfaEnab... | Get all information about you!
Returns:
dict: user information including the following fields:
* assignedEthAddress (`str`)
* availableNmr (`decimal.Decimal`)
* availableUsd (`decimal.Decimal`)
* banned (`bool`)
* email (`str`)
* id (`str`)
* insertedAt (`datetime`)
* mfaEnabled (`bool`)
* status (`str`)
* username (`str`)
* country (`str)
* phoneNumber (`str`)
* apiTokens (`list`) each with the following fields:
* name (`str`)
* public_id (`str`)
* scopes (`list of str`)
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.get_user()
{'apiTokens': [
{'name': 'tokenname',
'public_id': 'BLABLA',
'scopes': ['upload_submission', 'stake', ..]
}, ..],
'assignedEthAddress': '0x0000000000000000000000000001',
'availableNmr': Decimal('99.01'),
'availableUsd': Decimal('9.47'),
'banned': False,
'email': 'username@example.com',
'phoneNumber': '0123456',
'country': 'US',
'id': '1234-ABC..',
'insertedAt': datetime.datetime(2018, 1, 1, 2, 16, 48),
'mfaEnabled': False,
'status': 'VERIFIED',
'username': 'cool username'
} | [
"Get",
"all",
"information",
"about",
"you!"
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L869-L942 | train | 29,185 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.get_payments | def get_payments(self):
"""Get all your payments.
Returns:
list of dicts: payments
For each payout in the list, a dict contains the following items:
* nmrAmount (`decimal.Decimal`)
* usdAmount (`decimal.Decimal`)
* tournament (`str`)
* round (`dict`)
* number (`int`)
* openTime (`datetime`)
* resolveTime (`datetime`)
* resolvedGeneral (`bool`)
* resolvedStaking (`bool`)
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.get_payments()
[{'nmrAmount': Decimal('0.00'),
'round': {'number': 84,
'openTime': datetime.datetime(2017, 12, 2, 18, 0, tzinfo=tzutc()),
'resolveTime': datetime.datetime(2018, 1, 1, 18, 0, tzinfo=tzutc()),
'resolvedGeneral': True,
'resolvedStaking': True},
'tournament': 'staking',
'usdAmount': Decimal('17.44')},
...
]
"""
query = """
query {
user {
payments {
nmrAmount
round {
number
openTime
resolveTime
resolvedGeneral
resolvedStaking
}
tournament
usdAmount
}
}
}
"""
data = self.raw_query(query, authorization=True)['data']
payments = data['user']['payments']
# convert strings to python objects
for p in payments:
utils.replace(p['round'], "openTime", utils.parse_datetime_string)
utils.replace(p['round'], "resolveTime",
utils.parse_datetime_string)
utils.replace(p, "usdAmount", utils.parse_float_string)
utils.replace(p, "nmrAmount", utils.parse_float_string)
return payments | python | def get_payments(self):
"""Get all your payments.
Returns:
list of dicts: payments
For each payout in the list, a dict contains the following items:
* nmrAmount (`decimal.Decimal`)
* usdAmount (`decimal.Decimal`)
* tournament (`str`)
* round (`dict`)
* number (`int`)
* openTime (`datetime`)
* resolveTime (`datetime`)
* resolvedGeneral (`bool`)
* resolvedStaking (`bool`)
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.get_payments()
[{'nmrAmount': Decimal('0.00'),
'round': {'number': 84,
'openTime': datetime.datetime(2017, 12, 2, 18, 0, tzinfo=tzutc()),
'resolveTime': datetime.datetime(2018, 1, 1, 18, 0, tzinfo=tzutc()),
'resolvedGeneral': True,
'resolvedStaking': True},
'tournament': 'staking',
'usdAmount': Decimal('17.44')},
...
]
"""
query = """
query {
user {
payments {
nmrAmount
round {
number
openTime
resolveTime
resolvedGeneral
resolvedStaking
}
tournament
usdAmount
}
}
}
"""
data = self.raw_query(query, authorization=True)['data']
payments = data['user']['payments']
# convert strings to python objects
for p in payments:
utils.replace(p['round'], "openTime", utils.parse_datetime_string)
utils.replace(p['round'], "resolveTime",
utils.parse_datetime_string)
utils.replace(p, "usdAmount", utils.parse_float_string)
utils.replace(p, "nmrAmount", utils.parse_float_string)
return payments | [
"def",
"get_payments",
"(",
"self",
")",
":",
"query",
"=",
"\"\"\"\n query {\n user {\n payments {\n nmrAmount\n round {\n number\n openTime\n resolveTime\n resolvedGen... | Get all your payments.
Returns:
list of dicts: payments
For each payout in the list, a dict contains the following items:
* nmrAmount (`decimal.Decimal`)
* usdAmount (`decimal.Decimal`)
* tournament (`str`)
* round (`dict`)
* number (`int`)
* openTime (`datetime`)
* resolveTime (`datetime`)
* resolvedGeneral (`bool`)
* resolvedStaking (`bool`)
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.get_payments()
[{'nmrAmount': Decimal('0.00'),
'round': {'number': 84,
'openTime': datetime.datetime(2017, 12, 2, 18, 0, tzinfo=tzutc()),
'resolveTime': datetime.datetime(2018, 1, 1, 18, 0, tzinfo=tzutc()),
'resolvedGeneral': True,
'resolvedStaking': True},
'tournament': 'staking',
'usdAmount': Decimal('17.44')},
...
] | [
"Get",
"all",
"your",
"payments",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L944-L1003 | train | 29,186 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.get_transactions | def get_transactions(self):
"""Get all your deposits and withdrawals.
Returns:
dict: lists of your NMR and USD transactions
The returned dict has the following structure:
* nmrDeposits (`list`) contains items with fields:
* from (`str`)
* posted (`bool`)
* status (`str`)
* to (`str`)
* txHash (`str`)
* value (`decimal.Decimal`)
* nmrWithdrawals"` (`list`) contains items with fields:
* from"` (`str`)
* posted"` (`bool`)
* status"` (`str`)
* to"` (`str`)
* txHash"` (`str`)
* value"` (`decimal.Decimal`)
* usdWithdrawals"` (`list`) contains items with fields:
* confirmTime"` (`datetime` or `None`)
* ethAmount"` (`str`)
* from"` (`str`)
* posted"` (`bool`)
* sendTime"` (`datetime`)
* status"` (`str`)
* to (`str`)
* txHash (`str`)
* usdAmount (`decimal.Decimal`)
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.get_transactions()
{'nmrDeposits': [
{'from': '0x54479..9ec897a',
'posted': True,
'status': 'confirmed',
'to': '0x0000000000000000000001',
'txHash': '0x52..e2056ab',
'value': Decimal('9.0')},
.. ],
'nmrWithdrawals': [
{'from': '0x0000000000000000..002',
'posted': True,
'status': 'confirmed',
'to': '0x00000000000..001',
'txHash': '0x1278..266c',
'value': Decimal('2.0')},
.. ],
'usdWithdrawals': [
{'confirmTime': datetime.datetime(2018, 2, 11, 17, 54, 2, 785430, tzinfo=tzutc()),
'ethAmount': '0.295780674909307710',
'from': '0x11.....',
'posted': True,
'sendTime': datetime.datetime(2018, 2, 11, 17, 53, 25, 235035, tzinfo=tzutc()),
'status': 'confirmed',
'to': '0x81.....',
'txHash': '0x3c....',
'usdAmount': Decimal('10.07')},
..]}
"""
query = """
query {
user {
nmrDeposits {
from
posted
status
to
txHash
value
}
nmrWithdrawals {
from
posted
status
to
txHash
value
}
usdWithdrawals {
ethAmount
confirmTime
from
posted
sendTime
status
to
txHash
usdAmount
}
}
}
"""
txs = self.raw_query(query, authorization=True)['data']['user']
# convert strings to python objects
for t in txs['usdWithdrawals']:
utils.replace(t, "confirmTime", utils.parse_datetime_string)
utils.replace(t, "sendTime", utils.parse_datetime_string)
utils.replace(t, "usdAmount", utils.parse_float_string)
for t in txs["nmrWithdrawals"]:
utils.replace(t, "value", utils.parse_float_string)
for t in txs["nmrDeposits"]:
utils.replace(t, "value", utils.parse_float_string)
return txs | python | def get_transactions(self):
"""Get all your deposits and withdrawals.
Returns:
dict: lists of your NMR and USD transactions
The returned dict has the following structure:
* nmrDeposits (`list`) contains items with fields:
* from (`str`)
* posted (`bool`)
* status (`str`)
* to (`str`)
* txHash (`str`)
* value (`decimal.Decimal`)
* nmrWithdrawals"` (`list`) contains items with fields:
* from"` (`str`)
* posted"` (`bool`)
* status"` (`str`)
* to"` (`str`)
* txHash"` (`str`)
* value"` (`decimal.Decimal`)
* usdWithdrawals"` (`list`) contains items with fields:
* confirmTime"` (`datetime` or `None`)
* ethAmount"` (`str`)
* from"` (`str`)
* posted"` (`bool`)
* sendTime"` (`datetime`)
* status"` (`str`)
* to (`str`)
* txHash (`str`)
* usdAmount (`decimal.Decimal`)
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.get_transactions()
{'nmrDeposits': [
{'from': '0x54479..9ec897a',
'posted': True,
'status': 'confirmed',
'to': '0x0000000000000000000001',
'txHash': '0x52..e2056ab',
'value': Decimal('9.0')},
.. ],
'nmrWithdrawals': [
{'from': '0x0000000000000000..002',
'posted': True,
'status': 'confirmed',
'to': '0x00000000000..001',
'txHash': '0x1278..266c',
'value': Decimal('2.0')},
.. ],
'usdWithdrawals': [
{'confirmTime': datetime.datetime(2018, 2, 11, 17, 54, 2, 785430, tzinfo=tzutc()),
'ethAmount': '0.295780674909307710',
'from': '0x11.....',
'posted': True,
'sendTime': datetime.datetime(2018, 2, 11, 17, 53, 25, 235035, tzinfo=tzutc()),
'status': 'confirmed',
'to': '0x81.....',
'txHash': '0x3c....',
'usdAmount': Decimal('10.07')},
..]}
"""
query = """
query {
user {
nmrDeposits {
from
posted
status
to
txHash
value
}
nmrWithdrawals {
from
posted
status
to
txHash
value
}
usdWithdrawals {
ethAmount
confirmTime
from
posted
sendTime
status
to
txHash
usdAmount
}
}
}
"""
txs = self.raw_query(query, authorization=True)['data']['user']
# convert strings to python objects
for t in txs['usdWithdrawals']:
utils.replace(t, "confirmTime", utils.parse_datetime_string)
utils.replace(t, "sendTime", utils.parse_datetime_string)
utils.replace(t, "usdAmount", utils.parse_float_string)
for t in txs["nmrWithdrawals"]:
utils.replace(t, "value", utils.parse_float_string)
for t in txs["nmrDeposits"]:
utils.replace(t, "value", utils.parse_float_string)
return txs | [
"def",
"get_transactions",
"(",
"self",
")",
":",
"query",
"=",
"\"\"\"\n query {\n user {\n nmrDeposits {\n from\n posted\n status\n to\n txHash\n value\n }\n ... | Get all your deposits and withdrawals.
Returns:
dict: lists of your NMR and USD transactions
The returned dict has the following structure:
* nmrDeposits (`list`) contains items with fields:
* from (`str`)
* posted (`bool`)
* status (`str`)
* to (`str`)
* txHash (`str`)
* value (`decimal.Decimal`)
* nmrWithdrawals"` (`list`) contains items with fields:
* from"` (`str`)
* posted"` (`bool`)
* status"` (`str`)
* to"` (`str`)
* txHash"` (`str`)
* value"` (`decimal.Decimal`)
* usdWithdrawals"` (`list`) contains items with fields:
* confirmTime"` (`datetime` or `None`)
* ethAmount"` (`str`)
* from"` (`str`)
* posted"` (`bool`)
* sendTime"` (`datetime`)
* status"` (`str`)
* to (`str`)
* txHash (`str`)
* usdAmount (`decimal.Decimal`)
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.get_transactions()
{'nmrDeposits': [
{'from': '0x54479..9ec897a',
'posted': True,
'status': 'confirmed',
'to': '0x0000000000000000000001',
'txHash': '0x52..e2056ab',
'value': Decimal('9.0')},
.. ],
'nmrWithdrawals': [
{'from': '0x0000000000000000..002',
'posted': True,
'status': 'confirmed',
'to': '0x00000000000..001',
'txHash': '0x1278..266c',
'value': Decimal('2.0')},
.. ],
'usdWithdrawals': [
{'confirmTime': datetime.datetime(2018, 2, 11, 17, 54, 2, 785430, tzinfo=tzutc()),
'ethAmount': '0.295780674909307710',
'from': '0x11.....',
'posted': True,
'sendTime': datetime.datetime(2018, 2, 11, 17, 53, 25, 235035, tzinfo=tzutc()),
'status': 'confirmed',
'to': '0x81.....',
'txHash': '0x3c....',
'usdAmount': Decimal('10.07')},
..]} | [
"Get",
"all",
"your",
"deposits",
"and",
"withdrawals",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L1005-L1112 | train | 29,187 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.get_stakes | def get_stakes(self):
"""List all your stakes.
Returns:
list of dicts: stakes
Each stake is a dict with the following fields:
* confidence (`decimal.Decimal`)
* roundNumber (`int`)
* tournamentId (`int`)
* soc (`decimal.Decimal`)
* insertedAt (`datetime`)
* staker (`str`): NMR adress used for staking
* status (`str`)
* txHash (`str`)
* value (`decimal.Decimal`)
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.get_stakes()
[{'confidence': Decimal('0.053'),
'insertedAt': datetime.datetime(2017, 9, 26, 8, 18, 36, 709000, tzinfo=tzutc()),
'roundNumber': 74,
'soc': Decimal('56.60'),
'staker': '0x0000000000000000000000000000000000003f9e',
'status': 'confirmed',
'tournamentId': 1,
'txHash': '0x1cbb985629552a0f57b98a1e30a5e7f101a992121db318cef02e02aaf0e91c95',
'value': Decimal('3.00')},
..
]
"""
query = """
query {
user {
stakeTxs {
confidence
insertedAt
roundNumber
tournamentId
soc
staker
status
txHash
value
}
}
}
"""
data = self.raw_query(query, authorization=True)['data']
stakes = data['user']['stakeTxs']
# convert strings to python objects
for s in stakes:
utils.replace(s, "insertedAt", utils.parse_datetime_string)
utils.replace(s, "soc", utils.parse_float_string)
utils.replace(s, "confidence", utils.parse_float_string)
utils.replace(s, "value", utils.parse_float_string)
return stakes | python | def get_stakes(self):
"""List all your stakes.
Returns:
list of dicts: stakes
Each stake is a dict with the following fields:
* confidence (`decimal.Decimal`)
* roundNumber (`int`)
* tournamentId (`int`)
* soc (`decimal.Decimal`)
* insertedAt (`datetime`)
* staker (`str`): NMR adress used for staking
* status (`str`)
* txHash (`str`)
* value (`decimal.Decimal`)
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.get_stakes()
[{'confidence': Decimal('0.053'),
'insertedAt': datetime.datetime(2017, 9, 26, 8, 18, 36, 709000, tzinfo=tzutc()),
'roundNumber': 74,
'soc': Decimal('56.60'),
'staker': '0x0000000000000000000000000000000000003f9e',
'status': 'confirmed',
'tournamentId': 1,
'txHash': '0x1cbb985629552a0f57b98a1e30a5e7f101a992121db318cef02e02aaf0e91c95',
'value': Decimal('3.00')},
..
]
"""
query = """
query {
user {
stakeTxs {
confidence
insertedAt
roundNumber
tournamentId
soc
staker
status
txHash
value
}
}
}
"""
data = self.raw_query(query, authorization=True)['data']
stakes = data['user']['stakeTxs']
# convert strings to python objects
for s in stakes:
utils.replace(s, "insertedAt", utils.parse_datetime_string)
utils.replace(s, "soc", utils.parse_float_string)
utils.replace(s, "confidence", utils.parse_float_string)
utils.replace(s, "value", utils.parse_float_string)
return stakes | [
"def",
"get_stakes",
"(",
"self",
")",
":",
"query",
"=",
"\"\"\"\n query {\n user {\n stakeTxs {\n confidence\n insertedAt\n roundNumber\n tournamentId\n soc\n staker\n ... | List all your stakes.
Returns:
list of dicts: stakes
Each stake is a dict with the following fields:
* confidence (`decimal.Decimal`)
* roundNumber (`int`)
* tournamentId (`int`)
* soc (`decimal.Decimal`)
* insertedAt (`datetime`)
* staker (`str`): NMR adress used for staking
* status (`str`)
* txHash (`str`)
* value (`decimal.Decimal`)
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.get_stakes()
[{'confidence': Decimal('0.053'),
'insertedAt': datetime.datetime(2017, 9, 26, 8, 18, 36, 709000, tzinfo=tzutc()),
'roundNumber': 74,
'soc': Decimal('56.60'),
'staker': '0x0000000000000000000000000000000000003f9e',
'status': 'confirmed',
'tournamentId': 1,
'txHash': '0x1cbb985629552a0f57b98a1e30a5e7f101a992121db318cef02e02aaf0e91c95',
'value': Decimal('3.00')},
..
] | [
"List",
"all",
"your",
"stakes",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L1114-L1173 | train | 29,188 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.submission_status | def submission_status(self, submission_id=None):
"""submission status of the last submission associated with the account.
Args:
submission_id (str): submission of interest, defaults to the last
submission done with the account
Returns:
dict: submission status with the following content:
* concordance (`dict`):
* pending (`bool`)
* value (`bool`): whether the submission is concordant
* consistency (`float`): consistency of the submission
* validationLogloss (`float`)
* validationAuroc (`float`)
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.upload_predictions()
>>> api.submission_status()
{'concordance': {'pending': False, 'value': True},
'consistency': 91.66666666666666,
'validationLogloss': 0.691733023121,
'validationAuroc': 0.52}
"""
if submission_id is None:
submission_id = self.submission_id
if submission_id is None:
raise ValueError('You need to submit something first or provide\
a submission ID')
query = '''
query($submission_id: String!) {
submissions(id: $submission_id) {
concordance {
pending
value
}
consistency
validationLogloss
validationAuroc
}
}
'''
variable = {'submission_id': submission_id}
data = self.raw_query(query, variable, authorization=True)
status = data['data']['submissions'][0]
return status | python | def submission_status(self, submission_id=None):
"""submission status of the last submission associated with the account.
Args:
submission_id (str): submission of interest, defaults to the last
submission done with the account
Returns:
dict: submission status with the following content:
* concordance (`dict`):
* pending (`bool`)
* value (`bool`): whether the submission is concordant
* consistency (`float`): consistency of the submission
* validationLogloss (`float`)
* validationAuroc (`float`)
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.upload_predictions()
>>> api.submission_status()
{'concordance': {'pending': False, 'value': True},
'consistency': 91.66666666666666,
'validationLogloss': 0.691733023121,
'validationAuroc': 0.52}
"""
if submission_id is None:
submission_id = self.submission_id
if submission_id is None:
raise ValueError('You need to submit something first or provide\
a submission ID')
query = '''
query($submission_id: String!) {
submissions(id: $submission_id) {
concordance {
pending
value
}
consistency
validationLogloss
validationAuroc
}
}
'''
variable = {'submission_id': submission_id}
data = self.raw_query(query, variable, authorization=True)
status = data['data']['submissions'][0]
return status | [
"def",
"submission_status",
"(",
"self",
",",
"submission_id",
"=",
"None",
")",
":",
"if",
"submission_id",
"is",
"None",
":",
"submission_id",
"=",
"self",
".",
"submission_id",
"if",
"submission_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'You need... | submission status of the last submission associated with the account.
Args:
submission_id (str): submission of interest, defaults to the last
submission done with the account
Returns:
dict: submission status with the following content:
* concordance (`dict`):
* pending (`bool`)
* value (`bool`): whether the submission is concordant
* consistency (`float`): consistency of the submission
* validationLogloss (`float`)
* validationAuroc (`float`)
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.upload_predictions()
>>> api.submission_status()
{'concordance': {'pending': False, 'value': True},
'consistency': 91.66666666666666,
'validationLogloss': 0.691733023121,
'validationAuroc': 0.52} | [
"submission",
"status",
"of",
"the",
"last",
"submission",
"associated",
"with",
"the",
"account",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L1175-L1224 | train | 29,189 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.upload_predictions | def upload_predictions(self, file_path, tournament=1):
"""Upload predictions from file.
Args:
file_path (str): CSV file with predictions that will get uploaded
tournament (int): ID of the tournament (optional, defaults to 1)
Returns:
str: submission_id
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.upload_predictions()
'93c46857-fed9-4594-981e-82db2b358daf'
"""
self.logger.info("uploading predictions...")
auth_query = '''
query($filename: String!
$tournament: Int!) {
submission_upload_auth(filename: $filename
tournament: $tournament) {
filename
url
}
}
'''
arguments = {'filename': os.path.basename(file_path),
'tournament': tournament}
submission_resp = self.raw_query(auth_query, arguments,
authorization=True)
submission_auth = submission_resp['data']['submission_upload_auth']
with open(file_path, 'rb') as fh:
requests.put(submission_auth['url'], data=fh.read())
create_query = '''
mutation($filename: String!
$tournament: Int!) {
create_submission(filename: $filename
tournament: $tournament) {
id
}
}
'''
arguments = {'filename': submission_auth['filename'],
'tournament': tournament}
create = self.raw_query(create_query, arguments, authorization=True)
self.submission_id = create['data']['create_submission']['id']
return self.submission_id | python | def upload_predictions(self, file_path, tournament=1):
"""Upload predictions from file.
Args:
file_path (str): CSV file with predictions that will get uploaded
tournament (int): ID of the tournament (optional, defaults to 1)
Returns:
str: submission_id
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.upload_predictions()
'93c46857-fed9-4594-981e-82db2b358daf'
"""
self.logger.info("uploading predictions...")
auth_query = '''
query($filename: String!
$tournament: Int!) {
submission_upload_auth(filename: $filename
tournament: $tournament) {
filename
url
}
}
'''
arguments = {'filename': os.path.basename(file_path),
'tournament': tournament}
submission_resp = self.raw_query(auth_query, arguments,
authorization=True)
submission_auth = submission_resp['data']['submission_upload_auth']
with open(file_path, 'rb') as fh:
requests.put(submission_auth['url'], data=fh.read())
create_query = '''
mutation($filename: String!
$tournament: Int!) {
create_submission(filename: $filename
tournament: $tournament) {
id
}
}
'''
arguments = {'filename': submission_auth['filename'],
'tournament': tournament}
create = self.raw_query(create_query, arguments, authorization=True)
self.submission_id = create['data']['create_submission']['id']
return self.submission_id | [
"def",
"upload_predictions",
"(",
"self",
",",
"file_path",
",",
"tournament",
"=",
"1",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"uploading predictions...\"",
")",
"auth_query",
"=",
"'''\n query($filename: String!\n $tournament: I... | Upload predictions from file.
Args:
file_path (str): CSV file with predictions that will get uploaded
tournament (int): ID of the tournament (optional, defaults to 1)
Returns:
str: submission_id
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.upload_predictions()
'93c46857-fed9-4594-981e-82db2b358daf' | [
"Upload",
"predictions",
"from",
"file",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L1226-L1273 | train | 29,190 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.check_submission_successful | def check_submission_successful(self, submission_id=None):
"""Check if the last submission passes submission criteria.
Args:
submission_id (str, optional): submission of interest, defaults to
the last submission done with the account
Return:
bool: True if the submission passed all checks, False otherwise.
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.upload_predictions("predictions.csv")
>>> api.check_submission_successful()
True
"""
status = self.submission_status(submission_id)
# need to cast to bool to not return None in some cases.
success = bool(status["concordance"]["value"])
return success | python | def check_submission_successful(self, submission_id=None):
"""Check if the last submission passes submission criteria.
Args:
submission_id (str, optional): submission of interest, defaults to
the last submission done with the account
Return:
bool: True if the submission passed all checks, False otherwise.
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.upload_predictions("predictions.csv")
>>> api.check_submission_successful()
True
"""
status = self.submission_status(submission_id)
# need to cast to bool to not return None in some cases.
success = bool(status["concordance"]["value"])
return success | [
"def",
"check_submission_successful",
"(",
"self",
",",
"submission_id",
"=",
"None",
")",
":",
"status",
"=",
"self",
".",
"submission_status",
"(",
"submission_id",
")",
"# need to cast to bool to not return None in some cases.",
"success",
"=",
"bool",
"(",
"status",... | Check if the last submission passes submission criteria.
Args:
submission_id (str, optional): submission of interest, defaults to
the last submission done with the account
Return:
bool: True if the submission passed all checks, False otherwise.
Example:
>>> api = NumerAPI(secret_key="..", public_id="..")
>>> api.upload_predictions("predictions.csv")
>>> api.check_submission_successful()
True | [
"Check",
"if",
"the",
"last",
"submission",
"passes",
"submission",
"criteria",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L1369-L1388 | train | 29,191 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.tournament_number2name | def tournament_number2name(self, number):
"""Translate tournament number to tournament name.
Args:
number (int): tournament number to translate
Returns:
name (str): name of the tournament or `None` if unknown.
Examples:
>>> NumerAPI().tournament_number2name(4)
'delta'
>>> NumerAPI().tournament_number2name(99)
None
"""
tournaments = self.get_tournaments()
d = {t['tournament']: t['name'] for t in tournaments}
return d.get(number, None) | python | def tournament_number2name(self, number):
"""Translate tournament number to tournament name.
Args:
number (int): tournament number to translate
Returns:
name (str): name of the tournament or `None` if unknown.
Examples:
>>> NumerAPI().tournament_number2name(4)
'delta'
>>> NumerAPI().tournament_number2name(99)
None
"""
tournaments = self.get_tournaments()
d = {t['tournament']: t['name'] for t in tournaments}
return d.get(number, None) | [
"def",
"tournament_number2name",
"(",
"self",
",",
"number",
")",
":",
"tournaments",
"=",
"self",
".",
"get_tournaments",
"(",
")",
"d",
"=",
"{",
"t",
"[",
"'tournament'",
"]",
":",
"t",
"[",
"'name'",
"]",
"for",
"t",
"in",
"tournaments",
"}",
"retu... | Translate tournament number to tournament name.
Args:
number (int): tournament number to translate
Returns:
name (str): name of the tournament or `None` if unknown.
Examples:
>>> NumerAPI().tournament_number2name(4)
'delta'
>>> NumerAPI().tournament_number2name(99)
None | [
"Translate",
"tournament",
"number",
"to",
"tournament",
"name",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L1390-L1407 | train | 29,192 |
uuazed/numerapi | numerapi/numerapi.py | NumerAPI.tournament_name2number | def tournament_name2number(self, name):
"""Translate tournament name to tournament number.
Args:
name (str): tournament name to translate
Returns:
number (int): number of the tournament or `None` if unknown.
Examples:
>>> NumerAPI().tournament_name2number('delta')
4
>>> NumerAPI().tournament_name2number('foo')
None
"""
tournaments = self.get_tournaments()
d = {t['name']: t['tournament'] for t in tournaments}
return d.get(name, None) | python | def tournament_name2number(self, name):
"""Translate tournament name to tournament number.
Args:
name (str): tournament name to translate
Returns:
number (int): number of the tournament or `None` if unknown.
Examples:
>>> NumerAPI().tournament_name2number('delta')
4
>>> NumerAPI().tournament_name2number('foo')
None
"""
tournaments = self.get_tournaments()
d = {t['name']: t['tournament'] for t in tournaments}
return d.get(name, None) | [
"def",
"tournament_name2number",
"(",
"self",
",",
"name",
")",
":",
"tournaments",
"=",
"self",
".",
"get_tournaments",
"(",
")",
"d",
"=",
"{",
"t",
"[",
"'name'",
"]",
":",
"t",
"[",
"'tournament'",
"]",
"for",
"t",
"in",
"tournaments",
"}",
"return... | Translate tournament name to tournament number.
Args:
name (str): tournament name to translate
Returns:
number (int): number of the tournament or `None` if unknown.
Examples:
>>> NumerAPI().tournament_name2number('delta')
4
>>> NumerAPI().tournament_name2number('foo')
None | [
"Translate",
"tournament",
"name",
"to",
"tournament",
"number",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L1409-L1426 | train | 29,193 |
uuazed/numerapi | numerapi/cli.py | staking_leaderboard | def staking_leaderboard(round_num=0, tournament=1):
"""Retrieves the staking competition leaderboard for the given round."""
click.echo(prettify(napi.get_staking_leaderboard(tournament=tournament,
round_num=round_num))) | python | def staking_leaderboard(round_num=0, tournament=1):
"""Retrieves the staking competition leaderboard for the given round."""
click.echo(prettify(napi.get_staking_leaderboard(tournament=tournament,
round_num=round_num))) | [
"def",
"staking_leaderboard",
"(",
"round_num",
"=",
"0",
",",
"tournament",
"=",
"1",
")",
":",
"click",
".",
"echo",
"(",
"prettify",
"(",
"napi",
".",
"get_staking_leaderboard",
"(",
"tournament",
"=",
"tournament",
",",
"round_num",
"=",
"round_num",
")"... | Retrieves the staking competition leaderboard for the given round. | [
"Retrieves",
"the",
"staking",
"competition",
"leaderboard",
"for",
"the",
"given",
"round",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/cli.py#L56-L59 | train | 29,194 |
uuazed/numerapi | numerapi/cli.py | rankings | def rankings(limit=20, offset=0):
"""Get the overall rankings."""
click.echo(prettify(napi.get_rankings(limit=limit, offset=offset))) | python | def rankings(limit=20, offset=0):
"""Get the overall rankings."""
click.echo(prettify(napi.get_rankings(limit=limit, offset=offset))) | [
"def",
"rankings",
"(",
"limit",
"=",
"20",
",",
"offset",
"=",
"0",
")",
":",
"click",
".",
"echo",
"(",
"prettify",
"(",
"napi",
".",
"get_rankings",
"(",
"limit",
"=",
"limit",
",",
"offset",
"=",
"offset",
")",
")",
")"
] | Get the overall rankings. | [
"Get",
"the",
"overall",
"rankings",
"."
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/cli.py#L91-L93 | train | 29,195 |
uuazed/numerapi | numerapi/cli.py | submission_filenames | def submission_filenames(round_num=None, tournament=None):
"""Get filenames of your submissions"""
click.echo(prettify(
napi.get_submission_filenames(tournament, round_num))) | python | def submission_filenames(round_num=None, tournament=None):
"""Get filenames of your submissions"""
click.echo(prettify(
napi.get_submission_filenames(tournament, round_num))) | [
"def",
"submission_filenames",
"(",
"round_num",
"=",
"None",
",",
"tournament",
"=",
"None",
")",
":",
"click",
".",
"echo",
"(",
"prettify",
"(",
"napi",
".",
"get_submission_filenames",
"(",
"tournament",
",",
"round_num",
")",
")",
")"
] | Get filenames of your submissions | [
"Get",
"filenames",
"of",
"your",
"submissions"
] | fc9dcc53b32ede95bfda1ceeb62aec1d67d26697 | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/cli.py#L110-L113 | train | 29,196 |
kirbs-/hide_code | hide_code/hide_code.py | install_bootstrapped_files | def install_bootstrapped_files(nb_path=None, server_config=True, DEBUG=False):
"""
Installs javascript and exporting server extensions in Jupyter notebook.
Args:
nb_path (string): Path to notebook module.
server_config (boolean): Install exporting server extensions.
DEBUG (boolean): Verbose mode.
"""
install_path = None
print('Starting hide_code.js install...')
current_dir = path.abspath(path.dirname(__file__))
config_dirs = j_path.jupyter_config_path()
notebook_module_path = Utils.get_notebook_module_dir()
# check for config directory with a "custom" folder
# TODO update this logic to check if custom.js file exists
for dir in config_dirs:
custom_dir = path.join(dir, "custom")
if path.isdir(custom_dir):
install_path = custom_dir
break
# last ditch effort in case jupyter config directories don't contain custom/custom.js
if install_path == None:
print("No config directories contain \"custom\" folder. Trying Jupyter notebook module path...")
install_path = path.join(notebook_module_path, "static", "custom")
if nb_path != None:
install_path = nb_path
print("Using argument supplied path: " + install_path)
if DEBUG:
print(install_path)
# copy js into static/custom directory in Jupyter/iPython directory
if path.isdir(install_path):
shutil.copyfile(path.join(current_dir, "hide_code.js"), path.join(install_path, "hide_code.js"))
print('Copying hide_code.js to ' + install_path)
# add require to end of custom.js to auto-load on notebook startup
print("Attempting to configure custom.js to auto-load hide_code.js...")
try:
with open(path.join(current_dir, "auto-load.txt")) as auto:
auto_load_txt = auto.read();
auto_loaded = False
# check if auto-load.txt is already in custom.js
with open(path.join(install_path, "custom.js"), 'r') as customJS:
if auto_load_txt in customJS.read():
auto_loaded = True
print("Custom.js already configured to auto-load hide_code.js.")
if not auto_loaded: # append auto load require to end of custom.js
with open(path.join(install_path, "custom.js"), 'a') as customJS:
customJS.write(auto_load_txt)
print("Configured custom.js to auto-load hide_code.js.")
except:
print("Custom.js not in custom directory.")
else:
print('Unable to install into ' + install_path)
print('Directory doesn\'t exist.')
print('Make sure Jupyter is installed.')
if server_config:
print("Attempting to configure auto-loading for hide_code export handlers.")
try:
# Activate the Python server extension
server_cm = ConfigManager(config_dir=j_path.jupyter_config_dir())
cfg = server_cm.get('jupyter_notebook_config')
server_extensions = (cfg.setdefault('NotebookApp', {})
.setdefault('server_extensions', [])
)
extension = 'hide_code.hide_code'
if extension not in server_extensions:
cfg['NotebookApp']['server_extensions'] += [extension]
server_cm.update('jupyter_notebook_config', cfg)
print('Configured jupyter to auto-load hide_code export handlers.')
else:
print("Jupyter already configured to auto-load export handlers.")
except:
print('Unable to install server extension.') | python | def install_bootstrapped_files(nb_path=None, server_config=True, DEBUG=False):
"""
Installs javascript and exporting server extensions in Jupyter notebook.
Args:
nb_path (string): Path to notebook module.
server_config (boolean): Install exporting server extensions.
DEBUG (boolean): Verbose mode.
"""
install_path = None
print('Starting hide_code.js install...')
current_dir = path.abspath(path.dirname(__file__))
config_dirs = j_path.jupyter_config_path()
notebook_module_path = Utils.get_notebook_module_dir()
# check for config directory with a "custom" folder
# TODO update this logic to check if custom.js file exists
for dir in config_dirs:
custom_dir = path.join(dir, "custom")
if path.isdir(custom_dir):
install_path = custom_dir
break
# last ditch effort in case jupyter config directories don't contain custom/custom.js
if install_path == None:
print("No config directories contain \"custom\" folder. Trying Jupyter notebook module path...")
install_path = path.join(notebook_module_path, "static", "custom")
if nb_path != None:
install_path = nb_path
print("Using argument supplied path: " + install_path)
if DEBUG:
print(install_path)
# copy js into static/custom directory in Jupyter/iPython directory
if path.isdir(install_path):
shutil.copyfile(path.join(current_dir, "hide_code.js"), path.join(install_path, "hide_code.js"))
print('Copying hide_code.js to ' + install_path)
# add require to end of custom.js to auto-load on notebook startup
print("Attempting to configure custom.js to auto-load hide_code.js...")
try:
with open(path.join(current_dir, "auto-load.txt")) as auto:
auto_load_txt = auto.read();
auto_loaded = False
# check if auto-load.txt is already in custom.js
with open(path.join(install_path, "custom.js"), 'r') as customJS:
if auto_load_txt in customJS.read():
auto_loaded = True
print("Custom.js already configured to auto-load hide_code.js.")
if not auto_loaded: # append auto load require to end of custom.js
with open(path.join(install_path, "custom.js"), 'a') as customJS:
customJS.write(auto_load_txt)
print("Configured custom.js to auto-load hide_code.js.")
except:
print("Custom.js not in custom directory.")
else:
print('Unable to install into ' + install_path)
print('Directory doesn\'t exist.')
print('Make sure Jupyter is installed.')
if server_config:
print("Attempting to configure auto-loading for hide_code export handlers.")
try:
# Activate the Python server extension
server_cm = ConfigManager(config_dir=j_path.jupyter_config_dir())
cfg = server_cm.get('jupyter_notebook_config')
server_extensions = (cfg.setdefault('NotebookApp', {})
.setdefault('server_extensions', [])
)
extension = 'hide_code.hide_code'
if extension not in server_extensions:
cfg['NotebookApp']['server_extensions'] += [extension]
server_cm.update('jupyter_notebook_config', cfg)
print('Configured jupyter to auto-load hide_code export handlers.')
else:
print("Jupyter already configured to auto-load export handlers.")
except:
print('Unable to install server extension.') | [
"def",
"install_bootstrapped_files",
"(",
"nb_path",
"=",
"None",
",",
"server_config",
"=",
"True",
",",
"DEBUG",
"=",
"False",
")",
":",
"install_path",
"=",
"None",
"print",
"(",
"'Starting hide_code.js install...'",
")",
"current_dir",
"=",
"path",
".",
"abs... | Installs javascript and exporting server extensions in Jupyter notebook.
Args:
nb_path (string): Path to notebook module.
server_config (boolean): Install exporting server extensions.
DEBUG (boolean): Verbose mode. | [
"Installs",
"javascript",
"and",
"exporting",
"server",
"extensions",
"in",
"Jupyter",
"notebook",
"."
] | 351cc4146c9c111c39725e068690a0e4853f9876 | https://github.com/kirbs-/hide_code/blob/351cc4146c9c111c39725e068690a0e4853f9876/hide_code/hide_code.py#L213-L295 | train | 29,197 |
kirbs-/hide_code | hide_code/hide_code.py | ipynb_file_name | def ipynb_file_name(params):
"""
Returns OS path to notebook based on route parameters.
"""
global notebook_dir
p = notebook_dir + [param.replace('/', '') for param in params if param is not None]
return path.join(*p) | python | def ipynb_file_name(params):
"""
Returns OS path to notebook based on route parameters.
"""
global notebook_dir
p = notebook_dir + [param.replace('/', '') for param in params if param is not None]
return path.join(*p) | [
"def",
"ipynb_file_name",
"(",
"params",
")",
":",
"global",
"notebook_dir",
"p",
"=",
"notebook_dir",
"+",
"[",
"param",
".",
"replace",
"(",
"'/'",
",",
"''",
")",
"for",
"param",
"in",
"params",
"if",
"param",
"is",
"not",
"None",
"]",
"return",
"pa... | Returns OS path to notebook based on route parameters. | [
"Returns",
"OS",
"path",
"to",
"notebook",
"based",
"on",
"route",
"parameters",
"."
] | 351cc4146c9c111c39725e068690a0e4853f9876 | https://github.com/kirbs-/hide_code/blob/351cc4146c9c111c39725e068690a0e4853f9876/hide_code/hide_code.py#L314-L320 | train | 29,198 |
pytroll/pyspectral | pyspectral/radiance_tb_conversion.py | radiance2tb | def radiance2tb(rad, wavelength):
"""
Get the Tb from the radiance using the Planck function
rad:
Radiance in SI units
wavelength:
Wavelength in SI units (meter)
"""
from pyspectral.blackbody import blackbody_rad2temp as rad2temp
return rad2temp(wavelength, rad) | python | def radiance2tb(rad, wavelength):
"""
Get the Tb from the radiance using the Planck function
rad:
Radiance in SI units
wavelength:
Wavelength in SI units (meter)
"""
from pyspectral.blackbody import blackbody_rad2temp as rad2temp
return rad2temp(wavelength, rad) | [
"def",
"radiance2tb",
"(",
"rad",
",",
"wavelength",
")",
":",
"from",
"pyspectral",
".",
"blackbody",
"import",
"blackbody_rad2temp",
"as",
"rad2temp",
"return",
"rad2temp",
"(",
"wavelength",
",",
"rad",
")"
] | Get the Tb from the radiance using the Planck function
rad:
Radiance in SI units
wavelength:
Wavelength in SI units (meter) | [
"Get",
"the",
"Tb",
"from",
"the",
"radiance",
"using",
"the",
"Planck",
"function"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/radiance_tb_conversion.py#L249-L259 | train | 29,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.