idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
59,900
def pdbe_status_code ( code ) : url = 'http://www.ebi.ac.uk/pdbe/entry-files/download/{0}_1.mmol' . format ( code ) r = requests . head ( url = url ) return r . status_code
Check if a PDB code has structure files on the PDBE site .
59,901
def preferred_mmol ( code ) : if code in mmols_numbers . keys ( ) : mmol = mmols_numbers [ code ] [ 1 ] return mmol elif is_obsolete ( code ) : raise ValueError ( 'Obsolete PDB code {0}' . format ( code ) ) else : url_string = "http://www.ebi.ac.uk/pdbe/entry/pdb/{0}/analysis" . format ( code ) r = requests . get ( url_string ) if not r . ok : raise IOError ( "Could not get to url {0}" . format ( url_string ) ) r_content = r . text ass = re . findall ( 'Assembly\s\d+\s\(preferred\)' , r_content ) if len ( ass ) != 1 : ass = re . findall ( 'Assembly\s+\(preferred\)' , r_content ) if len ( ass ) == 1 : return 1 obs = re . findall ( 'Entry has been obsoleted and replaced by another entry \(OBS\)' , r_content ) if len ( obs ) == 1 : rep = re . findall ( 'by entry <a href="/pdbe/entry/pdb/\w{4}' , r_content ) if len ( rep ) == 1 : rep = rep [ 0 ] [ - 4 : ] raise IOError ( "{0} is obsolete and has been replaced by {1}." . format ( code , rep ) ) raise ValueError ( "More than one match to preferred assembly" ) mmol = ass [ 0 ] . split ( ) [ 1 ] try : mmol = int ( mmol ) except TypeError : raise TypeError ( "Unexpected match: non-integer mmol" ) return mmol
Get mmol number of preferred biological assembly as listed in the PDBe .
59,902
def current_codes_from_pdb ( ) : url = 'http://www.rcsb.org/pdb/rest/getCurrent' r = requests . get ( url ) if r . status_code == 200 : pdb_codes = [ x . lower ( ) for x in r . text . split ( '"' ) if len ( x ) == 4 ] else : print ( 'Request for {0} failed with status code {1}' . format ( url , r . status_code ) ) return return pdb_codes
Get list of all PDB codes currently listed in the PDB .
59,903
def mmols ( self ) : mmols_dict = { } mmol_dir = os . path . join ( self . parent_dir , 'structures' ) if not os . path . exists ( mmol_dir ) : os . makedirs ( mmol_dir ) mmol_file_names = [ '{0}_{1}.mmol' . format ( self . code , i ) for i in range ( 1 , self . number_of_mmols + 1 ) ] mmol_files = [ os . path . join ( mmol_dir , x ) for x in mmol_file_names ] for i , mmol_file in enumerate ( mmol_files ) : mmols_dict [ i + 1 ] = mmol_file if not os . path . exists ( mmol_file ) : get_mmol ( self . code , mmol_number = i + 1 , outfile = mmol_file ) return mmols_dict
Dict of filepaths for all mmol files associated with code .
59,904
def dssps ( self ) : dssps_dict = { } dssp_dir = os . path . join ( self . parent_dir , 'dssp' ) if not os . path . exists ( dssp_dir ) : os . makedirs ( dssp_dir ) for i , mmol_file in self . mmols . items ( ) : dssp_file_name = '{0}.dssp' . format ( os . path . basename ( mmol_file ) ) dssp_file = os . path . join ( dssp_dir , dssp_file_name ) if not os . path . exists ( dssp_file ) : dssp_out = run_dssp ( pdb = mmol_file , path = True , outfile = dssp_file ) if len ( dssp_out ) == 0 : raise Warning ( "dssp file {0} is empty" . format ( dssp_file ) ) dssps_dict [ i ] = dssp_file return dssps_dict
Dict of filepaths for all dssp files associated with code .
59,905
def fastas ( self , download = False ) : fastas_dict = { } fasta_dir = os . path . join ( self . parent_dir , 'fasta' ) if not os . path . exists ( fasta_dir ) : os . makedirs ( fasta_dir ) for i , mmol_file in self . mmols . items ( ) : mmol_name = os . path . basename ( mmol_file ) fasta_file_name = '{0}.fasta' . format ( mmol_name ) fasta_file = os . path . join ( fasta_dir , fasta_file_name ) if not os . path . exists ( fasta_file ) : if download : pdb_url = "http://www.rcsb.org/pdb/files/fasta.txt?structureIdList={0}" . format ( self . code . upper ( ) ) r = requests . get ( pdb_url ) if r . status_code == 200 : fasta_string = r . text else : fasta_string = None else : a = convert_pdb_to_ampal ( mmol_file ) if type ( a ) == AmpalContainer : a = a [ 0 ] fasta_string = a . fasta with open ( fasta_file , 'w' ) as foo : foo . write ( fasta_string ) fastas_dict [ i ] = fasta_file return fastas_dict
Dict of filepaths for all fasta files associated with code .
59,906
def mmcif ( self ) : mmcif_dir = os . path . join ( self . parent_dir , 'mmcif' ) if not os . path . exists ( mmcif_dir ) : os . makedirs ( mmcif_dir ) mmcif_file_name = '{0}.cif' . format ( self . code ) mmcif_file = os . path . join ( mmcif_dir , mmcif_file_name ) if not os . path . exists ( mmcif_file ) : get_mmcif ( code = self . code , outfile = mmcif_file ) return mmcif_file
Filepath for mmcif file associated with code .
59,907
def categories ( self ) : category_dict = { } for ligand in self : if ligand . category in category_dict : category_dict [ ligand . category ] . append ( ligand ) else : category_dict [ ligand . category ] = [ ligand ] return category_dict
Returns the categories of Ligands in LigandGroup .
59,908
def category_count ( self ) : category_dict = self . categories count_dict = { category : len ( category_dict [ category ] ) for category in category_dict } return count_dict
Returns the number of categories in categories .
59,909
def sequence_molecular_weight ( seq ) : if 'X' in seq : warnings . warn ( _nc_warning_str , NoncanonicalWarning ) return sum ( [ residue_mwt [ aa ] * n for aa , n in Counter ( seq ) . items ( ) ] ) + water_mass
Returns the molecular weight of the polypeptide sequence .
59,910
def sequence_molar_extinction_280 ( seq ) : if 'X' in seq : warnings . warn ( _nc_warning_str , NoncanonicalWarning ) return sum ( [ residue_ext_280 [ aa ] * n for aa , n in Counter ( seq ) . items ( ) ] )
Returns the molar extinction coefficient of the sequence at 280 nm .
59,911
def partial_charge ( aa , pH ) : difference = pH - residue_pka [ aa ] if residue_charge [ aa ] > 0 : difference *= - 1 ratio = ( 10 ** difference ) / ( 1 + 10 ** difference ) return ratio
Calculates the partial charge of the amino acid .
59,912
def sequence_charge ( seq , pH = 7.4 ) : if 'X' in seq : warnings . warn ( _nc_warning_str , NoncanonicalWarning ) adj_protein_charge = sum ( [ partial_charge ( aa , pH ) * residue_charge [ aa ] * n for aa , n in Counter ( seq ) . items ( ) ] ) adj_protein_charge += ( partial_charge ( 'N-term' , pH ) * residue_charge [ 'N-term' ] ) adj_protein_charge += ( partial_charge ( 'C-term' , pH ) * residue_charge [ 'C-term' ] ) return adj_protein_charge
Calculates the total charge of the input polypeptide sequence .
59,913
def charge_series ( seq , granularity = 0.1 ) : if 'X' in seq : warnings . warn ( _nc_warning_str , NoncanonicalWarning ) ph_range = numpy . arange ( 1 , 13 , granularity ) charge_at_ph = [ sequence_charge ( seq , ph ) for ph in ph_range ] return ph_range , charge_at_ph
Calculates the charge for pH 1 - 13 .
59,914
def sequence_isoelectric_point ( seq , granularity = 0.1 ) : if 'X' in seq : warnings . warn ( _nc_warning_str , NoncanonicalWarning ) ph_range , charge_at_ph = charge_series ( seq , granularity ) abs_charge_at_ph = [ abs ( ch ) for ch in charge_at_ph ] pi_index = min ( enumerate ( abs_charge_at_ph ) , key = lambda x : x [ 1 ] ) [ 0 ] return ph_range [ pi_index ]
Calculates the isoelectric point of the sequence for ph 1 - 13 .
59,915
def measure_sidechain_torsion_angles ( residue , verbose = True ) : chi_angles = [ ] aa = residue . mol_code if aa not in side_chain_dihedrals : if verbose : print ( "Amino acid {} has no known side-chain dihedral" . format ( aa ) ) else : for set_atoms in side_chain_dihedrals [ aa ] : required_for_dihedral = set_atoms [ 0 : 4 ] try : angle = dihedral ( residue [ required_for_dihedral [ 0 ] ] . _vector , residue [ required_for_dihedral [ 1 ] ] . _vector , residue [ required_for_dihedral [ 2 ] ] . _vector , residue [ required_for_dihedral [ 3 ] ] . _vector ) chi_angles . append ( angle ) except KeyError as k : print ( "{0} atom missing from residue {1} {2} " "- can't assign dihedral" . format ( k , residue . mol_code , residue . id ) ) chi_angles . append ( None ) return chi_angles
Calculates sidechain dihedral angles for a residue
59,916
def measure_torsion_angles ( residues ) : if len ( residues ) < 2 : torsion_angles = [ ( None , None , None ) ] * len ( residues ) else : torsion_angles = [ ] for i in range ( len ( residues ) ) : if i == 0 : res1 = residues [ i ] res2 = residues [ i + 1 ] omega = None phi = None try : psi = dihedral ( res1 [ 'N' ] . _vector , res1 [ 'CA' ] . _vector , res1 [ 'C' ] . _vector , res2 [ 'N' ] . _vector ) except KeyError as k : print ( "{0} atom missing - can't assign psi" . format ( k ) ) psi = None torsion_angles . append ( ( omega , phi , psi ) ) elif i == len ( residues ) - 1 : res1 = residues [ i - 1 ] res2 = residues [ i ] try : omega = dihedral ( res1 [ 'CA' ] . _vector , res1 [ 'C' ] . _vector , res2 [ 'N' ] . _vector , res2 [ 'CA' ] . _vector ) except KeyError as k : print ( "{0} atom missing - can't assign omega" . format ( k ) ) omega = None try : phi = dihedral ( res1 [ 'C' ] . _vector , res2 [ 'N' ] . _vector , res2 [ 'CA' ] . _vector , res2 [ 'C' ] . _vector ) except KeyError as k : print ( "{0} atom missing - can't assign phi" . format ( k ) ) phi = None psi = None torsion_angles . append ( ( omega , phi , psi ) ) else : res1 = residues [ i - 1 ] res2 = residues [ i ] res3 = residues [ i + 1 ] try : omega = dihedral ( res1 [ 'CA' ] . _vector , res1 [ 'C' ] . _vector , res2 [ 'N' ] . _vector , res2 [ 'CA' ] . _vector ) except KeyError as k : print ( "{0} atom missing - can't assign omega" . format ( k ) ) omega = None try : phi = dihedral ( res1 [ 'C' ] . _vector , res2 [ 'N' ] . _vector , res2 [ 'CA' ] . _vector , res2 [ 'C' ] . _vector ) except KeyError as k : print ( "{0} atom missing - can't assign phi" . format ( k ) ) phi = None try : psi = dihedral ( res2 [ 'N' ] . _vector , res2 [ 'CA' ] . _vector , res2 [ 'C' ] . _vector , res3 [ 'N' ] . _vector ) except KeyError as k : print ( "{0} atom missing - can't assign psi" . format ( k ) ) psi = None torsion_angles . append ( ( omega , phi , psi ) ) return torsion_angles
Calculates the dihedral angles for a list of backbone atoms .
59,917
def cc_to_local_params ( pitch , radius , oligo ) : rloc = numpy . sin ( numpy . pi / oligo ) * radius alpha = numpy . arctan ( ( 2 * numpy . pi * radius ) / pitch ) alphaloc = numpy . cos ( ( numpy . pi / 2 ) - ( ( numpy . pi ) / oligo ) ) * alpha pitchloc = ( 2 * numpy . pi * rloc ) / numpy . tan ( alphaloc ) return pitchloc , rloc , numpy . rad2deg ( alphaloc )
Returns local parameters for an oligomeric assembly .
59,918
def residues_per_turn ( p ) : cas = p . get_reference_coords ( ) prim_cas = p . primitive . coordinates dhs = [ abs ( dihedral ( cas [ i ] , prim_cas [ i ] , prim_cas [ i + 1 ] , cas [ i + 1 ] ) ) for i in range ( len ( prim_cas ) - 1 ) ] rpts = [ 360.0 / dh for dh in dhs ] rpts . append ( None ) return rpts
The number of residues per turn at each Monomer in the Polymer .
59,919
def polymer_to_reference_axis_distances ( p , reference_axis , tag = True , reference_axis_name = 'ref_axis' ) : if not len ( p ) == len ( reference_axis ) : raise ValueError ( "The reference axis must contain the same number of points " "as the Polymer primitive." ) prim_cas = p . primitive . coordinates ref_points = reference_axis . coordinates distances = [ distance ( prim_cas [ i ] , ref_points [ i ] ) for i in range ( len ( prim_cas ) ) ] if tag : p . tags [ reference_axis_name ] = reference_axis monomer_tag_name = 'distance_to_{0}' . format ( reference_axis_name ) for m , d in zip ( p . _monomers , distances ) : m . tags [ monomer_tag_name ] = d return distances
Returns distances between the primitive of a Polymer and a reference_axis .
59,920
def crick_angles ( p , reference_axis , tag = True , reference_axis_name = 'ref_axis' ) : if not len ( p ) == len ( reference_axis ) : raise ValueError ( "The reference axis must contain the same number of points" " as the Polymer primitive." ) prim_cas = p . primitive . coordinates p_cas = p . get_reference_coords ( ) ref_points = reference_axis . coordinates cr_angles = [ dihedral ( ref_points [ i ] , prim_cas [ i ] , prim_cas [ i + 1 ] , p_cas [ i ] ) for i in range ( len ( prim_cas ) - 1 ) ] cr_angles . append ( None ) if tag : p . tags [ reference_axis_name ] = reference_axis monomer_tag_name = 'crick_angle_{0}' . format ( reference_axis_name ) for m , c in zip ( p . _monomers , cr_angles ) : m . tags [ monomer_tag_name ] = c return cr_angles
Returns the Crick angle for each CA atom in the Polymer .
59,921
def alpha_angles ( p , reference_axis , tag = True , reference_axis_name = 'ref_axis' ) : if not len ( p ) == len ( reference_axis ) : raise ValueError ( "The reference axis must contain the same number of points " "as the Polymer primitive." ) prim_cas = p . primitive . coordinates ref_points = reference_axis . coordinates alphas = [ abs ( dihedral ( ref_points [ i + 1 ] , ref_points [ i ] , prim_cas [ i ] , prim_cas [ i + 1 ] ) ) for i in range ( len ( prim_cas ) - 1 ) ] alphas . append ( None ) if tag : p . tags [ reference_axis_name ] = reference_axis monomer_tag_name = 'alpha_angle_{0}' . format ( reference_axis_name ) for m , a in zip ( p . _monomers , alphas ) : m . tags [ monomer_tag_name ] = a return alphas
Alpha angle calculated using points on the primitive of helix and axis .
59,922
def reference_axis_from_chains ( chains ) : if not len ( set ( [ len ( x ) for x in chains ] ) ) == 1 : raise ValueError ( "All chains must be of the same length" ) coords = [ numpy . array ( chains [ 0 ] . primitive . coordinates ) ] orient_vector = polypeptide_vector ( chains [ 0 ] ) for i , c in enumerate ( chains [ 1 : ] ) : if is_acute ( polypeptide_vector ( c ) , orient_vector ) : coords . append ( numpy . array ( c . primitive . coordinates ) ) else : coords . append ( numpy . flipud ( numpy . array ( c . primitive . coordinates ) ) ) reference_axis = numpy . mean ( numpy . array ( coords ) , axis = 0 ) return Primitive . from_coordinates ( reference_axis )
Average coordinates from a set of primitives calculated from Chains .
59,923
def flip_reference_axis_if_antiparallel ( p , reference_axis , start_index = 0 , end_index = - 1 ) : p_vector = polypeptide_vector ( p , start_index = start_index , end_index = end_index ) if is_acute ( p_vector , reference_axis [ end_index ] - reference_axis [ start_index ] ) : reference_axis = numpy . flipud ( reference_axis ) return reference_axis
Flips reference axis if direction opposes the direction of the Polymer .
59,924
def make_primitive ( cas_coords , window_length = 3 ) : if len ( cas_coords ) >= window_length : primitive = [ ] count = 0 for _ in cas_coords [ : - ( window_length - 1 ) ] : group = cas_coords [ count : count + window_length ] average_x = sum ( [ x [ 0 ] for x in group ] ) / window_length average_y = sum ( [ y [ 1 ] for y in group ] ) / window_length average_z = sum ( [ z [ 2 ] for z in group ] ) / window_length primitive . append ( numpy . array ( [ average_x , average_y , average_z ] ) ) count += 1 else : raise ValueError ( 'A primitive cannot be generated for {0} atoms using a (too large) ' 'averaging window_length of {1}.' . format ( len ( cas_coords ) , window_length ) ) return primitive
Calculates running average of cas_coords with a fixed averaging window_length .
59,925
def make_primitive_smoothed ( cas_coords , smoothing_level = 2 ) : try : s_primitive = make_primitive ( cas_coords ) for x in range ( smoothing_level ) : s_primitive = make_primitive ( s_primitive ) except ValueError : raise ValueError ( 'Smoothing level {0} too high, try reducing the number of rounds' ' or give a longer Chain (curent length = {1}).' . format ( smoothing_level , len ( cas_coords ) ) ) return s_primitive
Generates smoothed primitive from a list of coordinates .
59,926
def make_primitive_extrapolate_ends ( cas_coords , smoothing_level = 2 ) : try : smoothed_primitive = make_primitive_smoothed ( cas_coords , smoothing_level = smoothing_level ) except ValueError : smoothed_primitive = make_primitive_smoothed ( cas_coords , smoothing_level = smoothing_level - 1 ) if len ( smoothed_primitive ) < 3 : smoothed_primitive = make_primitive_smoothed ( cas_coords , smoothing_level = smoothing_level - 1 ) final_primitive = [ ] for ca in cas_coords : prim_dists = [ distance ( ca , p ) for p in smoothed_primitive ] closest_indices = sorted ( [ x [ 0 ] for x in sorted ( enumerate ( prim_dists ) , key = lambda k : k [ 1 ] ) [ : 3 ] ] ) a , b , c = [ smoothed_primitive [ x ] for x in closest_indices ] ab_foot = find_foot ( a , b , ca ) bc_foot = find_foot ( b , c , ca ) ca_foot = ( ab_foot + bc_foot ) / 2 final_primitive . append ( ca_foot ) return final_primitive
Generates smoothed helix primitives and extrapolates lost ends .
59,927
def extend ( self , ampal_container ) : if isinstance ( ampal_container , AmpalContainer ) : self . _ampal_objects . extend ( ampal_container ) else : raise TypeError ( 'Only AmpalContainer objects may be merged with ' 'an AmpalContainer.' ) return
Extends an AmpalContainer with another AmpalContainer .
59,928
def pdb ( self ) : header_title = '{:<80}\n' . format ( 'HEADER {}' . format ( self . id ) ) data_type = '{:<80}\n' . format ( 'EXPDTA ISAMBARD Model' ) pdb_strs = [ ] for ampal in self : if isinstance ( ampal , Assembly ) : pdb_str = ampal . make_pdb ( header = False , footer = False ) else : pdb_str = ampal . make_pdb ( ) pdb_strs . append ( pdb_str ) merged_strs = 'ENDMDL\n' . join ( pdb_strs ) + 'ENDMDL\n' merged_pdb = '' . join ( [ header_title , data_type , merged_strs ] ) return merged_pdb
Compiles the PDB strings for each state into a single file .
59,929
def sort_by_tag ( self , tag ) : return AmpalContainer ( sorted ( self , key = lambda x : x . tags [ tag ] ) )
Sorts the AmpalContainer by a tag on the component objects .
59,930
def append ( self , item ) : if isinstance ( item , Polymer ) : self . _molecules . append ( item ) else : raise TypeError ( 'Only Polymer objects can be appended to an Assembly.' ) return
Adds a Polymer to the Assembly .
59,931
def extend ( self , assembly ) : if isinstance ( assembly , Assembly ) : self . _molecules . extend ( assembly ) else : raise TypeError ( 'Only Assembly objects may be merged with an Assembly.' ) return
Extends the Assembly with the contents of another Assembly .
59,932
def get_monomers ( self , ligands = True , pseudo_group = False ) : base_filters = dict ( ligands = ligands , pseudo_group = pseudo_group ) restricted_mol_types = [ x [ 0 ] for x in base_filters . items ( ) if not x [ 1 ] ] in_groups = [ x for x in self . filter_mol_types ( restricted_mol_types ) ] monomers = itertools . chain ( * ( p . get_monomers ( ligands = ligands ) for p in in_groups ) ) return monomers
Retrieves all the Monomers from the Assembly object .
59,933
def get_ligands ( self , solvent = True ) : if solvent : ligand_list = [ x for x in self . get_monomers ( ) if isinstance ( x , Ligand ) ] else : ligand_list = [ x for x in self . get_monomers ( ) if isinstance ( x , Ligand ) and not x . is_solvent ] return LigandGroup ( monomers = ligand_list )
Retrieves all ligands from the Assembly .
59,934
def get_atoms ( self , ligands = True , pseudo_group = False , inc_alt_states = False ) : atoms = itertools . chain ( * ( list ( m . get_atoms ( inc_alt_states = inc_alt_states ) ) for m in self . get_monomers ( ligands = ligands , pseudo_group = pseudo_group ) ) ) return atoms
Flat list of all the Atoms in the Assembly .
59,935
def is_within ( self , cutoff_dist , point , ligands = True ) : return find_atoms_within_distance ( self . get_atoms ( ligands = ligands ) , cutoff_dist , point )
Returns all atoms in AMPAL object within cut - off distance from the point .
59,936
def relabel_polymers ( self , labels = None ) : if labels : if len ( self . _molecules ) == len ( labels ) : for polymer , label in zip ( self . _molecules , labels ) : polymer . id = label else : raise ValueError ( 'Number of polymers ({}) and number of labels ({}) must be equal.' . format ( len ( self . _molecules ) , len ( labels ) ) ) else : for i , polymer in enumerate ( self . _molecules ) : polymer . id = chr ( i + 65 ) return
Relabels the component Polymers either in alphabetical order or using a list of labels .
59,937
def relabel_atoms ( self , start = 1 ) : counter = start for atom in self . get_atoms ( ligands = True ) : atom . id = counter counter += 1 return
Relabels all Atoms in numerical order offset by the start parameter .
59,938
def make_pdb ( self , ligands = True , alt_states = False , pseudo_group = False , header = True , footer = True ) : base_filters = dict ( ligands = ligands , pseudo_group = pseudo_group ) restricted_mol_types = [ x [ 0 ] for x in base_filters . items ( ) if not x [ 1 ] ] in_groups = [ x for x in self . filter_mol_types ( restricted_mol_types ) ] pdb_header = 'HEADER {:<80}\n' . format ( 'ISAMBARD Model {}' . format ( self . id ) ) if header else '' pdb_body = '' . join ( [ x . make_pdb ( alt_states = alt_states , inc_ligands = ligands ) + '{:<80}\n' . format ( 'TER' ) for x in in_groups ] ) pdb_footer = '{:<80}\n' . format ( 'END' ) if footer else '' pdb_str = '' . join ( [ pdb_header , pdb_body , pdb_footer ] ) return pdb_str
Generates a PDB string for the Assembly .
59,939
def backbone ( self ) : bb_molecules = [ p . backbone for p in self . _molecules if hasattr ( p , 'backbone' ) ] bb_assembly = Assembly ( bb_molecules , assembly_id = self . id ) return bb_assembly
Generates a new Assembly containing only the backbone atoms .
59,940
def primitives ( self ) : prim_molecules = [ p . primitive for p in self . _molecules if hasattr ( p , 'primitive' ) ] prim_assembly = Assembly ( molecules = prim_molecules , assembly_id = self . id ) return prim_assembly
Generates a new Assembly containing the primitives of each Polymer .
59,941
def sequences ( self ) : seqs = [ x . sequence for x in self . _molecules if hasattr ( x , 'sequence' ) ] return seqs
Returns the sequence of each Polymer in the Assembly as a list .
59,942
def fasta ( self ) : fasta_str = '' max_line_length = 79 for p in self . _molecules : if hasattr ( p , 'sequence' ) : fasta_str += '>{0}:{1}|PDBID|CHAIN|SEQUENCE\n' . format ( self . id . upper ( ) , p . id ) seq = p . sequence split_seq = [ seq [ i : i + max_line_length ] for i in range ( 0 , len ( seq ) , max_line_length ) ] for seq_part in split_seq : fasta_str += '{0}\n' . format ( seq_part ) return fasta_str
Generates a FASTA string for the Assembly .
59,943
def get_interaction_energy ( self , assign_ff = True , ff = None , mol2 = False , force_ff_assign = False ) : if not ff : ff = global_settings [ 'buff' ] [ 'force_field' ] if assign_ff : for molecule in self . _molecules : if hasattr ( molecule , 'update_ff' ) : molecule . update_ff ( ff , mol2 = mol2 , force_ff_assign = force_ff_assign ) else : raise AttributeError ( 'The following molecule does not have a update_ff' 'method:\n{}\nIf this is a custom molecule type it' 'should inherit from BaseAmpal:' . format ( molecule ) ) interactions = find_inter_ampal ( self , ff . distance_cutoff ) buff_score = score_interactions ( interactions , ff ) return buff_score
Calculates the interaction energy of the AMPAL object .
59,944
def pack_new_sequences ( self , sequences ) : from ampal . pdb_parser import convert_pdb_to_ampal assembly_bb = self . backbone total_seq_len = sum ( [ len ( x ) for x in sequences ] ) total_aa_len = sum ( [ len ( x ) for x in assembly_bb ] ) if total_seq_len != total_aa_len : raise ValueError ( 'Total sequence length ({}) does not match ' 'total Polymer length ({}).' . format ( total_seq_len , total_aa_len ) ) scwrl_out = pack_sidechains ( self . backbone . pdb , '' . join ( sequences ) ) if scwrl_out is None : return else : packed_structure , scwrl_score = scwrl_out new_assembly = convert_pdb_to_ampal ( packed_structure , path = False ) self . _molecules = new_assembly . _molecules [ : ] self . assign_force_field ( global_settings [ u'buff' ] [ u'force_field' ] ) self . tags [ 'scwrl_score' ] = scwrl_score return
Packs a new sequence onto each Polymer in the Assembly using Scwrl4 .
59,945
def repack_all ( self ) : non_na_sequences = [ s for s in self . sequences if ' ' not in s ] self . pack_new_sequences ( non_na_sequences ) return
Repacks the side chains of all Polymers in the Assembly .
59,946
def tag_secondary_structure ( self , force = False ) : for polymer in self . _molecules : if polymer . molecule_type == 'protein' : polymer . tag_secondary_structure ( force = force ) return
Tags each Monomer in the Assembly with it s secondary structure .
59,947
def tag_dssp_solvent_accessibility ( self , force = False ) : for polymer in self . _molecules : polymer . tag_dssp_solvent_accessibility ( force = force ) return
Tags each Monomer in the Assembly with its solvent accessibility .
59,948
def tag_torsion_angles ( self , force = False ) : for polymer in self . _molecules : if polymer . molecule_type == 'protein' : polymer . tag_torsion_angles ( force = force ) return
Tags each Monomer in the Assembly with its torsion angles .
59,949
def tag_ca_geometry ( self , force = False , reference_axis = None , reference_axis_name = 'ref_axis' ) : for polymer in self . _molecules : if polymer . molecule_type == 'protein' : polymer . tag_ca_geometry ( force = force , reference_axis = reference_axis , reference_axis_name = reference_axis_name ) return
Tags each Monomer in the Assembly with its helical geometry .
59,950
def tag_atoms_unique_ids ( self , force = False ) : tagged = [ 'unique_id' in x . tags . keys ( ) for x in self . get_atoms ( ) ] if ( not all ( tagged ) ) or force : for m in self . get_monomers ( ) : for atom_type , atom in m . atoms . items ( ) : atom . tags [ 'unique_id' ] = ( m . unique_id , atom_type ) return
Tags each Atom in the Assembly with its unique_id .
59,951
def convert_pro_to_hyp ( pro ) : with open ( str ( REF_PATH / 'hydroxyproline_ref_1bkv_0_6.pickle' ) , 'rb' ) as inf : hyp_ref = pickle . load ( inf ) align_nab ( hyp_ref , pro ) to_remove = [ 'CB' , 'CG' , 'CD' ] for ( label , atom ) in pro . atoms . items ( ) : if atom . element == 'H' : to_remove . append ( label ) for label in to_remove : del pro . atoms [ label ] for key , val in hyp_ref . atoms . items ( ) : if key not in pro . atoms . keys ( ) : pro . atoms [ key ] = val pro . mol_code = 'HYP' pro . mol_letter = 'X' pro . is_hetero = True pro . tags = { } pro . states = { 'A' : pro . atoms } pro . active_state = 'A' for atom in pro . get_atoms ( ) : atom . ampal_parent = pro atom . tags = { 'bfactor' : 1.0 , 'charge' : ' ' , 'occupancy' : 1.0 , 'state' : 'A' } return
Converts a pro residue to a hydroxypro residue .
59,952
def align_nab ( tar , ref ) : rot_trans_1 = find_transformations ( tar [ 'N' ] . array , tar [ 'CA' ] . array , ref [ 'N' ] . array , ref [ 'CA' ] . array ) apply_trans_rot ( tar , * rot_trans_1 ) rot_ang_ca_cb = dihedral ( tar [ 'CB' ] , ref [ 'CA' ] , ref [ 'N' ] , ref [ 'CB' ] ) tar . rotate ( rot_ang_ca_cb , ref [ 'N' ] . array - ref [ 'CA' ] . array , ref [ 'N' ] . array ) return
Aligns the N - CA and CA - CB vector of the target monomer .
59,953
def apply_trans_rot ( ampal , translation , angle , axis , point , radians = False ) : if not numpy . isclose ( angle , 0.0 ) : ampal . rotate ( angle = angle , axis = axis , point = point , radians = radians ) ampal . translate ( vector = translation ) return
Applies a translation and rotation to an AMPAL object .
59,954
def find_ss_regions_polymer ( polymer , ss ) : if isinstance ( ss , str ) : ss = [ ss [ : ] ] tag_key = 'secondary_structure' monomers = [ x for x in polymer if tag_key in x . tags . keys ( ) ] if len ( monomers ) == 0 : return Assembly ( ) if ( len ( ss ) == 1 ) and ( all ( [ m . tags [ tag_key ] == ss [ 0 ] for m in monomers ] ) ) : return Assembly ( polymer ) previous_monomer = None fragment = Polypeptide ( ampal_parent = polymer ) fragments = Assembly ( ) poly_id = 0 for monomer in monomers : current_monomer = monomer . tags [ tag_key ] if ( current_monomer == previous_monomer ) or ( not previous_monomer ) : fragment . append ( monomer ) else : if previous_monomer in ss : fragment . tags [ tag_key ] = monomer . tags [ tag_key ] fragment . id = chr ( poly_id + 65 ) fragments . append ( fragment ) poly_id += 1 fragment = Polypeptide ( ampal_parent = polymer ) fragment . append ( monomer ) previous_monomer = monomer . tags [ tag_key ] return fragments
Returns an Assembly of regions tagged as secondary structure .
59,955
def flat_list_to_polymer ( atom_list , atom_group_s = 4 ) : atom_labels = [ 'N' , 'CA' , 'C' , 'O' , 'CB' ] atom_elements = [ 'N' , 'C' , 'C' , 'O' , 'C' ] atoms_coords = [ atom_list [ x : x + atom_group_s ] for x in range ( 0 , len ( atom_list ) , atom_group_s ) ] atoms = [ [ Atom ( x [ 0 ] , x [ 1 ] ) for x in zip ( y , atom_elements ) ] for y in atoms_coords ] if atom_group_s == 5 : monomers = [ Residue ( OrderedDict ( zip ( atom_labels , x ) ) , 'ALA' ) for x in atoms ] elif atom_group_s == 4 : monomers = [ Residue ( OrderedDict ( zip ( atom_labels , x ) ) , 'GLY' ) for x in atoms ] else : raise ValueError ( 'Parameter atom_group_s must be 4 or 5 so atoms can be labeled correctly.' ) polymer = Polypeptide ( monomers = monomers ) return polymer
Takes a flat list of atomic coordinates and converts it to a Polymer .
59,956
def backbone ( self ) : bb_poly = Polypeptide ( [ x . backbone for x in self . _monomers ] , self . id ) return bb_poly
Returns a new Polymer containing only the backbone atoms .
59,957
def pack_new_sequence ( self , sequence ) : from ampal . pdb_parser import convert_pdb_to_ampal polymer_bb = self . backbone if len ( sequence ) != len ( polymer_bb ) : raise ValueError ( 'Sequence length ({}) does not match Polymer length ({}).' . format ( len ( sequence ) , len ( polymer_bb ) ) ) scwrl_out = pack_sidechains ( self . backbone . pdb , sequence ) if scwrl_out is None : return else : packed_structure , scwrl_score = scwrl_out new_assembly = convert_pdb_to_ampal ( packed_structure , path = False ) self . _monomers = new_assembly [ 0 ] . _monomers [ : ] self . tags [ 'scwrl_score' ] = scwrl_score self . assign_force_field ( global_settings [ 'buff' ] [ 'force_field' ] ) return
Packs a new sequence onto the polymer using Scwrl4 .
59,958
def sequence ( self ) : seq = [ x . mol_letter for x in self . _monomers ] return '' . join ( seq )
Returns the sequence of the Polymer as a string .
59,959
def backbone_bond_lengths ( self ) : bond_lengths = dict ( n_ca = [ distance ( r [ 'N' ] , r [ 'CA' ] ) for r in self . get_monomers ( ligands = False ) ] , ca_c = [ distance ( r [ 'CA' ] , r [ 'C' ] ) for r in self . get_monomers ( ligands = False ) ] , c_o = [ distance ( r [ 'C' ] , r [ 'O' ] ) for r in self . get_monomers ( ligands = False ) ] , c_n = [ distance ( r1 [ 'C' ] , r2 [ 'N' ] ) for r1 , r2 in [ ( self [ i ] , self [ i + 1 ] ) for i in range ( len ( self ) - 1 ) ] ] , ) return bond_lengths
Dictionary containing backbone bond lengths as lists of floats .
59,960
def backbone_bond_angles ( self ) : bond_angles = dict ( n_ca_c = [ angle_between_vectors ( r [ 'N' ] - r [ 'CA' ] , r [ 'C' ] - r [ 'CA' ] ) for r in self . get_monomers ( ligands = False ) ] , ca_c_o = [ angle_between_vectors ( r [ 'CA' ] - r [ 'C' ] , r [ 'O' ] - r [ 'C' ] ) for r in self . get_monomers ( ligands = False ) ] , ca_c_n = [ angle_between_vectors ( r1 [ 'CA' ] - r1 [ 'C' ] , r2 [ 'N' ] - r1 [ 'C' ] ) for r1 , r2 in [ ( self [ i ] , self [ i + 1 ] ) for i in range ( len ( self ) - 1 ) ] ] , c_n_ca = [ angle_between_vectors ( r1 [ 'C' ] - r2 [ 'N' ] , r2 [ 'CA' ] - r2 [ 'N' ] ) for r1 , r2 in [ ( self [ i ] , self [ i + 1 ] ) for i in range ( len ( self ) - 1 ) ] ] , ) return bond_angles
Dictionary containing backbone bond angles as lists of floats .
59,961
def tag_secondary_structure ( self , force = False ) : tagged = [ 'secondary_structure' in x . tags . keys ( ) for x in self . _monomers ] if ( not all ( tagged ) ) or force : dssp_out = run_dssp ( self . pdb , path = False ) if dssp_out is None : return dssp_ss_list = extract_all_ss_dssp ( dssp_out , path = False ) for monomer , dssp_ss in zip ( self . _monomers , dssp_ss_list ) : monomer . tags [ 'secondary_structure' ] = dssp_ss [ 1 ] return
Tags each Residue of the Polypeptide with secondary structure .
59,962
def tag_residue_solvent_accessibility ( self , tag_type = False , tag_total = False , force = False , include_hetatms = False ) : if tag_type : tag_type = tag_type else : tag_type = 'residue_solvent_accessibility' tagged = [ tag_type in x . tags . keys ( ) for x in self . _monomers ] if ( not all ( tagged ) ) or force : naccess_rsa_list , total = extract_residue_accessibility ( run_naccess ( self . pdb , mode = 'rsa' , path = False , include_hetatms = include_hetatms ) , path = False , get_total = tag_total ) for monomer , naccess_rsa in zip ( self . _monomers , naccess_rsa_list ) : monomer . tags [ tag_type ] = naccess_rsa if tag_total : self . tags [ 'total_polymer_accessibility' ] = total return
Tags Residues wirh relative residue solvent accessibility .
59,963
def tag_dssp_solvent_accessibility ( self , force = False ) : tagged = [ 'dssp_acc' in x . tags . keys ( ) for x in self . _monomers ] if ( not all ( tagged ) ) or force : dssp_out = run_dssp ( self . pdb , path = False ) if dssp_out is None : return dssp_acc_list = extract_solvent_accessibility_dssp ( dssp_out , path = False ) for monomer , dssp_acc in zip ( self . _monomers , dssp_acc_list ) : monomer . tags [ 'dssp_acc' ] = dssp_acc [ - 1 ] return
Tags each Residues Polymer with its solvent accessibility .
59,964
def tag_sidechain_dihedrals ( self , force = False ) : tagged = [ 'chi_angles' in x . tags . keys ( ) for x in self . _monomers ] if ( not all ( tagged ) ) or force : for monomer in self . _monomers : chi_angles = measure_sidechain_torsion_angles ( monomer , verbose = False ) monomer . tags [ 'chi_angles' ] = chi_angles return
Tags each monomer with side - chain dihedral angles
59,965
def tag_torsion_angles ( self , force = False ) : tagged = [ 'omega' in x . tags . keys ( ) for x in self . _monomers ] if ( not all ( tagged ) ) or force : tas = measure_torsion_angles ( self . _monomers ) for monomer , ( omega , phi , psi ) in zip ( self . _monomers , tas ) : monomer . tags [ 'omega' ] = omega monomer . tags [ 'phi' ] = phi monomer . tags [ 'psi' ] = psi monomer . tags [ 'tas' ] = ( omega , phi , psi ) return
Tags each Monomer of the Polymer with its omega phi and psi torsion angle .
59,966
def tag_ca_geometry ( self , force = False , reference_axis = None , reference_axis_name = 'ref_axis' ) : tagged = [ 'rise_per_residue' in x . tags . keys ( ) for x in self . _monomers ] if ( not all ( tagged ) ) or force : if len ( self ) < 7 : rprs = [ None ] * len ( self ) rocs = [ None ] * len ( self ) rpts = [ None ] * len ( self ) else : rprs = self . rise_per_residue ( ) rocs = self . radii_of_curvature ( ) rpts = residues_per_turn ( self ) for monomer , rpr , roc , rpt in zip ( self . _monomers , rprs , rocs , rpts ) : monomer . tags [ 'rise_per_residue' ] = rpr monomer . tags [ 'radius_of_curvature' ] = roc monomer . tags [ 'residues_per_turn' ] = rpt if ( reference_axis is not None ) and ( len ( reference_axis ) == len ( self ) ) : ref_axis_args = dict ( p = self , reference_axis = reference_axis , tag = True , reference_axis_name = reference_axis_name ) polymer_to_reference_axis_distances ( ** ref_axis_args ) crick_angles ( ** ref_axis_args ) alpha_angles ( ** ref_axis_args ) return
Tags each Residue with rise_per_residue radius_of_curvature and residues_per_turn .
59,967
def valid_backbone_bond_lengths ( self , atol = 0.1 ) : bond_lengths = self . backbone_bond_lengths a1 = numpy . allclose ( bond_lengths [ 'n_ca' ] , [ ideal_backbone_bond_lengths [ 'n_ca' ] ] * len ( self ) , atol = atol ) a2 = numpy . allclose ( bond_lengths [ 'ca_c' ] , [ ideal_backbone_bond_lengths [ 'ca_c' ] ] * len ( self ) , atol = atol ) a3 = numpy . allclose ( bond_lengths [ 'c_o' ] , [ ideal_backbone_bond_lengths [ 'c_o' ] ] * len ( self ) , atol = atol ) a4 = numpy . allclose ( bond_lengths [ 'c_n' ] , [ ideal_backbone_bond_lengths [ 'c_n' ] ] * ( len ( self ) - 1 ) , atol = atol ) return all ( [ a1 , a2 , a3 , a4 ] )
True if all backbone bonds are within atol Angstroms of the expected distance .
59,968
def valid_backbone_bond_angles ( self , atol = 20 ) : bond_angles = self . backbone_bond_angles omegas = [ x [ 0 ] for x in measure_torsion_angles ( self ) ] trans = [ 'trans' if ( omega is None ) or ( abs ( omega ) >= 90 ) else 'cis' for omega in omegas ] ideal_n_ca_c = [ ideal_backbone_bond_angles [ x ] [ 'n_ca_c' ] for x in trans ] ideal_ca_c_o = [ ideal_backbone_bond_angles [ trans [ i + 1 ] ] [ 'ca_c_o' ] for i in range ( len ( trans ) - 1 ) ] ideal_ca_c_o . append ( ideal_backbone_bond_angles [ 'trans' ] [ 'ca_c_o' ] ) ideal_ca_c_n = [ ideal_backbone_bond_angles [ x ] [ 'ca_c_n' ] for x in trans [ 1 : ] ] ideal_c_n_ca = [ ideal_backbone_bond_angles [ x ] [ 'c_n_ca' ] for x in trans [ 1 : ] ] a1 = numpy . allclose ( bond_angles [ 'n_ca_c' ] , [ ideal_n_ca_c ] , atol = atol ) a2 = numpy . allclose ( bond_angles [ 'ca_c_o' ] , [ ideal_ca_c_o ] , atol = atol ) a3 = numpy . allclose ( bond_angles [ 'ca_c_n' ] , [ ideal_ca_c_n ] , atol = atol ) a4 = numpy . allclose ( bond_angles [ 'c_n_ca' ] , [ ideal_c_n_ca ] , atol = atol ) return all ( [ a1 , a2 , a3 , a4 ] )
True if all backbone bond angles are within atol degrees of their expected values .
59,969
def backbone ( self ) : try : backbone = OrderedDict ( [ ( 'N' , self . atoms [ 'N' ] ) , ( 'CA' , self . atoms [ 'CA' ] ) , ( 'C' , self . atoms [ 'C' ] ) , ( 'O' , self . atoms [ 'O' ] ) ] ) except KeyError : missing_atoms = filter ( lambda x : x not in self . atoms . keys ( ) , ( 'N' , 'CA' , 'C' , 'O' ) ) raise KeyError ( 'Error in residue {} {} {}, missing ({}) atoms. ' '`atoms` must be an `OrderedDict` with coordinates ' 'defined for the backbone (N, CA, C, O) atoms.' . format ( self . ampal_parent . id , self . mol_code , self . id , ', ' . join ( missing_atoms ) ) ) bb_monomer = Residue ( backbone , self . mol_code , monomer_id = self . id , insertion_code = self . insertion_code , is_hetero = self . is_hetero ) return bb_monomer
Returns a new Residue containing only the backbone atoms .
59,970
def unique_id ( self ) : if self . is_hetero : if self . mol_code == 'HOH' : hetero_flag = 'W' else : hetero_flag = 'H_{0}' . format ( self . mol_code ) else : hetero_flag = ' ' return self . ampal_parent . id , ( hetero_flag , self . id , self . insertion_code )
Generates a tuple that uniquely identifies a Monomer in an Assembly .
59,971
def side_chain_environment ( self , cutoff = 4 , include_neighbours = True , inter_chain = True , include_ligands = False , include_solvent = False ) : if self . mol_code == 'GLY' : return [ self ] side_chain_dict = { x : { y : self . states [ x ] [ y ] for y in self . states [ x ] if self . states [ x ] [ y ] in self . side_chain } for x in self . states } side_chain_monomer = Monomer ( atoms = side_chain_dict , monomer_id = self . id , ampal_parent = self . ampal_parent ) sc_environment = side_chain_monomer . environment ( cutoff = cutoff , include_ligands = include_ligands , include_neighbours = include_neighbours , include_solvent = include_solvent , inter_chain = inter_chain ) return sc_environment
Finds Residues with any atom within the cutoff distance of side - chain .
59,972
def load_global_settings ( ) : with open ( settings_path , 'r' ) as settings_f : global global_settings settings_json = json . loads ( settings_f . read ( ) ) if global_settings is None : global_settings = settings_json global_settings [ u'package_path' ] = package_dir else : for k , v in settings_json . items ( ) : if type ( v ) == dict : global_settings [ k ] . update ( v ) else : global_settings [ k ] = v
Loads settings file containing paths to dependencies and other optional configuration elements .
59,973
def build ( self ) : for i in range ( 2 ) : self . _molecules . append ( self . make_helix ( self . aas [ i ] , self . axis_distances [ i ] , self . z_shifts [ i ] , self . phis [ i ] , self . splays [ i ] , self . off_plane [ i ] ) ) return
Builds a HelixPair using the defined attributes .
59,974
def make_helix ( aa , axis_distance , z_shift , phi , splay , off_plane ) : start = numpy . array ( [ axis_distance , 0 + z_shift , 0 ] ) end = numpy . array ( [ axis_distance , ( aa * 1.52 ) + z_shift , 0 ] ) mid = ( start + end ) / 2 helix = Helix . from_start_and_end ( start , end , aa = aa ) helix . rotate ( splay , ( 0 , 0 , 1 ) , mid ) helix . rotate ( off_plane , ( 1 , 0 , 0 ) , mid ) helix . rotate ( phi , helix . axis . unit_tangent , helix . helix_start ) return helix
Builds a helix for a given set of parameters .
59,975
def build ( self ) : self . _molecules = [ ] if self . handedness == 'l' : handedness = - 1 else : handedness = 1 rot_ang = self . rot_ang * handedness for i in range ( self . num_of_repeats ) : dup_unit = copy . deepcopy ( self . repeat_unit ) z = ( self . rise * i ) * numpy . array ( [ 0 , 0 , 1 ] ) dup_unit . translate ( z ) dup_unit . rotate ( rot_ang * i , [ 0 , 0 , 1 ] ) self . extend ( dup_unit ) self . relabel_all ( ) return
Builds a Solenoid using the defined attributes .
59,976
def from_start_and_end ( cls , start , end , sequence , helix_type = 'b_dna' , phos_3_prime = False ) : start = numpy . array ( start ) end = numpy . array ( end ) instance = cls ( sequence , helix_type = helix_type , phos_3_prime = phos_3_prime ) instance . move_to ( start = start , end = end ) return instance
Generates a helical Polynucleotide that is built along an axis .
59,977
def move_to ( self , start , end ) : start = numpy . array ( start ) end = numpy . array ( end ) if numpy . allclose ( start , end ) : raise ValueError ( 'start and end must NOT be identical' ) translation , angle , axis , point = find_transformations ( self . helix_start , self . helix_end , start , end ) if not numpy . isclose ( angle , 0.0 ) : self . rotate ( angle = angle , axis = axis , point = point , radians = False ) self . translate ( vector = translation ) return
Moves the Polynucleotide to lie on the start and end vector .
59,978
def fit_heptad_register ( crangles ) : crangles = [ x if x > 0 else 360 + x for x in crangles ] hept_p = [ x * ( 360.0 / 7.0 ) + ( ( 360.0 / 7.0 ) / 2.0 ) for x in range ( 7 ) ] ideal_crangs = [ hept_p [ 0 ] , hept_p [ 2 ] , hept_p [ 4 ] , hept_p [ 6 ] , hept_p [ 1 ] , hept_p [ 3 ] , hept_p [ 5 ] ] full_hept = len ( crangles ) // 7 ideal_crang_list = ideal_crangs * ( full_hept + 2 ) fitting = [ ] for i in range ( 7 ) : ang_pairs = zip ( crangles , ideal_crang_list [ i : ] ) ang_diffs = [ abs ( y - x ) for x , y in ang_pairs ] fitting . append ( ( i , numpy . mean ( ang_diffs ) , numpy . std ( ang_diffs ) ) ) return sorted ( fitting , key = lambda x : x [ 1 ] )
Attempts to fit a heptad repeat to a set of Crick angles .
59,979
def gather_layer_info ( self ) : for i in range ( len ( self . cc [ 0 ] ) ) : layer_radii = [ x [ i ] . tags [ 'distance_to_ref_axis' ] for x in self . cc ] self . radii_layers . append ( layer_radii ) layer_alpha = [ x [ i ] . tags [ 'alpha_angle_ref_axis' ] for x in self . cc ] self . alpha_layers . append ( layer_alpha ) layer_ca = [ x [ i ] . tags [ 'crick_angle_ref_axis' ] for x in self . cc ] self . ca_layers . append ( layer_ca ) return
Extracts the tagged coiled - coil parameters for each layer .
59,980
def calc_average_parameters ( parameter_layers ) : mean_layers = [ numpy . mean ( x ) if x [ 0 ] else 0 for x in parameter_layers ] overall_mean = numpy . mean ( [ x for x in mean_layers if x ] ) return mean_layers , overall_mean
Takes a group of equal length lists and averages them across each index .
59,981
def heptad_register ( self ) : base_reg = 'abcdefg' exp_base = base_reg * ( self . cc_len // 7 + 2 ) ave_ca_layers = self . calc_average_parameters ( self . ca_layers ) [ 0 ] [ : - 1 ] reg_fit = fit_heptad_register ( ave_ca_layers ) hep_pos = reg_fit [ 0 ] [ 0 ] return exp_base [ hep_pos : hep_pos + self . cc_len ] , reg_fit [ 0 ] [ 1 : ]
Returns the calculated register of the coiled coil and the fit quality .
59,982
def generate_report ( self ) : lines = [ 'Register Assignment\n-------------------' ] register , fit = self . heptad_register ( ) lines . append ( '{}\n{}\n' . format ( register , '\n' . join ( self . cc . sequences ) ) ) lines . append ( 'Fit Quality - Mean Angular Discrepancy = {:3.2f} (Std Dev = {:3.2f})\n' . format ( * fit ) ) lines . append ( 'Coiled Coil Parameters\n----------------------' ) layer_info = ( self . radii_layers , self . alpha_layers , self . ca_layers ) r_layer_aves , a_layer_aves , c_layer_aves = [ self . calc_average_parameters ( x ) for x in layer_info ] start_line = [ 'Res#' . rjust ( 5 ) , 'Radius' . rjust ( 9 ) , 'Alpha' . rjust ( 9 ) , 'CrAngle' . rjust ( 9 ) ] lines . append ( '' . join ( start_line ) ) for i in range ( len ( r_layer_aves [ 0 ] ) ) : residue = '{:>5}' . format ( i + 1 ) average_r = '{:+3.3f}' . format ( r_layer_aves [ 0 ] [ i ] ) . rjust ( 9 ) average_a = '{:+3.3f}' . format ( a_layer_aves [ 0 ] [ i ] ) . rjust ( 9 ) average_c = '{:+3.3f}' . format ( c_layer_aves [ 0 ] [ i ] ) . rjust ( 9 ) line = [ residue , average_r , average_a , average_c ] lines . append ( '' . join ( line ) ) lines . append ( '-' * 32 ) residue = ' Ave' average_r = '{:+3.3f}' . format ( r_layer_aves [ 1 ] ) . rjust ( 9 ) average_a = '{:+3.3f}' . format ( a_layer_aves [ 1 ] ) . rjust ( 9 ) average_c = '{:+3.3f}' . format ( c_layer_aves [ 1 ] ) . rjust ( 9 ) line = [ residue , average_r , average_a , average_c ] lines . append ( '' . join ( line ) ) residue = 'Std D' std_d_r = '{:+3.3f}' . format ( numpy . std ( r_layer_aves [ 0 ] ) ) . rjust ( 9 ) std_d_a = '{:+3.3f}' . format ( numpy . std ( a_layer_aves [ 0 ] [ : - 1 ] ) ) . rjust ( 9 ) std_d_c = '{:+3.3f}' . format ( numpy . std ( c_layer_aves [ 0 ] [ : - 1 ] ) ) . rjust ( 9 ) line = [ residue , std_d_r , std_d_a , std_d_c ] lines . append ( '' . join ( line ) ) return '\n' . join ( lines )
Generates a report on the coiled coil parameters .
59,983
def buff_interaction_eval ( cls , specification , sequences , parameters , ** kwargs ) : instance = cls ( specification , sequences , parameters , build_fn = default_build , eval_fn = buff_interaction_eval , ** kwargs ) return instance
Creates optimizer with default build and BUFF interaction eval .
59,984
def rmsd_eval ( cls , specification , sequences , parameters , reference_ampal , ** kwargs ) : eval_fn = make_rmsd_eval ( reference_ampal ) instance = cls ( specification , sequences , parameters , build_fn = default_build , eval_fn = eval_fn , mp_disabled = True , ** kwargs ) return instance
Creates optimizer with default build and RMSD eval .
59,985
def parse_individual ( self , individual ) : scaled_ind = [ ] for i in range ( len ( self . value_means ) ) : scaled_ind . append ( self . value_means [ i ] + ( individual [ i ] * self . value_ranges [ i ] ) ) fullpars = list ( self . arrangement ) for k in range ( len ( self . variable_parameters ) ) : for j in range ( len ( fullpars ) ) : if fullpars [ j ] == self . variable_parameters [ k ] : fullpars [ j ] = scaled_ind [ k ] return fullpars
Converts a deap individual into a full list of parameters .
59,986
def run_opt ( self , pop_size , generations , cores = 1 , plot = False , log = False , log_path = None , run_id = None , store_params = True , ** kwargs ) : self . _cores = cores self . _store_params = store_params self . parameter_log = [ ] self . _model_count = 0 self . halloffame = tools . HallOfFame ( 1 ) self . stats = tools . Statistics ( lambda thing : thing . fitness . values ) self . stats . register ( "avg" , numpy . mean ) self . stats . register ( "std" , numpy . std ) self . stats . register ( "min" , numpy . min ) self . stats . register ( "max" , numpy . max ) self . logbook = tools . Logbook ( ) self . logbook . header = [ "gen" , "evals" ] + self . stats . fields start_time = datetime . datetime . now ( ) self . _initialize_pop ( pop_size ) for g in range ( generations ) : self . _update_pop ( pop_size ) self . halloffame . update ( self . population ) self . logbook . record ( gen = g , evals = self . _evals , ** self . stats . compile ( self . population ) ) print ( self . logbook . stream ) end_time = datetime . datetime . now ( ) time_taken = end_time - start_time print ( "Evaluated {} models in total in {}" . format ( self . _model_count , time_taken ) ) print ( "Best fitness is {0}" . format ( self . halloffame [ 0 ] . fitness ) ) print ( "Best parameters are {0}" . format ( self . parse_individual ( self . halloffame [ 0 ] ) ) ) for i , entry in enumerate ( self . halloffame [ 0 ] ) : if entry > 0.95 : print ( "Warning! Parameter {0} is at or near maximum allowed " "value\n" . format ( i + 1 ) ) elif entry < - 0.95 : print ( "Warning! Parameter {0} is at or near minimum allowed " "value\n" . format ( i + 1 ) ) if log : self . log_results ( output_path = output_path , run_id = run_id ) if plot : print ( '----Minimisation plot:' ) plt . figure ( figsize = ( 5 , 5 ) ) plt . plot ( range ( len ( self . logbook . select ( 'min' ) ) ) , self . logbook . select ( 'min' ) ) plt . xlabel ( 'Iteration' , fontsize = 20 ) plt . ylabel ( 'Score' , fontsize = 20 ) return
Runs the optimizer .
59,987
def _make_parameters ( self ) : self . value_means = [ ] self . value_ranges = [ ] self . arrangement = [ ] self . variable_parameters = [ ] current_var = 0 for parameter in self . parameters : if parameter . type == ParameterType . DYNAMIC : self . value_means . append ( parameter . value [ 0 ] ) if parameter . value [ 1 ] < 0 : raise AttributeError ( '"{}" parameter has an invalid range. Range values ' 'must be greater than zero' . format ( parameter . label ) ) self . value_ranges . append ( parameter . value [ 1 ] ) var_label = 'var{}' . format ( current_var ) self . arrangement . append ( var_label ) self . variable_parameters . append ( var_label ) current_var += 1 elif parameter . type == ParameterType . STATIC : self . arrangement . append ( parameter . value ) else : raise AttributeError ( '"{}"Unknown parameter type ({}). Parameters can be STATIC or' ' DYNAMIC.' . format ( parameter . type ) ) return
Converts a list of Parameters into DEAP format .
59,988
def assign_fitnesses ( self , targets ) : self . _evals = len ( targets ) px_parameters = zip ( [ self . specification ] * len ( targets ) , [ self . sequences ] * len ( targets ) , [ self . parse_individual ( x ) for x in targets ] ) if ( self . _cores == 1 ) or ( self . mp_disabled ) : models = map ( self . build_fn , px_parameters ) fitnesses = map ( self . eval_fn , models ) else : with futures . ProcessPoolExecutor ( max_workers = self . _cores ) as executor : models = executor . map ( self . build_fn , px_parameters ) fitnesses = executor . map ( self . eval_fn , models ) tars_fits = list ( zip ( targets , fitnesses ) ) if self . _store_params : self . parameter_log . append ( [ ( self . parse_individual ( x [ 0 ] ) , x [ 1 ] ) for x in tars_fits ] ) for ind , fit in tars_fits : ind . fitness . values = ( fit , ) return
Assigns fitnesses to parameters .
59,989
def dynamic ( cls , label , val_mean , val_range ) : return cls ( label , ParameterType . DYNAMIC , ( val_mean , val_range ) )
Creates a static parameter .
59,990
def run_scwrl ( pdb , sequence , path = True ) : if path : with open ( pdb , 'r' ) as inf : pdb = inf . read ( ) pdb = pdb . encode ( ) sequence = sequence . encode ( ) try : with tempfile . NamedTemporaryFile ( delete = False ) as scwrl_tmp , tempfile . NamedTemporaryFile ( delete = False ) as scwrl_seq , tempfile . NamedTemporaryFile ( delete = False ) as scwrl_out : scwrl_tmp . write ( pdb ) scwrl_tmp . seek ( 0 ) scwrl_seq . write ( sequence ) scwrl_seq . seek ( 0 ) if not global_settings [ 'scwrl' ] [ 'rigid_rotamer_model' ] : scwrl_std_out = subprocess . check_output ( [ global_settings [ 'scwrl' ] [ 'path' ] , '-i' , scwrl_tmp . name , '-o' , scwrl_out . name , '-s' , scwrl_seq . name ] ) else : scwrl_std_out = subprocess . check_output ( [ global_settings [ 'scwrl' ] [ 'path' ] , '-v' , '-i' , scwrl_tmp . name , '-o' , scwrl_out . name , '-s' , scwrl_seq . name ] ) scwrl_out . seek ( 0 ) scwrl_pdb = scwrl_out . read ( ) finally : os . remove ( scwrl_tmp . name ) os . remove ( scwrl_out . name ) os . remove ( scwrl_seq . name ) if not scwrl_pdb : raise IOError ( 'SCWRL failed to run. SCWRL:\n{}' . format ( scwrl_std_out ) ) return scwrl_std_out . decode ( ) , scwrl_pdb . decode ( )
Runs SCWRL on input PDB strong or path to PDB and a sequence string .
59,991
def parse_scwrl_out ( scwrl_std_out , scwrl_pdb ) : score = re . findall ( r'Total minimal energy of the graph = ([-0-9.]+)' , scwrl_std_out ) [ 0 ] split_scwrl = scwrl_pdb . splitlines ( ) fixed_scwrl = [ ] for line in split_scwrl : if len ( line ) < 80 : line += ' ' * ( 80 - len ( line ) ) if re . search ( r'H?E?T?ATO?M\s+\d+.+' , line ) : front = line [ : 61 ] temp_factor = ' 0.00' back = line [ 66 : ] fixed_scwrl . append ( '' . join ( [ front , temp_factor , back ] ) ) else : fixed_scwrl . append ( line ) fixed_scwrl_str = '\n' . join ( fixed_scwrl ) + '\n' return fixed_scwrl_str , float ( score )
Parses SCWRL output and returns PDB and SCWRL score .
59,992
def pack_sidechains ( pdb , sequence , path = False ) : scwrl_std_out , scwrl_pdb = run_scwrl ( pdb , sequence , path = path ) return parse_scwrl_out ( scwrl_std_out , scwrl_pdb )
Packs sidechains onto a given PDB file or string .
59,993
def parse_pdb_file ( self ) : self . pdb_parse_tree = { 'info' : { } , 'data' : { self . state : { } } } try : for line in self . pdb_lines : self . current_line = line record_name = line [ : 6 ] . strip ( ) if record_name in self . proc_functions : self . proc_functions [ record_name ] ( ) else : if record_name not in self . pdb_parse_tree [ 'info' ] : self . pdb_parse_tree [ 'info' ] [ record_name ] = [ ] self . pdb_parse_tree [ 'info' ] [ record_name ] . append ( line ) except EOFError : pass if self . new_labels : ampal_data_session . commit ( ) return
Runs the PDB parser .
59,994
def proc_atom ( self ) : atom_data = self . proc_line_coordinate ( self . current_line ) ( at_type , at_ser , at_name , alt_loc , res_name , chain_id , res_seq , i_code , x , y , z , occupancy , temp_factor , element , charge ) = atom_data a_state = self . pdb_parse_tree [ 'data' ] [ self . state ] res_id = ( res_seq , i_code ) if chain_id not in a_state : a_state [ chain_id ] = ( set ( ) , OrderedDict ( ) ) if res_id not in a_state [ chain_id ] [ 1 ] : a_state [ chain_id ] [ 1 ] [ res_id ] = ( set ( ) , OrderedDict ( ) ) if at_type == 'ATOM' : if res_name in standard_amino_acids . values ( ) : poly = 'P' else : poly = 'N' else : poly = 'H' a_state [ chain_id ] [ 0 ] . add ( ( chain_id , at_type , poly ) ) a_state [ chain_id ] [ 1 ] [ res_id ] [ 0 ] . add ( ( at_type , res_seq , res_name , i_code ) ) if at_ser not in a_state [ chain_id ] [ 1 ] [ res_id ] [ 1 ] : a_state [ chain_id ] [ 1 ] [ res_id ] [ 1 ] [ at_ser ] = [ atom_data ] else : a_state [ chain_id ] [ 1 ] [ res_id ] [ 1 ] [ at_ser ] . append ( atom_data ) return
Processes an ATOM or HETATM record .
59,995
def make_ampal ( self ) : data = self . pdb_parse_tree [ 'data' ] if len ( data ) > 1 : ac = AmpalContainer ( id = self . id ) for state , chains in sorted ( data . items ( ) ) : if chains : ac . append ( self . proc_state ( chains , self . id + '_state_{}' . format ( state + 1 ) ) ) return ac elif len ( data ) == 1 : return self . proc_state ( data [ 0 ] , self . id ) else : raise ValueError ( 'Empty parse tree, check input PDB format.' )
Generates an AMPAL object from the parse tree .
59,996
def proc_state ( self , state_data , state_id ) : assembly = Assembly ( assembly_id = state_id ) for k , chain in sorted ( state_data . items ( ) ) : assembly . _molecules . append ( self . proc_chain ( chain , assembly ) ) return assembly
Processes a state into an Assembly .
59,997
def proc_chain ( self , chain_info , parent ) : hetatom_filters = { 'nc_aas' : self . check_for_non_canonical } polymer = False chain_labels , chain_data = chain_info chain_label = list ( chain_labels ) [ 0 ] monomer_types = { x [ 2 ] for x in chain_labels if x [ 2 ] } if ( 'P' in monomer_types ) and ( 'N' in monomer_types ) : raise ValueError ( 'Malformed PDB, multiple "ATOM" types in a single chain.' ) if 'P' in monomer_types : polymer_class = Polypeptide polymer = True elif 'N' in monomer_types : polymer_class = Polynucleotide polymer = True elif 'H' in monomer_types : polymer_class = LigandGroup else : raise AttributeError ( 'Malformed parse tree, check inout PDB.' ) chain = polymer_class ( polymer_id = chain_label [ 0 ] , ampal_parent = parent ) if polymer : chain . ligands = LigandGroup ( polymer_id = chain_label [ 0 ] , ampal_parent = parent ) ligands = chain . ligands else : ligands = chain for residue in chain_data . values ( ) : res_info = list ( residue [ 0 ] ) [ 0 ] if res_info [ 0 ] == 'ATOM' : chain . _monomers . append ( self . proc_monomer ( residue , chain ) ) elif res_info [ 0 ] == 'HETATM' : mon_cls = None on_chain = False for filt_func in hetatom_filters . values ( ) : filt_res = filt_func ( residue ) if filt_res : mon_cls , on_chain = filt_res break mon_cls = Ligand if on_chain : chain . _monomers . append ( self . proc_monomer ( residue , chain , mon_cls = mon_cls ) ) else : ligands . _monomers . append ( self . proc_monomer ( residue , chain , mon_cls = mon_cls ) ) else : raise ValueError ( 'Malformed PDB, unknown record type for data' ) return chain
Converts a chain into a Polymer type object .
59,998
def proc_monomer ( self , monomer_info , parent , mon_cls = False ) : monomer_labels , monomer_data = monomer_info if len ( monomer_labels ) > 1 : raise ValueError ( 'Malformed PDB, single monomer id with ' 'multiple labels. {}' . format ( monomer_labels ) ) else : monomer_label = list ( monomer_labels ) [ 0 ] if mon_cls : monomer_class = mon_cls het = True elif monomer_label [ 0 ] == 'ATOM' : if monomer_label [ 2 ] in standard_amino_acids . values ( ) : monomer_class = Residue else : monomer_class = Nucleotide het = False else : raise ValueError ( 'Unknown Monomer type.' ) monomer = monomer_class ( atoms = None , mol_code = monomer_label [ 2 ] , monomer_id = monomer_label [ 1 ] , insertion_code = monomer_label [ 3 ] , is_hetero = het , ampal_parent = parent ) monomer . states = self . gen_states ( monomer_data . values ( ) , monomer ) monomer . _active_state = sorted ( monomer . states . keys ( ) ) [ 0 ] return monomer
Processes a records into a Monomer .
59,999
def generate_antisense_sequence ( sequence ) : dna_antisense = { 'A' : 'T' , 'T' : 'A' , 'C' : 'G' , 'G' : 'C' } antisense = [ dna_antisense [ x ] for x in sequence [ : : - 1 ] ] return '' . join ( antisense )
Creates the antisense sequence of a DNA strand .