docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Retrieve a list of UniProt sites parsed from the feature file
Sites are defined here: http://www.uniprot.org/help/site and here: http://www.uniprot.org/help/function_section
Args:
uniprot_id: Valid UniProt ID
Returns: | def uniprot_sites(uniprot_id):
r = requests.post('http://www.uniprot.org/uniprot/%s.gff' % uniprot_id)
gff = StringIO(r.content.decode('utf-8'))
feats = list(GFF.parse(gff))
if len(feats) > 1:
log.warning('Too many sequences in GFF')
else:
return feats[0].features | 548,302 |
Download a UniProt file for a UniProt ID/ACC
Args:
uniprot_id: Valid UniProt ID
filetype: txt, fasta, xml, rdf, or gff
outdir: Directory to download the file
Returns:
str: Absolute path to file | def download_uniprot_file(uniprot_id, filetype, outdir='', force_rerun=False):
my_file = '{}.{}'.format(uniprot_id, filetype)
url = 'http://www.uniprot.org/uniprot/{}'.format(my_file)
outfile = op.join(outdir, my_file)
if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
urlretr... | 548,303 |
Parse a raw UniProt metadata file and return a dictionary.
Args:
infile: Path to metadata file
Returns:
dict: Metadata dictionary | def parse_uniprot_txt_file(infile):
uniprot_metadata_dict = {}
metadata = old_parse_uniprot_txt_file(infile)
metadata_keys = list(metadata.keys())
if metadata_keys:
metadata_key = metadata_keys[0]
else:
return uniprot_metadata_dict
uniprot_metadata_dict['seq_len'] = len(s... | 548,304 |
Provide pointers to the paths of the metadata file
Args:
m_path: Path to metadata file | def metadata_path(self, m_path):
if not m_path:
self.metadata_dir = None
self.metadata_file = None
else:
if not op.exists(m_path):
raise OSError('{}: file does not exist!'.format(m_path))
if not op.dirname(m_path):
... | 548,309 |
Process a NACCESS or freesasa RSA output file. Adapted from Biopython NACCESS modele.
Args:
rsa_outfile (str): Path to RSA output file
ignore_hets (bool): If HETATMs should be excluded from the final dictionary. This is extremely important
when loading this information into a ChainP... | def parse_rsa_data(rsa_outfile, ignore_hets=True):
naccess_rel_dict = OrderedDict()
with open(rsa_outfile, 'r') as f:
for line in f:
if line.startswith('RES'):
res_name = line[4:7]
chain_id = line[8]
resseq = int(line[9:13])
... | 548,317 |
Save all attributes that start with "df" into a specified directory.
Args:
outdir (str): Path to output directory
prefix (str): Prefix that dataframe attributes start with | def save_dataframes(self, outdir, prefix='df_'):
# Get list of attributes that start with "df_"
dfs = list(filter(lambda x: x.startswith(prefix), dir(self)))
counter = 0
for df in dfs:
outpath = ssbio.utils.outfile_maker(inname=df, outext='.csv', outdir=outdir)
... | 548,320 |
Parse a DOCK6 mol2 output file, return a Pandas DataFrame of the results.
Args:
mol2_outpath (str): Path to mol2 output file
Returns:
DataFrame: Pandas DataFrame of the results | def parse_results_mol2(mol2_outpath):
docked_ligands = pd.DataFrame()
lines = [line.strip() for line in open(mol2_outpath, 'r')]
props = {}
for i, line in enumerate(lines):
if line.startswith('########## Name:'):
ligand = line.strip().strip('##########').replace(' ', '').repla... | 548,333 |
Provide pointers to the paths of the structure file
Args:
path: Path to structure file | def structure_path(self, path):
if not path:
self.structure_dir = None
self.structure_file = None
else:
if not op.exists(path):
raise OSError('{}: file does not exist!'.format(path))
if not op.dirname(path):
self.... | 548,339 |
Prepare a PDB file for docking by first converting it to mol2 format.
Args:
force_rerun (bool): If method should be rerun even if output file exists | def dockprep(self, force_rerun=False):
log.debug('{}: running dock preparation...'.format(self.id))
prep_mol2 = op.join(self.dock_dir, '{}_prep.mol2'.format(self.id))
prep_py = op.join(self.dock_dir, "prep.py")
if ssbio.utils.force_rerun(flag=force_rerun, outfile=prep_mol2):
... | 548,340 |
Isolate the receptor by stripping everything except protein and specified ligands.
Args:
keep_ligands (str, list): Ligand(s) to keep in PDB file
force_rerun (bool): If method should be rerun even if output file exists | def protein_only_and_noH(self, keep_ligands=None, force_rerun=False):
log.debug('{}: running protein receptor isolation...'.format(self.id))
if not self.dockprep_path:
return ValueError('Please run dockprep')
receptor_mol2 = op.join(self.dock_dir, '{}_receptor.mol2'.format... | 548,341 |
Create surface representation (dms file) of receptor
Args:
force_rerun (bool): If method should be rerun even if output file exists | def dms_maker(self, force_rerun=False):
log.debug('{}: running surface representation maker...'.format(self.id))
if not self.receptorpdb_path:
return ValueError('Please run protein_only_and_noH')
dms = op.join(self.dock_dir, '{}_receptor.dms'.format(self.id))
if s... | 548,342 |
Create sphere representation (sph file) of receptor from the surface representation
Args:
force_rerun (bool): If method should be rerun even if output file exists | def sphgen(self, force_rerun=False):
log.debug('{}: running sphere generation...'.format(self.id))
if not self.dms_path:
return ValueError('Please run dms_maker')
sph = op.join(self.dock_dir, '{}_receptor.sph'.format(self.id))
insph = op.join(self.dock_dir, 'INSPH'... | 548,343 |
Select spheres based on binding site residues
Args:
radius (int, float): Radius around binding residues to dock to
force_rerun (bool): If method should be rerun even if output file exists | def sphere_selector_using_residues(self, radius, force_rerun=False):
log.debug('{}: running sphere selector...'.format(self.id))
if not self.sphgen_path or not self.bindingsite_path:
return ValueError('Please run sphgen and binding_site_mol2')
selsph = op.join(self.dock_di... | 548,345 |
Create the dummy PDB box around the selected spheres.
Args:
force_rerun (bool): If method should be rerun even if output file exists | def showbox(self, force_rerun=False):
log.debug('{}: running box maker...'.format(self.id))
if not self.sphsel_path:
return ValueError('Please run sphere_selector_using_residues')
boxfile = op.join(self.dock_dir, "{}_box.pdb".format(self.id))
boxscript = op.join(se... | 548,346 |
Create the scoring grid within the dummy box.
Args:
force_rerun (bool): If method should be rerun even if output file exists | def grid(self, force_rerun=False):
log.debug('{}: running grid maker...'.format(self.id))
if not self.receptormol2_path or not self.box_path:
return ValueError('Please run protein_only_and_noH and showbox')
gridscript = op.join(self.dock_dir, "{}_grid.in".format(self.id))
... | 548,347 |
Dock a ligand to the protein.
Args:
ligand_path (str): Path to ligand (mol2 format) to dock to protein
force_rerun (bool): If method should be rerun even if output file exists | def do_dock6_flexible(self, ligand_path, force_rerun=False):
log.debug('{}: running DOCK6...'.format(self.id))
ligand_name = os.path.basename(ligand_path).split('.')[0]
in_name = op.join(self.dock_dir, "{}_{}_flexdock.in".format(self.id, ligand_name))
out_name = op.join(self.do... | 548,348 |
Parse a MetalPDB .lig file and return a tuple of the chain ID it represents, along with metal binding information.
Args:
metalpdb_lig_file (str): Path to .lig file
Returns:
tuple: (str, dict) of the chain ID and the parsed metal binding site information | def get_metalpdb_info(metalpdb_lig_file):
pdb_metals = ['CU', 'ZN', 'MN', 'FE', 'MG', 'CO', 'SE', 'YB', 'SF4', 'FES', 'F3S', 'NI', 'FE2']
# Information to collect
coordination_number = 0
endogenous_ligands = []
exogenous_ligands = []
# Load the structure
ss = StructProp(ident='metalp... | 548,350 |
Summarize two alignment strings in a dataframe.
Args:
a_aln_seq (str): Aligned sequence string
b_aln_seq (str): Aligned sequence string
a_seq_id (str): Optional ID of a_seq
b_seq_id (str): Optional ID of b_aln_seq
Returns:
DataFrame: a per-residue level annotation of th... | def get_alignment_df(a_aln_seq, b_aln_seq, a_seq_id=None, b_seq_id=None):
if len(a_aln_seq) != len(b_aln_seq):
raise ValueError('Sequence lengths not equal - was an alignment run?')
if not a_seq_id:
a_seq_id = 'a_seq'
if not b_seq_id:
b_seq_id = 'b_seq'
a_aln_seq = ssbio.p... | 548,355 |
Get a Pandas DataFrame of the Needle alignment results. Contains all positions of the sequences.
Args:
alignment_file:
a_seq_id: Optional specification of the ID of the reference sequence
b_seq_id: Optional specification of the ID of the aligned sequence
Returns:
Pandas DataFra... | def get_alignment_df_from_file(alignment_file, a_seq_id=None, b_seq_id=None):
alignments = list(AlignIO.parse(alignment_file, "emboss"))
alignment_df = pd.DataFrame(columns=['id_a', 'id_b', 'type', 'id_a_aa', 'id_a_pos', 'id_b_aa', 'id_b_pos'])
for alignment in alignments:
if not a_seq_id:
... | 548,356 |
Get a list of residue numbers (in the original sequence's numbering) that are mutated
Args:
aln_df (DataFrame): Alignment DataFrame
just_resnums: If only the residue numbers should be returned, instead of a list of tuples of
(original_residue, resnum, mutated_residue)
Returns:
... | def get_mutations(aln_df):
mutation_df = aln_df[aln_df['type'] == 'mutation']
tuples = []
if not mutation_df.empty:
subset = mutation_df[['id_a_aa', 'id_a_pos', 'id_b_aa']]
subset['id_a_pos'] = subset['id_a_pos'].astype(int)
tuples = [tuple(x) for x in subset.values]
return ... | 548,357 |
Get a list of residue numbers (in the original sequence's numbering) that are unresolved
Args:
aln_df (DataFrame): Alignment DataFrame
Returns:
list: Residue numbers that are mutated | def get_unresolved(aln_df):
unresolved_df = aln_df[aln_df['type'] == 'unresolved']
unresolved = []
if not unresolved_df.empty:
unresolved_df['id_a_pos'] = unresolved_df['id_a_pos'].astype(int)
unresolved = unresolved_df.id_a_pos.tolist()
return unresolved | 548,358 |
Get a report of a pairwise alignment.
Args:
reference_seq_aln (str, Seq, SeqRecord): Reference sequence, alignment form
other_seq_aln (str, Seq, SeqRecord): Other sequence, alignment form
Returns:
dict: Dictionary of information on mutations, insertions, sequence identity, etc. | def pairwise_alignment_stats(reference_seq_aln, other_seq_aln):
if len(reference_seq_aln) != len(other_seq_aln):
raise ValueError('Sequence lengths not equal - was an alignment run?')
reference_seq_aln = ssbio.protein.sequence.utils.cast_to_str(reference_seq_aln)
other_seq_aln = ssbio.protein.... | 548,362 |
Reads in a needle alignment file and spits out statistics of the alignment.
Args:
infile (str): Alignment file name
Returns:
dict: alignment_properties - a dictionary telling you the number of gaps, identity, etc. | def needle_statistics(infile):
alignments = list(AlignIO.parse(infile, "emboss"))
alignment_properties = defaultdict(dict)
with open(infile) as f:
line = f.readline()
for i in range(len(alignments)):
while line.rstrip() != "#=======================================":
... | 548,363 |
Reads in a needle alignment file and returns an AlignIO object with annotations
Args:
infile (str): Alignment file name
Returns:
AlignIO: annotated AlignIO object | def needle_statistics_alignio(infile):
alignments = list(AlignIO.parse(infile, "emboss"))
if len(alignments) > 1:
raise ValueError('Alignment file contains more than one pairwise alignment')
alignment = alignments[0]
with open(infile) as f:
line = f.readline()
for i in ... | 548,364 |
Run FoldX RepairPDB on this PDB file.
Original command::
foldx --command=RepairPDB --pdb=4bxi.pdb
Args:
silent (bool): If FoldX output should be silenced from printing to the shell.
force_rerun (bool): If FoldX RepairPDB should be rerun even if a repaired file exis... | def run_repair_pdb(self, silent=False, force_rerun=False):
# Create RepairPDB command
foldx_repair_pdb = 'foldx --command=RepairPDB --pdb={}'.format(self.pdb_file)
# Repaired PDB output file name
foldx_repair_outfile = '{}_Repair.pdb'.format(op.splitext(self.pdb_file)[0])
... | 548,370 |
Create the FoldX file 'individual_list.txt' to run BuildModel upon.
Args:
list_of_tuples (list): A list of tuples indicating mutation groups to carry out BuildModel upon. Example::
[
(('N', 'A', 308, 'S'), ('S', 'A', 320, 'T'), ('S', 'A', 321, 'H')), # Mutation... | def create_mutation_file(self, list_of_tuples):
self.mutation_infile = op.join(self.foldx_dir, 'individual_list.txt')
idx = 1
with open(self.mutation_infile, 'w') as f:
for mutant_group in list_of_tuples:
# Write the mutation string to the file
... | 548,371 |
Run FoldX BuildModel command with a mutant file input.
Original command::
foldx --command=BuildModel --pdb=4bxi_Repair.pdb --mutant-file=individual_list.txt --numberOfRuns=5
Args:
num_runs (int):
silent (bool): If FoldX output should be silenced from printing to th... | def run_build_model(self, num_runs=5, silent=False, force_rerun=False):
# BuildModel output files
self.mutation_ddG_avg_outfile = 'Average_{}.fxout'.format(op.splitext(self.repaired_pdb_outfile)[0])
self.mutation_ddG_raw_outfile = 'Raw_{}.fxout'.format(op.splitext(self.repaired_pdb_outf... | 548,373 |
Run MSMS (using Biopython) on a Biopython Structure Model.
Depths are in units Angstroms. 1A = 10^-10 m = 1nm. Returns a dictionary of::
{
chain_id:{
resnum1_id: (res_depth, ca_depth),
resnum2_id: (res_depth, ca_depth)
}
... | def get_msms_df(model, pdb_id, outfile=None, outdir=None, outext='_msms.df', force_rerun=False):
# XTODO: need to deal with temporary surface/vertex files in tmp directory when running on a large scale --
# XTODO: will run into inode limits! Also, some valuable information is in these MSMS output files tha... | 548,380 |
Parse an MMTF file and return basic header-like information.
Args:
infile (str): Path to MMTF file
Returns:
dict: Dictionary of parsed header
Todo:
- Can this be sped up by not parsing the 3D coordinate info somehow?
- OR just store the sequences when this happens since it... | def parse_mmtf_header(infile):
infodict = {}
mmtf_decoder = mmtf.parse(infile)
infodict['date'] = mmtf_decoder.deposition_date
infodict['release_date'] = mmtf_decoder.release_date
try:
infodict['experimental_method'] = [x.decode() for x in mmtf_decoder.experimental_methods]
except ... | 548,385 |
Download a mmCIF header file from the RCSB PDB by ID.
Args:
pdb_id: PDB ID
outdir: Optional output directory, default is current working directory
force_rerun: If the file should be downloaded again even if it exists
Returns:
str: Path to outfile | def download_mmcif_header(pdb_id, outdir='', force_rerun=False):
# TODO: keep an eye on https://github.com/biopython/biopython/pull/943 Biopython PR#493 for functionality of this
# method in biopython. extra file types have not been added to biopython download yet
pdb_id = pdb_id.lower()
file_type... | 548,386 |
Parse a couple important fields from the mmCIF file format with some manual curation of ligands.
If you want full access to the mmCIF file just use the MMCIF2Dict class in Biopython.
Args:
infile: Path to mmCIF file
Returns:
dict: Dictionary of parsed header | def parse_mmcif_header(infile):
from Bio.PDB.MMCIF2Dict import MMCIF2Dict
newdict = {}
try:
mmdict = MMCIF2Dict(infile)
except ValueError as e:
log.exception(e)
return newdict
chemical_ids_exclude = ['HOH']
chemical_types_exclude = ['l-peptide linking','peptide lin... | 548,387 |
Download the SIFTS file for a PDB ID.
Args:
pdb_id (str): PDB ID
outdir (str): Output directory, current working directory if not specified.
force_rerun (bool): If the file should be downloaded again even if it exists
Returns:
str: Path to downloaded file | def download_sifts_xml(pdb_id, outdir='', force_rerun=False):
baseURL = 'ftp://ftp.ebi.ac.uk/pub/databases/msd/sifts/xml/'
filename = '{}.xml.gz'.format(pdb_id.lower())
outfile = op.join(outdir, filename.split('.')[0] + '.sifts.xml')
if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
... | 548,388 |
Download a structure from the RCSB PDB by ID. Specify the file type desired.
Args:
pdb_id: PDB ID
file_type: pdb, pdb.gz, mmcif, cif, cif.gz, xml.gz, mmtf, mmtf.gz
outdir: Optional output directory
only_header: If only the header file should be downloaded
force_rerun: If the... | def download_structure(pdb_id, file_type, outdir='', only_header=False, force_rerun=False):
# method in biopython. extra file types have not been added to biopython download yet
pdb_id = pdb_id.lower()
file_type = file_type.lower()
file_types = ['pdb', 'pdb.gz', 'mmcif', 'cif', 'cif.gz', 'xml.gz',... | 548,397 |
Parses all PROCHECK files in a directory and returns a Pandas DataFrame of the results
Args:
quality_directory: path to directory with PROCHECK output (.sum files)
Returns:
Pandas DataFrame: Summary of PROCHECK results | def parse_procheck(quality_directory):
# TODO: save as dict instead, offer df as option
# TODO: parse for one file instead
procheck_summaries = glob.glob(os.path.join(quality_directory, '*.sum'))
if len(procheck_summaries) == 0:
return pd.DataFrame()
all_procheck = {}
for summ i... | 548,403 |
Parse a PSQS result file and returns a Pandas DataFrame of the results
Args:
psqs_results_file: Path to psqs results file
Returns:
Pandas DataFrame: Summary of PSQS results | def parse_psqs(psqs_results_file):
# TODO: generalize column names for all results, save as dict instead
psqs_results = pd.read_csv(psqs_results_file, sep='\t', header=None)
psqs_results['pdb_file'] = psqs_results[0].apply(lambda x: str(x).strip('./').strip('.pdb'))
psqs_results = psqs_results.re... | 548,404 |
Return a DictList of only specified types in the sequences attribute.
Args:
seq_type (SeqProp): Object type
Returns:
DictList: A filtered DictList of specified object type only | def filter_sequences(self, seq_type):
return DictList(x for x in self.sequences if isinstance(x, seq_type)) | 548,413 |
Automatically consolidate loaded sequences (manual, UniProt, or KEGG) and set a single representative
sequence.
Manually set representative sequences override all existing mappings. UniProt mappings override KEGG mappings
except when KEGG mappings have PDBs associated with them and UniProt does... | def set_representative_sequence(self, force_rerun=False):
if len(self.sequences) == 0:
log.error('{}: no sequences mapped'.format(self.id))
return self.representative_sequence
kegg_mappings = self.filter_sequences(KEGGProp)
if len(kegg_mappings) > 0:
... | 548,418 |
Write all the stored sequences as a single FASTA file. By default, sets IDs to model gene IDs.
Args:
outname (str): Name of the output FASTA file without the extension
outdir (str): Path to output directory for the file, default is the sequences directory | def write_all_sequences_file(self, outname, outdir=None):
if not outdir:
outdir = self.sequence_dir
if not outdir:
raise ValueError('Output directory must be specified')
outfile = op.join(outdir, outname + '.faa')
SeqIO.write(self.sequences, out... | 548,421 |
Run Biopython ProteinAnalysis and EMBOSS pepstats to summarize basic statistics of the protein sequences.
Results are stored in the protein's respective SeqProp objects at ``.annotations``
Args:
representative_only (bool): If analysis should only be run on the representative sequence | def get_sequence_properties(self, clean_seq=False, representative_only=True):
if representative_only:
# Check if a representative sequence was set
if not self.representative_sequence:
log.warning('{}: no representative sequence set, cannot get sequence properties... | 548,422 |
Run Biopython ProteinAnalysis with a sliding window to calculate a given property.
Results are stored in the protein's respective SeqProp objects at ``.letter_annotations``
Args:
scale (str): Scale name
window (int): Sliding window size
representative_only (bool): If... | def get_sequence_sliding_window_properties(self, scale, window, representative_only=True):
if representative_only:
# Check if a representative sequence was set
if not self.representative_sequence:
log.warning('{}: no representative sequence set, cannot get sequen... | 548,423 |
Run MSMS on structures and store calculations.
Annotations are stored in the protein structure's chain sequence at:
``<chain_prop>.seq_record.letter_annotations['*-msms']``
Args:
representative_only (bool): If analysis should only be run on the representative structure
... | def get_msms_annotations(self, representative_only=True, force_rerun=False):
if representative_only:
if self.representative_structure:
try:
self.representative_structure.get_msms_annotations(outdir=self.structure_dir, force_rerun=force_rerun)
... | 548,449 |
Run Biopython's disulfide bridge finder and store found bridges.
Annotations are stored in the protein structure's chain sequence at:
``<chain_prop>.seq_record.annotations['SSBOND-biopython']``
Args:
representative_only (bool): If analysis should only be run on the representative s... | def find_disulfide_bridges(self, representative_only=True):
if representative_only:
if self.representative_structure:
try:
self.representative_structure.find_disulfide_bridges()
except KeyError:
log.error('{}: unable to... | 548,450 |
Run Biopython ProteinAnalysis and EMBOSS pepstats to summarize basic statistics of the protein sequences.
Results are stored in the protein's respective SeqProp objects at ``.annotations``
Args:
representative_only (bool): If analysis should only be run on the representative sequence | def get_all_disorder_predictions(self, iupred_path='/home/nathan/software/iupred/',
iupred_exec='iupred', disembl_cmd='/home/nathan/software/DisEMBL-1.4/DisEMBL.py',
representative_only=True):
if representative_only:
... | 548,475 |
Parse the main init.dat file which contains the modeling results
The first line of the file init.dat contains stuff like::
"120 easy 40 8"
The other lines look like this::
" 161 11.051 1 1guqA MUSTER"
and getting the first 10 gives you the top 10 templates us... | def parse_init_dat(infile):
# TODO: would be nice to get top 10 templates instead of just the top
init_dict = {}
log.debug('{}: reading file...'.format(infile))
with open(infile, 'r') as f:
# Get first 2 lines of file
head = [next(f).strip() for x in range(2)]
summary = head[... | 548,477 |
Parse the cscore file to return a dictionary of scores.
Args:
infile (str): Path to cscore
Returns:
dict: Dictionary of scores | def parse_cscore(infile):
cscore_dict = {}
with open(infile, 'r') as f:
for ll in f.readlines():
# Look for the first line that starts with model1
if ll.lower().startswith('model1'):
l = ll.split()
cscore = l[1]
tmscore_full... | 548,478 |
Parse the EC.dat output file of COACH and return a dataframe of results
EC.dat contains the predicted EC number and active residues.
The columns are: PDB_ID, TM-score, RMSD, Sequence identity,
Coverage, Confidence score, EC number, and Active site residues
Args:
infile (str): Path to EC.dat
... | def parse_coach_ec_df(infile):
ec_df = pd.read_table(infile, delim_whitespace=True,
names=['pdb_template', 'tm_score', 'rmsd', 'seq_ident', 'seq_coverage',
'c_score', 'ec_number', 'binding_residues'])
ec_df['pdb_template_id'] = ec_df['pdb_templat... | 548,480 |
Copy the raw information from I-TASSER modeling to a new folder.
Copies all files in the list _attrs_to_copy.
Args:
copy_to_dir (str): Directory to copy the minimal set of results per sequence.
rename_model_to (str): New file name (without extension)
force_rerun (bo... | def copy_results(self, copy_to_dir, rename_model_to=None, force_rerun=False):
# Save path to the structure and copy it if specified
if not rename_model_to:
rename_model_to = self.model_to_use
new_model_path = op.join(copy_to_dir, '{}.pdb'.format(rename_model_to))
i... | 548,484 |
Initialize the parameters which indicate what mutations will occur
Args:
chain:
residue_number:
mutate_to: | def __init__(self, mutation_list):
self.mutation_list = [(i[0], int(i[1]), self._standard_resname(i[2])) for i in mutation_list]
self.chains_and_residues = [(i[0], int(i[1])) for i in mutation_list] | 548,490 |
Load a COBRApy Model object into the GEM-PRO project.
Args:
model (Model): COBRApy ``Model`` object | def load_cobra_model(self, model):
self.model = ModelPro(model)
for g in self.model.genes:
if self.genes_dir:
g.root_dir = self.genes_dir
g.protein.pdb_file_type = self.pdb_file_type
self.genes = self.model.genes
log.info('{}: loaded mode... | 548,497 |
Add gene IDs manually into the GEM-PRO project.
Args:
genes_list (list): List of gene IDs as strings. | def add_gene_ids(self, genes_list):
orig_num_genes = len(self.genes)
for g in list(set(genes_list)):
if not self.genes.has_id(g):
new_gene = GenePro(id=g, pdb_file_type=self.pdb_file_type, root_dir=self.genes_dir)
if self.model:
s... | 548,503 |
Automatically consolidate loaded sequences (manual, UniProt, or KEGG) and set a single representative sequence.
Manually set representative sequences override all existing mappings. UniProt mappings override KEGG mappings
except when KEGG mappings have PDBs associated with them and UniProt doesn't.
... | def set_representative_sequence(self, force_rerun=False):
# TODO: rethink use of multiple database sources - may lead to inconsistency with genome sources
successfully_mapped_counter = 0
for g in tqdm(self.genes):
repseq = g.protein.set_representative_sequence(force_rerun=... | 548,513 |
Write all the model's sequences as a single FASTA file. By default, sets IDs to model gene IDs.
Args:
outname (str): Name of the output FASTA file without the extension
outdir (str): Path to output directory of downloaded files, must be set if GEM-PRO directories
were no... | def write_representative_sequences_file(self, outname, outdir=None, set_ids_from_model=True):
if not outdir:
outdir = self.data_dir
if not outdir:
raise ValueError('Output directory must be specified')
outfile = op.join(outdir, outname + '.faa')
... | 548,516 |
Run Biopython ProteinAnalysis and EMBOSS pepstats to summarize basic statistics of all protein sequences.
Results are stored in the protein's respective SeqProp objects at ``.annotations``
Args:
representative_only (bool): If analysis should only be run on the representative sequences | def get_sequence_properties(self, clean_seq=False, representatives_only=True):
for g in tqdm(self.genes):
g.protein.get_sequence_properties(clean_seq=clean_seq, representative_only=representatives_only) | 548,517 |
Run Biopython ProteinAnalysis and EMBOSS pepstats to summarize basic statistics of all protein sequences.
Results are stored in the protein's respective SeqProp objects at ``.annotations``
Args:
representative_only (bool): If analysis should only be run on the representative sequences | def get_sequence_sliding_window_properties(self, scale, window, representatives_only=True):
for g in tqdm(self.genes):
g.protein.get_sequence_sliding_window_properties(scale=scale, window=window,
representative_only=representative... | 548,518 |
Download ALL mapped experimental structures to each protein's structures directory.
Args:
outdir (str): Path to output directory, if GEM-PRO directories were not set or other output directory is
desired
pdb_file_type (str): Type of PDB file to download, if not already se... | def pdb_downloader_and_metadata(self, outdir=None, pdb_file_type=None, force_rerun=False):
if not pdb_file_type:
pdb_file_type = self.pdb_file_type
counter = 0
for g in tqdm(self.genes):
pdbs = g.protein.pdb_downloader_and_metadata(outdir=outdir, pdb_file_type=... | 548,533 |
Run DSSP on structures and store calculations.
Annotations are stored in the protein structure's chain sequence at:
``<chain_prop>.seq_record.letter_annotations['*-dssp']``
Args:
representative_only (bool): If analysis should only be run on the representative structure
... | def get_dssp_annotations_parallelize(self, sc, representatives_only=True, force_rerun=False):
genes_rdd = sc.parallelize(self.genes)
def get_dssp_annotation(g):
g.protein.get_dssp_annotations(representative_only=representatives_only, force_rerun=force_rerun)
return g
... | 548,536 |
Run MSMS on structures and store calculations.
Annotations are stored in the protein structure's chain sequence at:
``<chain_prop>.seq_record.letter_annotations['*-msms']``
Args:
representative_only (bool): If analysis should only be run on the representative structure
... | def get_msms_annotations(self, representatives_only=True, force_rerun=False):
for g in tqdm(self.genes):
g.protein.get_msms_annotations(representative_only=representatives_only, force_rerun=force_rerun) | 548,537 |
Run MSMS on structures and store calculations.
Annotations are stored in the protein structure's chain sequence at:
``<chain_prop>.seq_record.letter_annotations['*-msms']``
Args:
representative_only (bool): If analysis should only be run on the representative structure
... | def get_msms_annotations_parallelize(self, sc, representatives_only=True, force_rerun=False):
genes_rdd = sc.parallelize(self.genes)
def get_msms_annotation(g):
g.protein.get_msms_annotations(representative_only=representatives_only, force_rerun=force_rerun)
return g
... | 548,538 |
Run Biopython's disulfide bridge finder and store found bridges.
Annotations are stored in the protein structure's chain sequence at:
``<chain_prop>.seq_record.annotations['SSBOND-biopython']``
Args:
representative_only (bool): If analysis should only be run on the representative s... | def find_disulfide_bridges(self, representatives_only=True):
for g in tqdm(self.genes):
g.protein.find_disulfide_bridges(representative_only=representatives_only) | 548,542 |
Run Biopython's disulfide bridge finder and store found bridges.
Annotations are stored in the protein structure's chain sequence at:
``<chain_prop>.seq_record.annotations['SSBOND-biopython']``
Args:
representative_only (bool): If analysis should only be run on the representative s... | def find_disulfide_bridges_parallelize(self, sc, representatives_only=True):
genes_rdd = sc.parallelize(self.genes)
def find_disulfide_bridges(g):
g.protein.find_disulfide_bridges(representative_only=representatives_only)
return g
result = genes_rdd.map(find_di... | 548,543 |
Parse the oligomeric prediction in a SWISS-MODEL repository file
As of 2018-02-26, works on all E. coli models. Untested on other pre-made organism models.
Args:
swiss_model_path (str): Path to SWISS-MODEL PDB file
Returns:
dict: Information parsed about the oligomeric state | def get_oligomeric_state(swiss_model_path):
oligo_info = {}
with open(swiss_model_path, 'r') as f:
for line in f:
if line.startswith('REMARK 3 MODEL INFORMATION'):
break
for i in range(10):
line = f.readline()
if 'ENGIN' in line:
... | 548,548 |
Translate the OSTAT field to an integer.
As of 2018-02-26, works on all E. coli models. Untested on other pre-made organism models.
Args:
ostat (str): Predicted oligomeric state of the PDB file
Returns:
int: Translated string to integer | def translate_ostat(ostat):
ostat_lower = ostat.strip().lower()
if ostat_lower == 'monomer':
return 1
elif ostat_lower == 'homo-dimer':
return 2
elif ostat_lower == 'homo-trimer':
return 3
elif ostat_lower == 'homo-tetramer':
return 4
elif ostat_lower == 'hom... | 548,549 |
Return all available models for a UniProt accession number.
Args:
uniprot_acc (str): UniProt ACC/ID
Returns:
dict: All available models in SWISS-MODEL for this UniProt entry | def get_models(self, uniprot_acc):
if uniprot_acc in self.all_models:
return self.all_models[uniprot_acc]
else:
log.error('{}: no SWISS-MODELs available'.format(uniprot_acc))
return None | 548,553 |
Get the path to the homology model using information from the index dictionary for a single model.
Example: use self.get_models(UNIPROT_ID) to get all the models, which returns a list of dictionaries.
Use one of those dictionaries as input to this function to get the filepath to the model itself.
... | def get_model_filepath(self, infodict):
u = infodict['uniprot_ac']
original_filename = '{}_{}_{}_{}'.format(infodict['from'], infodict['to'],
infodict['template'], infodict['coordinate_id'])
file_path = op.join(self.metadata_dir, u[:2], ... | 548,554 |
Download all models available for a UniProt accession number.
Args:
uniprot_acc (str): UniProt ACC/ID
outdir (str): Path to output directory, uses working directory if not set
force_rerun (bool): Force a redownload the models if they already exist
Returns:
... | def download_models(self, uniprot_acc, outdir='', force_rerun=False):
downloaded = []
subset = self.get_models(uniprot_acc)
for entry in subset:
ident = '{}_{}_{}_{}'.format(uniprot_acc, entry['template'], entry['from'], entry['to'])
outfile = op.join(outdir, id... | 548,555 |
Organize and rename SWISS-MODEL models to a single folder with a name containing template information.
Args:
outdir (str): New directory to copy renamed models to
force_rerun (bool): If models should be copied again even if they already exist
Returns:
dict: Dictiona... | def organize_models(self, outdir, force_rerun=False):
uniprot_to_swissmodel = defaultdict(list)
for u, models in self.all_models.items():
for m in models:
original_filename = '{}_{}_{}_{}'.format(m['from'], m['to'], m['template'], m['coordinate_id'])
... | 548,556 |
Get dH using Oobatake method in units cal/mol.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
temp (float): Temperature in degrees C
Returns:
float: dH in units cal/mol | def calculate_oobatake_dH(seq, temp):
seq = ssbio.protein.sequence.utils.cast_to_str(seq)
dH = 0
temp += 273.15
T0 = 298.15
for aa in seq:
H0 = oobatake_dictionary[aa]['dH'] * 1000
dH += H0
return dH + _sum_of_dCp(seq) * (temp - T0) | 548,557 |
Get dS using Oobatake method in units cal/mol.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
temp (float): Temperature in degrees C
Returns:
float: dS in units cal/mol | def calculate_oobatake_dS(seq, temp):
seq = ssbio.protein.sequence.utils.cast_to_str(seq)
dS = 0
temp += 273.15
T0 = 298.15
dCp_sum = _sum_of_dCp(seq)
for aa in seq:
S0 = oobatake_dictionary[aa]['dS']
dS += S0
return dS + dCp_sum * math.log(temp / T0) | 548,558 |
Get free energy of unfolding (dG) using Oobatake method in units cal/mol.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
temp (float): Temperature in degrees C
Returns:
float: Free energy of unfolding dG (J/mol) | def calculate_oobatake_dG(seq, temp):
dH = calculate_oobatake_dH(seq, temp)
dS = calculate_oobatake_dS(seq, temp)
dG = dH - (temp + 273.15) * dS
# 563.552 - a correction for N- and C-terminal group (approximated from 7 examples in the paper)
return dG - 563.552 | 548,559 |
Get free energy of unfolding (dG) using Dill method in units J/mol.
Args:
seq_len (int): Length of amino acid sequence
temp (float): Temperature in degrees C
Returns:
float: Free energy of unfolding dG (J/mol) | def calculate_dill_dG(seq_len, temp):
Th = 373.5 # This quantity affects the up-and-down of the dG vs temperature curve (dG values)
Ts = 385 # This quantity affects the left-and-right
temp += 273.15
dH = (4.0 * seq_len + 143) * 1000
dS = 13.27 * seq_len + 448
dCp = (0.049 * seq_len + 0.8... | 548,560 |
Predict dG at temperature T, using best predictions from Dill or Oobatake methods.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
temp (float): Temperature in degrees C
Returns:
(tuple): tuple containing:
dG (float) Free energy of unfolding dG (cal/mol)
k... | def get_dG_at_T(seq, temp):
# R (molar gas constant) in calories
r_cal = scipy.constants.R / scipy.constants.calorie
seq = ssbio.protein.sequence.utils.cast_to_str(seq)
oobatake = {}
for t in range(20, 51):
oobatake[t] = calculate_oobatake_dG(seq, t)
stable = [i for i in oobatake... | 548,561 |
Run the PPM server from OPM to predict transmembrane residues.
Args:
pdb_file (str): Path to PDB file
outfile (str): Path to output HTML results file
force_rerun (bool): Flag to rerun PPM if HTML results file already exists
Returns:
dict: Dictionary of information from the PPM ... | def run_ppm_server(pdb_file, outfile, force_rerun=False):
if ssbio.utils.force_rerun(outfile=outfile, flag=force_rerun):
url = 'http://sunshine.phar.umich.edu/upload_file.php'
files = {'userfile': open(pdb_file, 'rb')}
r = requests.post(url, files=files)
info = r.text
#... | 548,562 |
Submit a protein sequence string to CCTOP and return the job ID.
Args:
seq_str (str): Protein sequence as a string
Returns:
dict: Job ID on the CCTOP server | def cctop_submit(seq_str):
url = 'http://cctop.enzim.ttk.mta.hu/php/submit.php?sequence={}&tmFilter&signalPred'.format(seq_str)
r = requests.post(url)
jobid = r.text.split('ID: ')[1]
return jobid | 548,566 |
Check the status of a CCTOP job ID.
Args:
jobid (str): Job ID obtained when job was submitted
Returns:
str: 'Finished' if the job is finished and results ready to be downloaded, 'Running' if still in progress,
'Invalid' for any errors. | def cctop_check_status(jobid):
status = 'http://cctop.enzim.ttk.mta.hu/php/poll.php?jobId={}'.format(jobid)
status_text = requests.post(status)
return status_text.text | 548,567 |
Save the CCTOP results file in XML format.
Args:
jobid (str): Job ID obtained when job was submitted
outpath (str): Path to output filename
Returns:
str: Path to output filename | def cctop_save_xml(jobid, outpath):
status = cctop_check_status(jobid=jobid)
if status == 'Finished':
result = 'http://cctop.enzim.ttk.mta.hu/php/result.php?jobId={}'.format(jobid)
result_text = requests.post(result)
with open(outpath, 'w') as f:
f.write(result_text.text... | 548,568 |
Parse a CCTOP XML results file and return a list of the consensus TM domains in the format::
[(1, inside_outside_or_tm),
(2, inside_outside_or_tm),
...]
Where the first value of a tuple is the sequence residue number, and the second is the predicted location with the
valu... | def parse_cctop_full(infile):
parser = etree.XMLParser(ns_clean=True)
with open(infile, 'r') as f:
tree = etree.fromstring(f.read(), parser)
all_info = []
if tree.find('Topology') is not None:
for r in tree.find('Topology').findall('Region'):
region_start = int(r.attri... | 548,569 |
Load a feather of amino acid counts for a protein.
Args:
protein_feather (str): path to feather file
copynum_scale (bool): if counts should be multiplied by protein copy number
copynum_df (DataFrame): DataFrame of copy numbers
Returns:
DataFrame: of counts with some aggregated ... | def load_feather(protein_feather, length_filter_pid=None, copynum_scale=False, copynum_df=None):
protein_df = pd.read_feather(protein_feather).set_index('index')
# Combine counts for residue groups
from ssbio.protein.sequence.properties.residues import _aa_property_dict_one, EXTENDED_AA_PROPERTY_DICT_... | 548,574 |
Merge all existing models into a Structure's first_model attribute.
This directly modifies the Biopython Structure object. Chains IDs will start from A and increment for each new
chain (model that is converted).
Args:
biop_structure (Structure): Structure with multiple models that should be merged | def merge_all_models_into_first_model(biop_structure):
from string import ascii_uppercase
idx = 1
first_model = biop_structure[0]
for m in biop_structure.get_models():
# Don't duplicate the original model
if first_model.id == m.id:
continue
for c in m.get_chains... | 548,594 |
Utility to take as input a bioassembly file and merge all its models into multiple chains in a single model.
Args:
infile (str): Path to input PDB file with multiple models that represent an oligomeric form of a structure.
outdir (str): Path to output directory
outname (str): New filename o... | def write_merged_bioassembly(inpath, outdir, outname, force_rerun=False):
outpath = outfile=op.join(outdir, outname + '.pdb')
if ssbio.utils.force_rerun(flag=force_rerun, outfile=op.join(outdir, outname + '.pdb')):
s = StructProp('Model merging', structure_path=inpath, file_type='pdb')
ss ... | 548,595 |
Save the object as a pickle file
Args:
outfile (str): Filename
protocol (int): Pickle protocol to use. Default is 2 to remain compatible with Python 2
Returns:
str: Path to pickle file | def save_pickle(obj, outfile, protocol=2):
with open(outfile, 'wb') as f:
pickle.dump(obj, f, protocol=protocol)
return outfile | 548,600 |
Load a pickle file.
Args:
file (str): Path to pickle file
Returns:
object: Loaded object from pickle file | def load_pickle(file, encoding=None):
# TODO: test set encoding='latin1' for 2/3 incompatibility
if encoding:
with open(file, 'rb') as f:
return pickle.load(f, encoding=encoding)
with open(file, 'rb') as f:
return pickle.load(f) | 548,601 |
Copy attributes of a Gene object over to this Gene, given that the modified gene has the same ID.
Args:
modified_gene (Gene, GenePro): Gene with modified attributes that you want to copy over.
ignore_model_attributes (bool): If you want to ignore copying over attributes related to metab... | def copy_modified_gene(self, modified_gene, ignore_model_attributes=True):
ignore = ['_model', '_reaction', '_functional', 'model', 'reaction', 'functional']
for attr in filter(lambda a: not a.startswith('__') and not isinstance(getattr(type(self), a, None), property) and not callable(getattr(s... | 548,609 |
Load a structure file and provide pointers to its location
Args:
structure_path (str): Path to structure file
file_type (str): Type of structure file | def load_structure_path(self, structure_path, file_type):
if not file_type:
raise ValueError('File type must be specified')
self.file_type = file_type
self.structure_dir = op.dirname(structure_path)
self.structure_file = op.basename(structure_path) | 548,614 |
Read the 3D coordinates of a structure file and return it as a Biopython Structure object.
Also create ChainProp objects in the chains attribute for each chain in the first model.
Args:
store_in_memory (bool): If the Biopython Structure object should be stored in the attribute ``structure``... | def parse_structure(self, store_in_memory=False):
# TODO: perhaps add option to parse into ProDy object?
if not self.structure_file:
log.error('{}: no structure file, unable to parse'.format(self.id))
return None
else:
# Add Biopython structure object... | 548,615 |
Add chains by ID into the mapped_chains attribute
Args:
mapped_chains (str, list): Chain ID or list of IDs | def add_mapped_chain_ids(self, mapped_chains):
mapped_chains = ssbio.utils.force_list(mapped_chains)
for c in mapped_chains:
if c not in self.mapped_chains:
self.mapped_chains.append(c)
log.debug('{}: added to list of mapped chains'.format(c))
... | 548,617 |
Add chains by ID into the chains attribute
Args:
chains (str, list): Chain ID or list of IDs | def add_chain_ids(self, chains):
chains = ssbio.utils.force_list(chains)
for c in chains:
if self.chains.has_id(c):
log.debug('{}: chain already present'.format(c))
else:
chain_prop = ChainProp(ident=c, pdb_parent=self.id)
... | 548,618 |
Gather chain sequences and store in their corresponding ``ChainProp`` objects in the ``chains`` attribute.
Args:
model (Model): Biopython Model object of the structure you would like to parse | def get_structure_seqs(self, model):
# Don't overwrite existing ChainProp objects
dont_overwrite = []
chains = list(model.get_chains())
for x in chains:
if self.chains.has_id(x.id):
if self.chains.get_by_id(x.id).seq_record:
dont_... | 548,619 |
get_dict method which incorporates attributes found in a specific chain. Does not overwrite any attributes
in the original StructProp.
Args:
chain:
only_keys:
chain_keys:
exclude_attributes:
df_format:
Returns:
dict: attri... | def get_dict_with_chain(self, chain, only_keys=None, chain_keys=None, exclude_attributes=None, df_format=False):
# Choose attributes to return, return everything in the object if a list is not specified
if not only_keys:
keys = list(self.__dict__.keys())
else:
k... | 548,620 |
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 sh... | 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
if ssbio.utils.is_ipynb():
import nglview as nv
else:
raise EnvironmentError... | 548,627 |
Parse the 'long' output format of TMHMM and return a dictionary of ``{sequence_ID: TMHMM_prediction}``.
Args:
tmhmm_results (str): Path to long format TMHMM output.
Returns:
dict: Dictionary of ``{sequence_ID: TMHMM_prediction}`` | def parse_tmhmm_long(tmhmm_results):
with open(tmhmm_results) as f:
lines = f.read().splitlines()
infodict = defaultdict(dict)
for l in lines:
if 'Number of predicted TMHs:' in l:
gene = l.split(' Number')[0].strip('# ')
infodict[gene]['num_tm_helices'] = int(l... | 548,630 |
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 i... | 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_label == 'T':
T_residue.append(residue_count)
residue_count = residue_count + 1
TM_number_d... | 548,631 |
Submit sequence and structural class to FOLD-RATE calculator (http://www.iitm.ac.in/bioinfo/fold-rate/)
to calculate kinetic folding rate.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
secstruct (str): Structural class: `all-alpha``, ``all-beta``, ``mixed``, or ``unknown``
Returns:
... | def get_foldrate(seq, secstruct):
seq = ssbio.protein.sequence.utils.cast_to_str(seq)
url = 'http://www.iitm.ac.in/bioinfo/cgi-bin/fold-rate/foldrateCalculator.pl'
values = {'sequence': seq, 'eqn': secstruct}
data = urlencode(values)
data = data.encode('ASCII')
response = urlopen(url, da... | 548,632 |
Scale the predicted kinetic folding rate of a protein to temperature T, based on the relationship ln(k_f)∝1/T
Args:
ref_rate (float): Kinetic folding rate calculated from the function :func:`~ssbio.protein.sequence.properties.kinetic_folding_rate.get_foldrate`
new_temp (float): Temperature in degre... | def get_foldrate_at_temp(ref_rate, new_temp, ref_temp=37.0):
# Not much data available on this slope value, however its effect on growth rate in a model is very small
slope = 22000
# Get folding rate for the reference temperature
preFactor = float(ref_rate) + slope / (float(ref_temp) + 273.15)
... | 548,633 |
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... | def emboss_pepstats_on_fasta(infile, outfile='', outdir='', outext='.pepstats', force_rerun=False):
# 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="{... | 548,636 |
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. | def emboss_pepstats_parser(infile):
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(... | 548,637 |
Prepare a GEM-PRO model for ATLAS analysis
Args:
atlas_name (str): Name of your ATLAS project
root_dir (str): Path to where the folder named after ``atlas_name`` will be created.
reference_gempro (GEMPRO): GEM-PRO model to use as the reference genome
reference_ge... | def __init__(self, atlas_name, root_dir, reference_gempro, reference_genome_path=None, description=None):
Object.__init__(self, id=atlas_name, description=description)
# Create directories
self._root_dir = None
self.root_dir = root_dir
self.strains = DictList()
... | 548,641 |
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 | 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=False)
# logging.disable(logging.NOTSET)
self.strains.append(strain_gp)
return self.... | 548,643 |
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 | def download_patric_genomes(self, ids, force_rerun=False):
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='p... | 548,644 |
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 | 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]
genes_to_remove.extend(self.missing_in_orthology_matrix)
genes_to_remove = list(set(genes_to_rem... | 548,647 |
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 | 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 length of the protein, other... | 548,652 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.