def calculate_physiochemical_features(temp_dict, sequence): analyzed_seq = ProteinAnalysis(sequence) charge_at_pH7 = analyzed_seq.charge_at_pH(7) instability_index = analyzed_seq.instability_index() molecular_weight = analyzed_seq.molecular_weight() aromaticity = analyzed_seq.aromaticity() molar_extinction_coefficient = analyzed_seq.molar_extinction_coefficient() range_l, range_h = molar_extinction_coefficient molar_extinction_coefficient = (float(range_l) + float(range_h)) / 2 gravy = analyzed_seq.gravy( ) #Grand Average Hyrdopathy - Higher value = More Hydrophobic isoelectric_point = analyzed_seq.isoelectric_point() helix_fraction, turn_fraction, sheet_fraction = analyzed_seq.secondary_structure_fraction( ) physiochem_dict = { "Charge at pH7": charge_at_pH7, "Instability Index": instability_index, "Molecular Wt": molecular_weight, "Aromaticity": aromaticity, "Molar Extinction Coeff": molar_extinction_coefficient, "Gravy": gravy, "Isoelectric pt": isoelectric_point, "Helix Fraction": helix_fraction, "Turn Fraction": turn_fraction, "Sheet Fraction": sheet_fraction } temp_dict.update(physiochem_dict) #Adding separately because get_amino_acids_percent() generates a dictionary on its own aa_percent = analyzed_seq.get_amino_acids_percent() temp_dict.update(aa_percent)
def physchem_props(data): """Calculate the physicochemical properties per protein in ara_d.""" new_table = [] header = "ID\tclass\tindex\tsequon\tsequence\tmol_weight\tgravy\taromaticity\tinstab_index\tiso_point\n" new_table.append(header) for line in data: split_line = line.rstrip().split('\t') seq = split_line[-2] # Sequon, not sequence # Calculates the properties if "X" in seq or '*' in seq or seq == '': continue # Skip non-usable sequences, only negs try: a_seq = ProteinAnalysis(seq) # Update ara_d with new physchem properties results = [ a_seq.molecular_weight(), a_seq.gravy(), a_seq.aromaticity(), a_seq.instability_index(), #a_seq.flexibility(), a_seq.isoelectric_point(), #a_seq.secondary_structure_fraction(), ] except: print(split_line) sys.exit(1) new_line = line.rstrip() + "\t{}\t{}\t{}\t{}\t{}\n".format(*results) new_table.append(new_line) return new_table
def sequence_vector(temp_window: str, window: int = 6, chemical=1): """ This vector takes the sequence and has each amino acid represented by an int 0 represents nonstandard amino acids or as fluff for tails/heads of sequences Strip is a list which can be modified as user needs call for """ temp_window = clean(temp_window) temp_window = windower(sequence=temp_window, position=int(len(temp_window)*.5), wing_size=window) vec = [] aa = {"G": 1, "A": 2, "L": 3, "M": 4, "F": 5, "W": 6, "K": 7, "Q": 8, "E": 9, "S": 10, "P": 11, "V": 12, "I": 13, "C": 14, "Y": 15, "H": 16, "R": 17, "N": 18, "D": 19, "T": 20, "X": 0} for i in temp_window: vec.append(aa[i]) if len(vec) != (window*2)+1: t = len(vec) for i in range((window*2)+1-t): vec.append(0) # Hydrophobicity is optional if chemical == 1: s = ProteinAnalysis(temp_window) vec.append(s.gravy()) vec.append(s.instability_index()) vec.append(s.aromaticity()) return vec
def protein_analysis(): if session.username == None: redirect(URL(r=request, c='account', f='log_in')) from Bio.SeqUtils.ProtParam import ProteinAnalysis form = FORM( TABLE( TR( "Amino acid sequence: ", TEXTAREA(_type="text", _name="sequence", requires=IS_NOT_EMPTY())), INPUT(_type="submit", _value="SUBMIT"))) if form.accepts(request.vars, session): session['sequence'] = seqClean(form.vars.sequence.upper()) X = ProteinAnalysis(session['sequence']) session['aa_count'] = X.count_amino_acids() session['percent_aa'] = X.get_amino_acids_percent() session['mw'] = X.molecular_weight() session['aromaticity'] = X.aromaticity() session['instability'] = X.instability_index() session['flexibility'] = X.flexibility() session['pI'] = X.isoelectric_point() session['sec_struct'] = X.secondary_structure_fraction() redirect(URL(r=request, f='protein_analysis_output')) return dict(form=form)
def protParam(seq): params = ProteinAnalysis(seq) mw = params.molecular_weight() c_aa = params.count_amino_acids() p_aa = params.get_amino_acids_percent() gravy = params.gravy() aromaticity = params.aromaticity() isoelectric_point = params.isoelectric_point() ext_coeff = sum([c_aa["W"]*5690,c_aa["Y"]*1280,c_aa["C"]*120]) mgml = ext_coeff * (1./mw) print("Amino acid count") pprint.pprint(c_aa) print("Amino acid percent") pprint.pprint(p_aa) print("Molecular weight") print("%f Da"%mw) print("Gravy") print(gravy) print("Isoelectric point") print(isoelectric_point) print("Aromaticity") print(aromaticity) print("Extinction coefficient: %d M-1cm-1 (Assuming reduced)"%ext_coeff) print("")
def parse_pro_sequence(self, p_seq, id=None, desc=None): try: p_seq = ''.join([pro for pro in p_seq if pro in proteins]) # append fasta sequence metadata self.id.append(id) self.description.append(desc) # reverse translate protein to nucleotide sequence n_seq = ''.join([list(dna_codons.keys())[list(dna_codons.values()).index(pro)] for pro in p_seq]) self.nucleotide_sequence.append(n_seq) self.protein_sequence.append(p_seq) # self.protein_sequence.append(str(record.seq.translate()).replace('*', ' ')) # GC content self.gc_content.append(self.calculate_gc_content(n_seq)) # protein analysis methods analysis = ProteinAnalysis(p_seq) self.amino_acid_dict.append(analysis.get_amino_acids_percent()) self.molecular_weight.append(analysis.molecular_weight()) self.instability_index.append(analysis.instability_index()) self.aromaticity.append(analysis.aromaticity()) except Exception as e: print('-'*80) print(f"Exception in parsing uploaded virus sequence: {e}") traceback.print_exc(file=sys.stdout) print('-'*80)
def feat_extract(sequences): list_dict_feat = [] for sequence in sequences: protein = ProteinAnalysis(sequence) sequence_feat = defaultdict(float) sequence_len = len(sequence) sequence_feat["sequence_length"] = sequence_len sequence_feat["aromaticty"] = protein.aromaticity() sequence_feat["isoeletric_point"] = protein.isoelectric_point() #sequence_feat["flexibility"] = protein.flexibility() if ('X' not in sequence) and ('O' not in sequence) and ( 'U' not in sequence) and ('B' not in sequence): sequence_feat["molecular_weight"] = protein.molecular_weight() for letter in sequence: sequence_feat["relative_fre_{}".format(letter)] += 1 / sequence_len for property in dic_properties: if letter in dic_properties[property]: sequence_feat['freq_{}'.format(property)] += 1 for letter in sequence[0:50]: sequence_feat["relative_fre_start{}".format(letter)] += 1 / 50 for letter in sequence[-51:-1]: sequence_feat["relative_fre_end{}".format(letter)] += 1 / 50 list_dict_feat.append(sequence_feat) return list_dict_feat
def my_own_filtering(input_file, output_file, filt_gc=45, filt_arom=0.01): sequences = {} c = 0 with open(input_file, "r") as content: for record in SeqIO.parse(content, "fasta"): c += 1 # calculate GC content using Bio calc_gc = SeqUtils.GC(record.seq) # calculate aromaticity using Bio prot_seq = record.seq.translate() X = ProteinAnalysis(str(prot_seq)) calc_arom = X.aromaticity() # so, now you can filter if calc_gc >= filt_gc and calc_arom >= filt_arom: sequences[record.id] = record.se # write a new fasta file with aminoacids records = [] for seq_id, seq in sequences.items(): records.append(SeqRecord(seq.translate(), id=seq_id, description="")) write_file = open('my_fasta', 'w') SeqIO.write(records, write_file, 'fasta') write_file.close() # print the percentage print(len(records) / c)
def protAnalysis(self, content): result, resultFlexDic = dict(), dict() content = Parsers.normalizeSequence(content, self.sourceType) protein = ProteinAnalysis(content) result['proteinMWeight'] = protein.molecular_weight() result['proteinAroma'] = protein.aromaticity() result['proteinInstab'] = protein.instability_index() result['proteinIsoelec'] = protein.isoelectric_point() result['proteinGravy'] = protein.gravy() proteinStructure = protein.secondary_structure_fraction() protStruct = self.flatten('proteinSecstruc', proteinStructure) result = {**protStruct, **result} # merge result and protein Structure flexibility = protein.flexibility() flexibFlat = self.flatten('proteinFlex', flexibility) flexibAmino = self.flatten(list(content), flexibility) flattened = {**flexibFlat, **result} flattenedFlexDic = {**flexibAmino, **result} return result, flattened, flattenedFlexDic,
def protein_properties(seq): """Return a tuple with some protein biochemical properties seq is a Bio.Seq.Seq or str representing protein sequence """ pa = ProteinAnalysis(seq) aa_counts = pa.count_amino_acids() arom = pa.aromaticity() isoelec = pa.isoelectric_point() try: instability = pa.instability_index() except KeyError: instability = None try: gravy = pa.gravy() except KeyError: gravy = None return ProtProp(aa=str(seq), gravy=gravy, aromaticity=arom, isoelectric_point=isoelec, instability=instability, aa_counts=aa_counts)
def protParam(seq): params = ProteinAnalysis(seq) mw = params.molecular_weight() c_aa = params.count_amino_acids() p_aa = params.get_amino_acids_percent() gravy = params.gravy() aromaticity = params.aromaticity() isoelectric_point = params.isoelectric_point() ext_coeff = sum([c_aa["W"] * 5690, c_aa["Y"] * 1280, c_aa["C"] * 120]) mgml = ext_coeff * (1. / mw) print("Amino acid count") pprint.pprint(c_aa) print("Amino acid percent") pprint.pprint(p_aa) print("Molecular weight") print("%f Da" % mw) print("Gravy") print(gravy) print("Isoelectric point") print(isoelectric_point) print("Aromaticity") print(aromaticity) print("Extinction coefficient: %d M-1cm-1 (Assuming reduced)" % ext_coeff) print("")
def featureExtraction(train_df, test_df): #feature extraction using bio library to acquire peptide attributes n = len(train_df) Y = train_df[0] train_df = train_df.drop(columns=0) train_df = train_df.rename(columns={1: 0}) big = pd.concat([train_df, test_df], ignore_index=True) big['molecular_weight'] = 0.0 #big['flexibility'] = 0 big['isoelectric_point'] = 0.0 big['aromaticity'] = 0.0 big['stability'] = 0.0 for i in range(len(big)): #print(big.iloc[i, 0]) val = big.iloc[i, 0] #invalid peptide check, set all values to 0 if 'X' in val or 'Z' in val: big.at[i, 'molecular_weight'] = -1 #big.at[i, 'flexibility'] = -1 big.at[i, 'isoelectric_point'] = -1 big.at[i, 'aromaticity'] = -1 big.at[i, 'stability'] = -1 continue model = ProteinAnalysis(val) big.at[i, 'molecular_weight'] = model.molecular_weight() #big.at[i, 'flexibility'] = model.flexibility() big.at[i, 'isoelectric_point'] = model.isoelectric_point() big.at[i, 'aromaticity'] = model.aromaticity() big.at[i, 'stability'] = model.instability_index() big = big.drop(columns=0) train_df = big.iloc[:n, ] test_df = big.iloc[n:, ] return train_df, test_df, Y
def _protein_parameters(self, sequence): """Calculates physicochemical properties for the amino acid sequence. Args: sequence: str, amino acid sequence. Returns: property_arr: np array, vector of properties. """ analysis = ProteinAnalysis(sequence) property_arr = [] property_arr.append(analysis.molecular_weight()) property_arr.append(analysis.aromaticity()) property_arr.append(analysis.instability_index()) property_arr.append(analysis.gravy()) property_arr.append(analysis.isoelectric_point()) secondary = analysis.secondary_structure_fraction() property_arr.append(secondary[0]) property_arr.append(secondary[1]) property_arr.append(secondary[2]) molar_extinction_coefficient = analysis.molar_extinction_coefficient() property_arr.append(molar_extinction_coefficient[0]) property_arr.append(molar_extinction_coefficient[1]) property_arr.append(self._net_charge(sequence)) return np.array(property_arr)
def prot_param_features(seq): features = {} pa = ProteinAnalysis(str(seq.seq)) # .replace('X','G').replace('B','A') # 1. Amino Acid Percent aa = pa.get_amino_acids_percent() aa_dict = {"frac_{}".format(k): v for k, v in aa.items()} features.update(aa_dict) # 2. Aromaticity features["aromaticity"] = pa.aromaticity() # 3. Isoelectric Point features["isoelectric"] = pa.isoelectric_point() # 4. Molecular Weight try: features["mol_weight"] = pa.molecular_weight() except ValueError: replaced = str(seq.seq).replace('X', 'G').replace('B', 'N') # 5. Flexibility # try: # features["flexibility"] = np.mean(pa.flexibility()) # except KeyError: # replaced = str(seq.seq).replace('X', 'G').replace('B', 'N').replace('U','C') # features["flexibility"] = np.mean(ProteinAnalysis(replaced).flexibility()) # 6. Secondary Structure Fraction struc = ["struc_helix", "struc_turn", "struc_sheet"] ss = pa.secondary_structure_fraction() features.update(dict(zip(struc, ss))) return features
def get_protein_analysis(aa): protein_analysis = ProteinAnalysis(aa) analyze = [protein_analysis.molecular_weight(), protein_analysis.aromaticity(), protein_analysis.instability_index(), protein_analysis.isoelectric_point(), protein_analysis.gravy()] + list( protein_analysis.secondary_structure_fraction()) return analyze
def get_aromacity(self): """ Calculates Aromacity from sequence (1 value) from biopython :return: dictionary with the value of aromacity """ res = {} analysed_seq = ProteinAnalysis(self.ProteinSequence) res['Aromacity'] = analysed_seq.aromaticity() return res
def processSeq(seq): ''' Protein features found: - Sequence Length - Amino Acid Composition (global) - Amino Acid Composition (First 50/Last 50) - Isoelectric Point - Aromacity - Grand Average Hydropathy (Gravy) - Molecular Weight (global) - Molecular Weight (First 50/Last 50) - Secondary Structure Fraction ''' # seq = str(seq_record.seq) prot = ProteinAnalysis(seq) # desc = str(seq_record.description).split('_') # species = desc[1].split(' ')[0] seq_length = len(seq) isoelectric = prot.isoelectric_point() gravy = calculateGravy(seq, 0, seq_length) aroma = prot.aromaticity() ss_frac = prot.secondary_structure_fraction() mol_global_weight = calculateMolecularWeight(seq, 0, seq_length) AA_global_dist = getAAPercent(seq, 0, seq_length) flex_global = calculateFlexibility(seq, 0, seq_length) if (seq_length > 50): AA_local_head = getAAPercent(seq, 0, 50) AA_local_tail = getAAPercent(seq, seq_length - 50, seq_length) mol_local_weight_head = calculateMolecularWeight(seq, 0, 50) mol_local_weight_tail = calculateMolecularWeight( seq, seq_length - 50, seq_length) flex_localh = calculateFlexibility(seq, 0, 50) flex_localt = calculateFlexibility(seq, seq_length - 50, seq_length) else: AA_local_head = AA_global_dist AA_local_tail = AA_global_dist mol_local_weight_head = mol_global_weight mol_local_weight_tail = mol_global_weight flex_localh = flex_global flex_localt = flex_global return_vector = [seq_length,aroma, isoelectric, mol_global_weight, mol_local_weight_head, mol_local_weight_tail, gravy,flex_global, flex_localh, flex_localt] + \ AA_global_dist + AA_local_head + AA_local_tail + list(ss_frac) # print seq_length, GC_distribution, mol_weight, aroma, isoelectric return return_vector
def find_composition(df_original): df_copy = df_original.copy() column_names = [] for ch in codes: column_names.append(ch + '_percent') column_names.append(ch + '_percent_first') column_names.append(ch + '_percent_last') column_names.append('len') column_names.append('weight') column_names.append('gravy') column_names.append('flex_mean') column_names.append('flex_std') column_names.append('ss_helix') column_names.append('ss_turn') column_names.append('ss_sheet') column_names.append('iep') column_names.append('aromaticity') df = pd.DataFrame(columns=column_names) for _, seq in enumerate(tqdm(df_copy['seq'])): df_temp = pd.Series() sequence = str(seq) analysed = ProteinAnalysis(sequence) analysed_first = ProteinAnalysis(sequence[:first_n]) analysed_last = ProteinAnalysis(sequence[-last_n:]) df_temp['len'] = analysed.length df_temp['ss_helix'], df_temp['ss_turn'], df_temp['ss_sheet'] = analysed.secondary_structure_fraction() df_temp['iep'] = analysed.isoelectric_point() # overall for aa, percent in analysed.get_amino_acids_percent().items(): df_temp[aa + '_percent'] = percent # # first N for aa, percent in analysed_first.get_amino_acids_percent().items(): df_temp[aa + '_percent_first'] = percent # last N for aa, percent in analysed_last.get_amino_acids_percent().items(): df_temp[aa + '_percent_last'] = percent df_temp['weight'] = analysed.molecular_weight() df_temp['gravy'] = analysed.gravy() df_temp['aromaticity'] = analysed.aromaticity() df_temp['flex_mean'] = np.mean(analysed.flexibility()) df_temp['flex_std'] = np.std(analysed.flexibility()) df = df.append(df_temp, ignore_index=True) return pd.concat([df_copy, df], axis=1)
def biopython_protein_analysis(inseq): """Utiize Biopython's ProteinAnalysis module to return general sequence properties of an amino acid string. For full definitions see: http://biopython.org/DIST/docs/api/Bio.SeqUtils.ProtParam.ProteinAnalysis-class.html Args: inseq: Amino acid sequence Returns: dict: Dictionary of sequence properties. Some definitions include: instability_index: Any value above 40 means the protein is unstable (has a short half life). secondary_structure_fraction: Percentage of protein in helix, turn or sheet TODO: Finish definitions of dictionary """ inseq = ssbio.protein.sequence.utils.cast_to_str(inseq) analysed_seq = ProteinAnalysis(inseq) info_dict = {} info_dict['amino_acids_content-biop'] = analysed_seq.count_amino_acids() info_dict[ 'amino_acids_percent-biop'] = analysed_seq.get_amino_acids_percent() info_dict['length-biop'] = analysed_seq.length info_dict['monoisotopic-biop'] = analysed_seq.monoisotopic info_dict['molecular_weight-biop'] = analysed_seq.molecular_weight() info_dict['aromaticity-biop'] = analysed_seq.aromaticity() info_dict['instability_index-biop'] = analysed_seq.instability_index() # TODO: What is flexibility? info_dict['flexibility-biop'] = analysed_seq.flexibility() info_dict['isoelectric_point-biop'] = analysed_seq.isoelectric_point() # grand average of hydrophobicity info_dict['gravy-biop'] = analysed_seq.gravy() # Separated secondary_structure_fraction into each definition # info_dict['secondary_structure_fraction-biop'] = analysed_seq.secondary_structure_fraction() info_dict[ 'percent_helix_naive-biop'] = analysed_seq.secondary_structure_fraction( )[0] info_dict[ 'percent_turn_naive-biop'] = analysed_seq.secondary_structure_fraction( )[1] info_dict[ 'percent_strand_naive-biop'] = analysed_seq.secondary_structure_fraction( )[2] return info_dict
def phyChemProps(seq): svv = [0 for x in range(10)] X = ProteinAnalysis(seq) svv[0] = X.aromaticity() svv[1] = X.secondary_structure_fraction()[0] svv[2] = X.secondary_structure_fraction()[1] svv[3] = X.secondary_structure_fraction()[2] svv[4] = X.gravy() svv[5] = X.instability_index() svv[6] = X.isoelectric_point() svv[7] = X.molecular_weight() svv[8] = X.molar_extinction_coefficient()[0] svv[9] = X.molar_extinction_coefficient()[1] return svv
def biochemical_properties(sequence: str) -> Dict[str, Any]: # Define objects used for calculations analysis_object = ProteinAnalysis(sequence) descriptor_object = PyPro.GetProDes(sequence) sequence_object = Seq(sequence) # TODO(Ahmed): Verify that all these calculations are actually returning reasonable values # For example, it says the percent composition of every amino acid is zero when I run # calculate_biochem_properties.biochemical_properties('qwertyipasdfghklcvnm') return { 'Isoelectric point': analysis_object.isoelectric_point(), 'Molecular weight': analysis_object.molecular_weight(), # Daltons? Amu? g/mol? 'Aromaticity': analysis_object.aromaticity(), 'Instability index': analysis_object.instability_index(), 'GRAVY': analysis_object.gravy(), 'H-bonding percent': h_bonding_percent(sequence), 'Melting temp': melting_temp(sequence), 'LCC': lcc.lcc_simp(sequence) }
def calculate_properties_from_sequence(self): """ Function to calculate some molecular properties based on RDKit functionalities Arguments: Sequence - amino acid sequence of the peptide Return: Average Eisenberg hydrophobicity ProtParam parameters: Isolectric point, aromaticity, instability index, amino acid percentage """ # Hydrophobicity -> Eisenberg scale hydrophobicity = { 'A': 0.620, 'R': -2.530, 'N': -0.780, 'D': -0.900, 'C': 0.290, 'Q': -0.850, 'E': -0.740, 'G': 0.480, 'H': -0.400, 'Y': 0.260, 'I': 1.380, 'L': 1.060, 'K': -1.500, 'M': 0.640, 'F': 1.190, 'P': 0.120, 'S': -0.180, 'T': -0.050, 'W': 0.810, 'V': 1.080 } self.avg_hydro = sum([hydrophobicity[resi] for resi in self.sequence]) # ProParam properties prot_parameters = ProteinAnalysis(self.sequence) self.aromaticity = prot_parameters.aromaticity() self.aa_percent = prot_parameters.get_amino_acids_percent() self.instability_index = prot_parameters.instability_index() self.isoelectric_point = prot_parameters.isoelectric_point()
def __init__(self, sequence): self.sequence = sequence self.sequence_length = len(sequence) analysis = ProteinAnalysis(sequence) self.amino_acid_percents = analysis.get_amino_acids_percent() self.amino_acids_composition = calculate_amino_acids_composition(sequence) self.aromaticity = analysis.aromaticity() self.instability = analysis.instability_index() self.flexibility = calculate_flexibility(sequence) protein_scale_parameters = [{'name': 'Hydrophilicity', 'dictionary': hw}, {'name': 'Surface accessibility', 'dictionary': em}, {'name': 'Janin Interior to surface transfer energy scale', 'dictionary': ja}, {'name': 'Bulkiness', 'dictionary': bulkiness}, {'name': 'Polarity', 'dictionary': polarity}, {'name': 'Buried residues', 'dictionary': buried_residues}, {'name': 'Average area buried', 'dictionary': average_area_buried}, {'name': 'Retention time', 'dictionary': retention_time}] self.protein_scales = calculate_protein_scales(analysis, protein_scale_parameters) self.isoelectric_point = analysis.isoelectric_point() self.secondary_structure_fraction = calculate_secondary_structure_fraction(analysis) self.molecular_weight = analysis.molecular_weight() self.kyte_plot = analysis.gravy() self.pefing = calculate_pefing(sequence) # next parameters are calculated using R.Peptides r('require(Peptides)') r('sequence = "{0}"'.format(sequence)) self.aliphatic_index = r('aindex(sequence)')[0] self.boman_index = r('boman(sequence)')[0] self.charges = calculate_charges(sequence, 1.0, 14.0, 0.5, 'Lehninger') self.hydrophobicity = r('seq(sequence)')[0] angles = [{'name': 'Alpha-helix', 'angle': -47}, {'name': '3-10-helix', 'angle': -26}, {'name': 'Pi-helix', 'angle': -80}, {'name': 'Omega', 'angle': 180}, {'name': 'Antiparallel beta-sheet', 'angle': 135}, {'name': 'Parallel beta-sheet', 'angle': 113}] if self.amino_acid_percents['P'] + self.amino_acid_percents['G'] > 0.3: angles.append({'name': 'Polygly-polypro helix', 'angle': 153}) self.hydrophobic_moments = calculate_hydrophobic_moments(sequence, angles) self.kidera_factors = calculate_kidera_factors(sequence) self.peptide_types = calculate_peptide_types(sequence, angles)
def protein_analysis(): if session.username == None: redirect(URL(r=request,f='../account/log_in')) from Bio.SeqUtils.ProtParam import ProteinAnalysis form = FORM(TABLE( TR("Amino acid sequence: ", TEXTAREA(_type="text", _name="sequence", requires=IS_NOT_EMPTY())), INPUT(_type="submit", _value="SUBMIT"))) if form.accepts(request.vars,session): session['sequence'] = seqClean(form.vars.sequence.upper()) X = ProteinAnalysis(session['sequence']) session['aa_count'] = X.count_amino_acids() session['percent_aa'] = X.get_amino_acids_percent() session['mw'] = X.molecular_weight() session['aromaticity'] = X.aromaticity() session['instability'] = X.instability_index() session['flexibility'] = X.flexibility() session['pI'] = X.isoelectric_point() session['sec_struct'] = X.secondary_structure_fraction() redirect(URL(r=request, f='protein_analysis_output')) return dict(form=form)
def GRAvy_ARomo(seq, genetic_code_=1, G=False, A=False): """calculating Gravy and Aroma for DNA sequence. Args: seq (str):DNA sequence genetic_code_(int): default = 1, The Genetic Codes number described by NCBI (https://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi) G (bool): default = False A (bool): default = False Returns: - Gravy value if arg(G) is True - Aroma value if arg(A) is True - None if both args are False """ from Bio.SeqUtils.ProtParam import ProteinAnalysis from Bio.Seq import Seq try: seq = Seq(seq) except: pass translate_seq = str(seq.translate(table=genetic_code_)) protein_seq = translate_seq.replace("*", "") protein_seq = ProteinAnalysis(protein_seq) AROMO = protein_seq.aromaticity() gravy = protein_seq.gravy() if G and G == True: return gravy elif A and A == True: return AROMO
def get_features(seq): """get global features from a protein sequence Parameters ---------- seq : str protein sequence Return ---------- dictionary: global features of the protein sequence """ features = {} features['undefined_count'] = len([x for x in seq if x in ['X','B','Z',"'",'O','U']]) features['length'] = len(seq) features['perc_undefined_count'] = features['undefined_count']/features['length'] features['entropy'] = entropy(seq) features['ideal_entropy'] = entropy_ideal(len(seq)) features['perc_entropy'] = features['entropy']/features['ideal_entropy'] features['hydr_count'] = sum(1 for x in seq if x in hydrophobic_proteins) features['polar_count'] = sum(1 for x in seq if x in polar_proteins) features['buried'] = sum(buried[x] for x in seq if x in hydrophobic_proteins) seq = ''.join([x for x in seq if x not in ['X','B','Z',"'",'O','U']]) protein = ProteinAnalysis(seq) features['gravy'] = protein.gravy() features['molecular_weight'] = protein.molecular_weight() features['aromaticity'] = protein.aromaticity() features['instability_index'] = protein.instability_index() features['isoelectric_point'] = protein.isoelectric_point() features['helix'], features['turn'], features['sheet'] = protein.secondary_structure_fraction() features.update(protein.count_amino_acids()) # features.update(protein.get_amino_acids_percent()) return features
def GetFeatures (My_seq): Features = {} ProteinAnalysis(My_seq) analysed_seq = ProteinAnalysis(My_seq) #Caracteristicas monovaloradas Features["Molecular_weight"] = analysed_seq.molecular_weight() Features["Aromaticity"] = analysed_seq.aromaticity() Features["Instability_index"] = analysed_seq.instability_index() Features["Isoelectric_point"] = analysed_seq.isoelectric_point() #Caracteristicas multivaloradas Features["Flexibility"] = analysed_seq.flexibility() # List 580 Features["Second_structure_fraction"] = analysed_seq.secondary_structure_fraction() #3 Tupla Features["Count_amino_acids"] = analysed_seq.count_amino_acids() #20 Dict Features["Amino_acids_percent"] = analysed_seq.get_amino_acids_percent() #20 Dict return Features
def seqs_to_features(self, seqs, no_seqs): """ Extract the features from the sequences.""" X = np.zeros((no_seqs, 32)) for i, s in enumerate(chain(*seqs)): # iterate over all sequences # get amino acid counts alphabet = 'ABCDEFGHIKLMNPQRSTUVWXY' # no JOZ for j, letter in enumerate(alphabet): X[i, j] = s.count(letter) / len(s) # other analysis analysis = ProteinAnalysis( s.replace('X', 'A').replace('B', 'A').replace('U', 'A')) X[i, -1] = analysis.molecular_weight() X[i, -2] = analysis.aromaticity() X[i, -3] = analysis.instability_index() X[i, -4] = analysis.isoelectric_point() helix_array_sheet_fracs = analysis.secondary_structure_fraction() X[i, -5] = helix_array_sheet_fracs[0] X[i, -6] = helix_array_sheet_fracs[1] X[i, -7] = helix_array_sheet_fracs[2] X[i, -8] = len(s) X[i, -9] = analysis.gravy() # mean hydrophobicity return X
def physchem_props(ara_d): """Calculate the physicochemical properties per protein in ara_d.""" c = 0 g = 0 for protein in ara_d: seq = ara_d[protein]["sequence"] # Calculates the properties if "X" in seq: continue # Skip non-usable sequences, only negs if '*' in seq: if ara_d[protein]["pos"] != []: print(protein) continue a_seq = ProteinAnalysis(seq) # Update ara_d with new physchem properties results = [ a_seq.molecular_weight(), a_seq.gravy(), a_seq.aromaticity(), a_seq.instability_index(), a_seq.flexibility(), a_seq.isoelectric_point(), a_seq.secondary_structure_fraction(), ] keys = [ "mol_weight", "gravy", "aromaticity", "instab_index", "flexi", "iso_point", "seq_struct", ] ara_d[protein]["Properties"] = {} for k, v in zip(keys, results): ara_d[protein]["Properties"][k] = v return ara_d
def parse_nuc_sequence(self, n_seq, id=None, desc=None): """ Parses valid RNA sequence, translates nucleotides, calculates GC content and other methods available from ProteinAnalysis() in BioPython module. Keyword arguments: seq -- valid string sequence id -- id obtained from FASTA file record (default None) desc -- description obtained from FASTA file record (default None) """ try: # append fasta sequence metadata self.id.append(id) self.description.append(desc) self.nucleotide_sequence.append(n_seq) # translate nucleotide string sequence p_seq = self.translate_nucleotides(n_seq) self.protein_sequence.append(p_seq) # self.protein_sequence.append(str(record.seq.translate()).replace('*', ' ')) # GC content self.gc_content.append(self.calculate_gc_content(n_seq)) # protein analysis methods analysis = ProteinAnalysis(p_seq) self.amino_acid_dict.append(analysis.get_amino_acids_percent()) self.molecular_weight.append(analysis.molecular_weight()) self.instability_index.append(analysis.instability_index()) self.aromaticity.append(analysis.aromaticity()) except Exception as e: print('-'*80) print(f"Exception in parsing uploaded virus sequence: {e}") traceback.print_exc(file=sys.stdout) print('-'*80)
def add_protein_characteristics(df): df = df.copy() aa_list = [ 'A', 'C', 'E', 'D', 'G', 'F', 'I', 'H', 'K', 'M', 'L', 'N', 'Q', 'P', 'S', 'R', 'T', 'W', 'V', 'Y' ] aa_dict = {} for aa in aa_list: aa_dict[aa] = [] prop_dict = { 'aromaticity': [], 'helix': [], 'turn': [], 'sheet': [], 'isoelectric_point': [], 'gravy': [] } #, 'flexibility': [], 'instability_index': []} for i, s in enumerate(df['sequence']): s = s.replace('B', 'D').replace('Z', 'E').replace('J', 'L').replace( 'X', 'G').replace('U', 'C').replace('O', 'K') pa = ProteinAnalysis(s) prop_dict['aromaticity'].append(pa.aromaticity()) prop_dict['isoelectric_point'].append(pa.isoelectric_point()) prop_dict['gravy'].append(pa.gravy()) # prop_dict['instability_index'].append(pa.instability_index()) # prop_dict['flexibility'].append(np.mean(pa.flexibility())) for fraction, ss in zip(pa.secondary_structure_fraction(), ['helix', 'turn', 'sheet']): prop_dict[ss].append(fraction) for k, v in pa.get_amino_acids_percent().items(): aa_dict[k].append(v) for k, v in aa_dict.items(): df[k] = v for k, v in prop_dict.items(): df[k] = v return df
isoelectricPt=[] aromaticity=[] aminoPercent=[] secstruct=[] hydrophob=[] hydrophil=[] surface=[] gravy=[] molweight=[] instidx=[] flex=[] for seq in sequences: X=ProteinAnalysis(str(seq)) isoelectricPt.append(X.isoelectric_point()) aromaticity.append(X.aromaticity()) aminoPercent.append(X.get_amino_acids_percent()) secstruct.append(X.secondary_structure_fraction()) # These features throw Key & Value Errors due to non standard amino acids # (i.e. out of the 20 standard ones) e.g. X, U etc try: gravy.append(X.gravy()) molweight.append(X.molecular_weight()) instidx.append(X.instability_index()) flex.append(X.flexibility()) hydrophob.append(X.protein_scale(ProtParamData.kd, 9, 0.4)) hydrophil.append(X.protein_scale(ProtParamData.hw, 9, 0.4)) surface.append(X.protein_scale(ProtParamData.em, 9, 0.4)) except (KeyError,ValueError):
from Bio.SeqUtils.ProtParam import ProteinAnalysis from Bio.SeqUtils import ProtParamData from Bio import SeqIO with open('../../samples/pdbaa') as fh: for rec in SeqIO.parse(fh,'fasta'): myprot = ProteinAnalysis(str(rec.seq)) print(myprot.count_amino_acids()) print(myprot.get_amino_acids_percent()) print(myprot.molecular_weight()) print(myprot.aromaticity()) print(myprot.instability_index()) print(myprot.flexibility()) print(myprot.isoelectric_point()) print(myprot.secondary_structure_fraction()) print(myprot.protein_scale(ProtParamData.kd, 9, .4))
total_area.append(list_areas[2]) print('done') with temppathlib.TemporaryDirectory() as tmpdir: # unzip the file with all the test PDBs with zipfile.ZipFile(args.infile, "r") as zip_: zip_.extractall(tmpdir.path) for test_pdb in tmpdir.path.glob("*.pdb"): for record in SeqIO.parse(test_pdb, "pdb-atom"): sequence = str(record.seq).replace('X', 'G') protein = ProteinAnalysis(str(sequence)) p_len.append(len(sequence)) mol_w.append(protein.molecular_weight()) iso_p.append(protein.isoelectric_point()) smell.append(protein.aromaticity()) taste_factor.append(protein.gravy()) insta_ind.append(protein.instability_index()) char_at_acid.append(protein.charge_at_pH(1)) char_at_neutral.append(protein.charge_at_pH(7)) char_at_base.append(protein.charge_at_pH(14)) helter_skeler.append(protein.secondary_structure_fraction()[0]) turnip.append(protein.secondary_structure_fraction()[1]) garfield.append(protein.secondary_structure_fraction()[2]) for x in amino_acids: n = protein.count_amino_acids()[x] for y in d_count.keys(): if y[-1] == x: d_count[y].append(n) for a in amino_acids: m = protein.get_amino_acids_percent()[a]
#!/usr/bin/env python import sys from Bio import SeqIO from Bio.SeqUtils.ProtParam import ProteinAnalysis sys.stdout.write("ID\tMW\tIP\tgravy\tlength\tinstability\tmonoisotpoic\tSequence\n") for record in SeqIO.parse(sys.stdin, "fasta"): a = ProteinAnalysis(str(record.seq)) properties = list() properties.append(record.id) properties.append(a.molecular_weight()) properties.append(a.isoelectric_point()) properties.append(a.gravy()) properties.append(a.length) properties.append(a.instability_index()) properties.append(a.aromaticity()) # always last column to make the output more readable properties.append(a.sequence) sys.stdout.write( '\t'.join(map(str, properties))+"\n" )