### Install pyBioMed Source: https://github.com/abdulk084/cardiotox/blob/master/README.md Installs the pyBioMed library by running its setup script. Navigate to the PyBioMed directory first. ```bash cd PyBioMed python setup.py install cd .. ``` -------------------------------- ### Install CardioTox Environment Source: https://context7.com/abdulk084/cardiotox/llms.txt Set up the required conda environment and install the PyBioMed dependency. ```bash # Create and activate conda environment conda env create -f environment.yml conda activate cardiotox # Install PyBioMed dependency cd PyBioMed python setup.py install cd .. # Verify installation python test.py ``` -------------------------------- ### Test PyBioMed installation Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/test.md Use this command to verify that the PyBioMed package is correctly installed and functional. ```pycon >>> from PyBioMed.test import test_PyBioMed >>> test_PyBioMed.test_pybiomed() ``` -------------------------------- ### Create Conda Environment Source: https://github.com/abdulk084/cardiotox/blob/master/README.md Restores the project's environment from the 'environment.yml' file. Ensure conda is installed and accessible. ```bash conda env create -f environment.yml ``` -------------------------------- ### Predict hERG Blockade with Ensemble Model (Single SMILE) Source: https://github.com/abdulk084/cardiotox/blob/master/README.md Loads the ensemble model and predicts hERG channel blockade for a single molecule represented by its SMILES string. Requires the 'cardiotox' library to be installed. ```python import cardiotox smile = "CC(=O)SC1CC2=CC(=O)CCC2(C)C2CCC3C(CCC34CCC(=O)O4)C12" model = cardiotox.load_ensemble() model.predict(smile) ``` -------------------------------- ### Load DNA Sequences from FASTA Files Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/build/lib/PyBioMed/doc/application.md Loads positive and negative DNA sequence data from FASTA files using PyBioMed's GetDNA module. Requires specifying the correct path to the example files. ```python import pandas as pd from PyBioMed import Pydna from PyBioMed.PyGetMol import GetDNA import numpy as np from sklearn.ensemble import RandomForestClassifier as RF from sklearn import cross_validation from sklearn import metrics from matplotlib import pyplot as plt #============================================================================== # loading data #============================================================================== path = 'PyBioMed package real path in your computer' # input the real path in your own computer seqs_pos = GetDNA.ReadFasta(open(path + '/example/dna/H_sapiens_pos.fasta')) seqs_neg = GetDNA.ReadFasta(open(path + '/example/dna/H_sapiens_neg.fasta')) ``` -------------------------------- ### Load DNA Sequences from FASTA Files Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/application.md Loads positive and negative DNA sequences from FASTA files using PyBioMed's GetDNA module. Ensure the 'path' variable points to the correct location of the example files. ```python import pandas as pd from PyBioMed import Pydna from PyBioMed.PyGetMol import GetDNA import numpy as np from sklearn.ensemble import RandomForestClassifier as RF from sklearn import cross_validation from sklearn import metrics from matplotlib import pyplot as plt #============================================================================== # loading data #============================================================================== path = 'PyBioMed package real path in your computer' # input the real path in your own computer seqs_pos = GetDNA.ReadFasta(open(path + '/example/dna/H_sapiens_pos.fasta')) seqs_neg = GetDNA.ReadFasta(open(path + '/example/dna/H_sapiens_neg.fasta')) #============================================================================== ``` -------------------------------- ### Get Kappa Descriptors from DrugBank ID Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/User_guide.md Retrieve a molecule's SMILES string from DrugBank using its ID, then read it into a PyMolecule object to calculate Kappa descriptors. ```python from PyBioMed import Pymolecule DrugBankID = 'DB01014' mol = Pymolecule.PyMolecule() smi = mol.GetMolFromDrugbank(DrugBankID) mol.ReadMolFromSmile(smi) molecular_descriptor = mol.GetKappa() print molecular_descriptor ``` -------------------------------- ### Protein Subcellular Location Prediction Setup Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/build/lib/PyBioMed/doc/application.md Loads protein sequence data for Cytoplasm and Nuclear locations from text files using PyBioMed. This script prepares the data for feature extraction and subsequent classification model building. ```python import pandas as pd from PyBioMed.PyProtein.CTD import CalculateCTD import numpy as np from sklearn.ensemble import RandomForestClassifier as RF from sklearn import cross_validation from sklearn import metrics from matplotlib import pyplot as plt #============================================================================== # loading the data #============================================================================== path = 'input PyBioMed path in your computer' #input the PyBioMed path in your own computer f = open(path + 'example/subcell/Cytoplasm_seq.txt','r') cytoplasm = [line.replace('\n','') for line in f.readlines() if line != '\n'] f.close() f = open(path + 'example/subcell/Nuclear_seq.txt','r') nuclear = [line.replace('\n','') for line in f.readlines() if line != '\n'] f.close() #============================================================================== ``` -------------------------------- ### Calculate DNA Descriptors Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/application.md Calculates a comprehensive set of descriptors for a given DNA sequence using Pydna. Includes descriptors like DAC, PseDNC, PseKNC, and SCPseDNC. Ensure Pydna library is installed. ```python def calculate_des(seq): des = [] dnaclass = Pydna.PyDNA(seq) des.extend(dnaclass.GetDAC(all_property=True).values()) des.extend(dnaclass.GetPseDNC(all_property=True,lamada=2, w=0.05).values()) des.extend(dnaclass.GetPseKNC(all_property=True,lamada=2, w=0.05).values()) des.extend(dnaclass.GetSCPseDNC(all_property=True).values()) return des ``` -------------------------------- ### Get Probability Distribution Source: https://context7.com/abdulk084/cardiotox/llms.txt Retrieve class probabilities for both non-hERG and hERG blocker categories. ```python import cardiotox model = cardiotox.load_ensemble() smile = "CCCCCCCCCC[N+](CC)(CC)CC" # Get class probabilities [non-hERG, hERG] probabilities = model.predict_probabilities([smile]) print(f"Non-hERG probability: {probabilities[0][0]:.3f}") print(f"hERG blocker probability: {probabilities[0][1]:.3f}") # Output: # Non-hERG probability: 0.156 # hERG blocker probability: 0.844 ``` -------------------------------- ### Calculate Charge Descriptors via PyMolecule Object Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/User_guide.md Instantiate PyMolecule, read a molecule from a MOL file, and then use GetCharge to calculate charge descriptors. Note: Ensure the path to the MOL file is correct. ```python from PyBioMed import Pymolecule mol = Pymolecule.PyMolecule() mol.ReadMolFromMol('test/test_data/test.mol') #change path to the real path in your own computer molecular_descriptor = mol.GetCharge() print molecular_descriptor ``` -------------------------------- ### Calculate Molecular Fingerprints Source: https://context7.com/abdulk084/cardiotox/llms.txt Demonstrates the calculation of different molecular fingerprints (ECFP4, PubChem, MACCS) and how to use the PyMolecule object for fingerprint generation. ```python from PyBioMed.PyFingerprint import CalculateECFP4Fingerprint, CalculatePubChemFingerprint, CalculateMACCSFingerprint from PyBioMed.PyMolecule import Pymolecule # Assuming 'mol' and 'smi' are pre-defined molecule and SMILES objects # ecfp4 = CalculateECFP4Fingerprint(mol) # print(f"ECFP4 fingerprint bits set: {len(ecfp4[1])}") # pubchem = CalculatePubChemFingerprint(mol) # print(f"PubChem fingerprint length: {len(pubchem)}") # maccs = CalculateMACCSFingerprint(mol) # print(f"MACCS fingerprint length: {len(maccs[0])}") # Using PyMolecule object for fingerprints pymol = Pymolecule.PyMolecule() pymol.ReadMolFromSmile(smi) fp = pymol.GetFingerprint(FPName='ECFP4') print(f"\nECFP4 via PyMolecule: {len(fp[1])} bits set") ``` -------------------------------- ### Get DNA Sequence from Gene ID Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/build/lib/PyBioMed/doc/User_guide.md Retrieves a DNA sequence using a Gene ID from a website. Requires the GetDNA module. ```python from PyBioMed.PyGetMol import GetDNA seq = GetDNA.GetDNAFromUniGene('AA954964') print seq ``` -------------------------------- ### Access Preprocessing Functions Source: https://context7.com/abdulk084/cardiotox/llms.txt Shows how to manually preprocess SMILES strings into features and run predictions on those pre-computed features. ```python from cardiotox import SVModel, DescModel import numpy as np smiles = ["CCCCCCCCCC[N+](CC)(CC)CC", "CC(N)C(=O)O"] # SMILES Vector model preprocessing (converts to character token indices) sv_model = SVModel() sv_features = sv_model.preprocess_smile(smiles) print(f"SV features shape: {sv_features.shape}") # (2, 97) - padded token sequences print(f"First molecule tokens: {sv_features[0][:10]}") # Run prediction on preprocessed features sv_prediction = sv_model.predict_preprocessed(sv_features) print(f"SV prediction: {sv_prediction}") # Descriptor model preprocessing (calculates Mordred descriptors) desc_model = DescModel() desc_features = desc_model.preprocess_smile(smiles) print(f"Descriptor features shape: {desc_features.shape}") # (2, 995) - normalized descriptors # Run prediction on preprocessed descriptors desc_prediction = desc_model.predict_preprocessed(desc_features) print(f"Descriptor prediction: {desc_prediction}") ``` -------------------------------- ### Calculate Molecular Descriptors Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/build/lib/PyBioMed/doc/application.md Calculates molecular descriptors using PyBioMed's Pymolecule class. Reads a SMILES string and returns a DataFrame of descriptors. Ensure PyBioMed and pandas are installed. ```python from PyBioMed import Pymolecule import pandas as pd import numpy as np from sklearn import cross_validation from sklearn.ensemble import RandomForestRegressor from matplotlib import pyplot as plt from sklearn.cross_validation import train_test_split from sklearn import metrics #============================================================================== # loading the data #============================================================================== #change the path to your own path solubility_set = pd.read_excel('./example/solubility/Solubility-total.xlsx',sheetname = 0) smis = solubility_set['SMI'] logS = solubility_set['logS'] #============================================================================== # #calculating molecular descriptors #============================================================================== def calculate_des(smi): des = {} drugclass=Pymolecule.PyMolecule() drugclass.ReadMolFromSmile(smi) des.update(drugclass.GetEstate()) des.update(drugclass.GetMOE()) return pd.DataFrame({smi:(des)}).T solubility_set_des = pd.concat(map(calculate_des,list(smis))) ``` -------------------------------- ### Use Individual Models Source: https://context7.com/abdulk084/cardiotox/llms.txt Access and use the four individual models provided by the library independently. ```python from cardiotox import DescModel, SVModel, FVModel, FingerprintModel smile = "CCCCCCCCCC[N+](CC)(CC)CC" ``` -------------------------------- ### Run Individual Model Prediction Source: https://github.com/abdulk084/cardiotox/blob/master/README.md Instantiates and uses an individual prediction model (e.g., SVModel) similarly to the ensemble model. Requires the specific model class to be imported. ```python from cardiotox import SVModel smile = "CCCCCCCCCC[N+](CC)(CC)CC" model = SVModel() model.predict(smile) ``` -------------------------------- ### Retrieve Molecules from Databases Source: https://context7.com/abdulk084/cardiotox/llms.txt Shows how to retrieve molecular structures from online databases like DrugBank, NCBI PubChem, KEGG, and CAS using their respective IDs. Includes conversion to RDKit mol object. ```python from PyBioMed.PyGetMol import Getmol from PyBioMed.PyGetMol.Getmol import ReadMolFromSmile # Get molecule from DrugBank drugbank_id = 'DB01014' # Balsalazide smi = Getmol.GetMolFromDrugbank(drugbank_id) print(f"DrugBank {drugbank_id}: {smi}") # Get molecule from NCBI PubChem cid = "2244" # Aspirin smi = Getmol.GetMolFromNCBI(cid=cid) print(f"PubChem CID {cid}: {smi}") # Get molecule from KEGG kegg_id = "D02176" # Carnitine smi = Getmol.GetMolFromKegg(kid=kegg_id) print(f"KEGG {kegg_id}: {smi}") # Get molecule from CAS cas_id = "50-12-4" # Mephenytoin smi = Getmol.GetMolFromCAS(casid=cas_id) print(f"CAS {cas_id}: {smi}") # Convert SMILES to RDKit mol object mol = ReadMolFromSmile(smi) print(f"RDKit mol object: {mol}") ``` -------------------------------- ### Calculate All Descriptors (excluding fingerprints) Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/User_guide.md Read a molecule from SMILES into a PyMolecule object and then call GetAllDescriptor to compute all available molecular descriptors, excluding fingerprints. The total count is printed. ```python from PyBioMed import Pymolecule smi = 'CCOC=N' mol = Pymolecule.PyMolecule() mol.ReadMolFromSmile(smi) alldes = mol.GetAllDescriptor() print len(alldes) ``` -------------------------------- ### Calculate E-state Descriptors via PyMolecule Object Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/User_guide.md Instantiate the PyMolecule class, read a molecule from SMILES format, and then call the GetEstate method to calculate E-state descriptors. The length of the returned dictionary is printed. ```python from PyBioMed import Pymolecule smi = 'CCC1(c2ccccc2)C(=O)N(C)C(=N1)O' mol = Pymolecule.PyMolecule() mol.ReadMolFromSmile(smi) molecular_descriptor = mol.GetEstate() print len(molecular_descriptor) ``` -------------------------------- ### Prepare Feature Matrix and Labels for Cross-Validation Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/build/lib/PyBioMed/doc/application.md Combines the calculated descriptors for positive and negative pairs into a single feature matrix (X) and creates a corresponding label vector (y). This prepares the data for training and evaluating a machine learning model. ```python x = np.array(pd.concat([pd.DataFrame(positive_pairs_des).T, pd.DataFrame(negative_pairs_des).T], join_axes=[pd.DataFrame(positive_pairs_des).T.columns],axis = 0, ignore_index=True)) positive_count, negative_count = len(positive_pairs_des), len(negative_pairs_des) y = np.array([1]*positive_count+ [0]*negative_count) ``` -------------------------------- ### Load Protein Sequence Data Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/application.md This code loads protein sequences from text files for Cytoplasm and Nuclear locations. It reads each line, removes newline characters, and stores them in lists. Ensure the 'path' variable points to the correct PyBioMed installation directory. ```python import pandas as pd from PyBioMed.PyProtein.CTD import CalculateCTD import numpy as np from sklearn.ensemble import RandomForestClassifier as RF from sklearn import cross_validation from sklearn import metrics from matplotlib import pyplot as plt path = 'input PyBioMed path in your computer' #input the PyBioMed path in your own computer f = open(path + 'example/subcell/Cytoplasm_seq.txt','r') cytoplasm = [line.replace(' ','') for line in f.readlines() if line != ' '] f.close() f = open(path + 'example/subcell/Nuclear_seq.txt','r') nuclear = [line.replace(' ','') for line in f.readlines() if line != ' '] f.close() ``` -------------------------------- ### Calculate Molecular Fingerprints with PyBioMed Source: https://context7.com/abdulk084/cardiotox/llms.txt Demonstrates how to generate different types of molecular fingerprints using PyBioMed utilities. ```python from PyBioMed import Pymolecule from PyBioMed.PyMolecule.fingerprint import ( CalculateECFP2Fingerprint, CalculateECFP4Fingerprint, CalculatePubChemFingerprint, CalculateMACCSFingerprint ) from rdkit import Chem smi = "CC(N)C(=O)O" mol = Chem.MolFromSmiles(smi) # ECFP2 fingerprint (used in FingerprintModel) ecfp2 = CalculateECFP2Fingerprint(mol) print(f"ECFP2 fingerprint bits set: {len(ecfp2[1])}") ``` -------------------------------- ### Read molecular structures from input Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/User_guide.md Load molecules from SMILES strings or SDF files using the Getmol module. ```python >>> from PyBioMed.PyGetMol.Getmol import ReadMolFromSmile >>> mol = ReadMolFromSmile('N[C@@H](CO)C(=O)O') >>> print mol ``` ```python >>> from PyBioMed.PyGetMol.Getmol import ReadMolFromSDF >>> mol = ReadMolFromSDF('./PyBioMed/test/test_data/test.sdf') #You should change the path to your own real path >>> print mol ``` -------------------------------- ### Build and Predict Aqueous Solubility Model Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/application.md Builds a Random Forest Regressor model for aqueous solubility prediction and evaluates it using cross-validation and a test set. Requires pre-loaded data and calculated molecular descriptors. ```python from sklearn import cross_validation from sklearn.ensemble import RandomForestRegressor from matplotlib import pyplot as plt from sklearn.cross_validation import train_test_split from sklearn import metrics import pandas as pd import numpy as np from PyBioMed import Pymolecule # loading the data solubility_set = pd.read_excel('./example/solubility/Solubility-total.xlsx',sheetname = 0) smis = solubility_set['SMI'] logS = solubility_set['logS'] # calculating molecular descriptors def calculate_des(smi): des = {} drugclass=Pymolecule.PyMolecule() drugclass.ReadMolFromSmile(smi) des.update(drugclass.GetEstate()) des.update(drugclass.GetMOE()) return pd.DataFrame({smi:(des)}).T solubility_set_des = pd.concat(map(calculate_des,list(smis))) solubility_set_des = np.array(solubility_set_des) logS = np.array(logS) # building the model and predict train_set_des, test_set_des, train_logS, test_logS = train_test_split(solubility_set_des, logS, test_size = 0.33, random_state = 42) kf = cross_validation.KFold(train_set_des.shape[0], n_folds=10, random_state=0) clf = RandomForestRegressor(n_estimators=500, max_features='auto', n_jobs = -1) CV_pred_logS = [] VALIDATION_index = [] for train_index, validation_index in kf: VALIDATION_index = VALIDATION_index + list(validation_index) clf.fit(train_set_des[train_index ,:],train_logS[train_index]) pred_logS = clf.predict(train_set_des[validation_index,:]) CV_pred_logS = CV_pred_logS + list(pred_logS) CV_true_logS = train_logS[VALIDATION_index] r2_CV = metrics.r2_score(CV_true_logS, CV_pred_logS) clf.fit(train_set_des,train_logS) pred_logS_test = clf.predict(test_set_des) r2_test = metrics.r2_score(test_logS, pred_logS_test) # plotting the figure plt.figure(figsize = (10,10)) plt.plot(range(-15,5),range(-15,5),'black') plt.plot(CV_true_logS,CV_pred_logS,'b.',label = 'cross validation', alpha = 0.5 ) plt.plot(test_logS,pred_logS_test,'r.',label = 'test set',alpha = 0.5) plt.title('Aqueous Solubility Prediction',{'fontsize':25}) plt.legend(loc="lower right",numpoints=1) plt.plot() ``` -------------------------------- ### Test CardioTox Model Source: https://github.com/abdulk084/cardiotox/blob/master/README.md Runs the main test script to evaluate the model on external datasets mentioned in the paper. This serves as a basic functionality check. ```bash python test.py ``` -------------------------------- ### Load Ensemble Model Source: https://context7.com/abdulk084/cardiotox/llms.txt Initialize the stacked ensemble model and access individual member models if required. ```python import cardiotox # Load the pre-trained ensemble model model = cardiotox.load_ensemble() # The model contains 4 member models: fp (fingerprint), dm (descriptor), sv (SMILES vector), fv (fingerprint vector) # Access individual models if needed fp_model = model.get_model("fp") desc_model = model.get_model("dm") sv_model = model.get_model("sv") fv_model = model.get_model("fv") ``` -------------------------------- ### Read protein sequences from FASTA files Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/User_guide.md Parse protein sequences from a FASTA file using the ReadFasta utility. ```python >>> from PyBioMed.PyGetMol.GetProtein import ReadFasta >>> f = open('./PyBioMed/test/test_data/protein.fasta') #You should change the path to your own real path >>> protein_seq = ReadFasta(f) >>> print protein ['MLIHQYDHATAQYIASHLADPDPLNDGRWLIPAFATATPLPERPARTWPFFLDGAWVLRPDHRGQRLYRTDTGEAAEIVAAG IAPEAAGLTPTPRPSDEHRWIDGAWQIDPQIVAQRARDAAMREFDLRMASARQANAGRADAYAAGLLSDAEIAVFKAWAIYQMD LVRVVSAASFPDDVQWPAEPDEAAVIEQADGKASAGDAAAA', 'MLIHQYDHATAQYIASHLADPDPLNDGRWLIPAFATATPLPERPARTWPFFLDGAWVLRPDHRGQRLYRTDTGEAAEIVAAGI APEAAGLTPTPRPSDEHRWIDGAWQIDPQIVAQRARDAAMREFDLRMASARQANAGRADAYAAGLLSDAEIAVFKAWAIYQMDL VRVVSAASFPDDVQWPAEPDEAAVIEQADGKASAGDAAAA'] ``` -------------------------------- ### Import Individual CardioTox Models Source: https://github.com/abdulk084/cardiotox/blob/master/README.md Imports specific model classes from the 'cardiotox' library. Choose the model class corresponding to the desired prediction task. ```python from cardiotox import DescModel, SVModel, FVModel, FingerprintModel ``` -------------------------------- ### Print evaluation results Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/build/lib/PyBioMed/doc/application.md Displays the final performance metrics calculated during validation. ```pycon >>> print 'sensitivity:',TPR, 'specificity:', SPE, 'accuracy:', ACC, 'AUC:', AUC_score, 'MACCS:', matthews_corrcoef, 'F1:', f1_score sensitivity: 0.82 specificity: 0.80 accuracy: 0.81 AUC: 0.88 MACCS: 0.62 F1: 0.81 ``` -------------------------------- ### Fetch Protein Sequence from Uniprot and Calculate CTD Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/build/lib/PyBioMed/doc/User_guide.md Fetches a protein sequence from Uniprot using its ID and then calculates the குறித்து Composition (CTD) descriptor. Requires importing Pyprotein and GetProteinSequence. ```python >>> from PyBioMed import Pyprotein >>> from PyBioMed.PyProtein.GetProteinFromUniprot import GetProteinSequence >>> uniprotID = 'P48039' >>> protein_sequence = GetProteinSequence(uniprotID) >>> print protein_sequence MEDINFASLAPRHGSRPFMGTWNEIGTSQLNGGAFSWSSLWSGIKNFGSSIKSFGNKAWNSNTGQMLRDKLKDQNFQQKVVDGL ASGINGVVDIANQALQNQINQRLENSRQPPVALQQRPPPKVEEVEEKLPPLEVAPPLPSKGEKRPRPDLEETLVVESREPPS YEQALKEGASPYPMTKPIGSMARPVYGKESKPVTLELPPPVPTVPPMPAPTLGTAVSRPTAPTVAVATPARRPRGANWQSTLNS IVGLGVKSLKRRRCY >>> protein_class = Pyprotein.PyProtein(protein_sequence) >>> CTD = protein_class.GetCTD() >>> print len(CTD) 147 ``` -------------------------------- ### Calculate Protein Descriptors Source: https://context7.com/abdulk084/cardiotox/llms.txt Shows how to calculate various protein sequence-based features, including amino acid composition, dipeptide composition, CTD descriptors, and comprehensive feature sets using the PyProtein object. ```python from PyBioMed import Pyprotein from PyBioMed.PyProtein import AAComposition, CTD protein_seq = "ADGCGVGEGTGQGPMCNCMCMKWVYADEDAADLESDSFADEDASLESDSFPWSNQRVFCSFADEDAS" # Calculate amino acid composition aac = AAComposition.CalculateAAComposition(protein_seq) print(f"Amino acid composition: {len(aac)} features") print(f"Alanine (A): {aac['A']:.2f}%, Cysteine (C): {aac['C']:.2f}%") # Calculate dipeptide composition dpc = AAComposition.CalculateDipeptideComposition(protein_seq) print(f"\nDipeptide composition: {len(dpc)} features") # Calculate CTD (Composition, Transition, Distribution) descriptors ctd = CTD.CalculateCTD(protein_seq) print(f"\nCTD descriptors: {len(ctd)} features") # Using PyProtein object for comprehensive feature calculation protein = Pyprotein.PyProtein(protein_seq) # Get all descriptors except tripeptide (10049 features) all_features = protein.GetALL() print(f"\nTotal protein features: {len(all_features)}") # Get specific feature types autocorr = protein.GetMoreauBrotoAuto() print(f"Moreau-Broto autocorrelation: {len(autocorr)} features") quasi_seq = protein.GetQuasiSequenceOrder() print(f"Quasi-sequence order: {len(quasi_seq)} features") ``` -------------------------------- ### Pretreat Molecular Structures Source: https://context7.com/abdulk084/cardiotox/llms.txt Demonstrates molecular structure standardization and preprocessing, including full pipeline standardization of SMILES and individual operations like disconnecting metal atoms using the StandardizeMol class. ```python from PyBioMed.PyPretreat import PyPretreatMol from PyBioMed.PyPretreat.PyPretreatMol import StandardizeMol from rdkit import Chem # Standardize a SMILES string (full preprocessing pipeline) raw_smi = '[Na]OC(=O)c1ccc(C[S+2]([O-])([O-]))cc1' standardized_smi = PyPretreatMol.StandardSmi(raw_smi) print(f"Raw: {raw_smi}") print(f"Standardized: {standardized_smi}") # Use StandardizeMol class for individual operations mol = Chem.MolFromSmiles('[Na]OC(=O)c1ccc(C[S+2]([O-])([O-]))cc1') sdm = StandardizeMol() # Disconnect metal atoms mol_disconnected = sdm.disconnect_metals(mol) print(f"After metal disconnection: {Chem.MolToSmiles(mol_disconnected, isomericSmiles=True)}") # Example with salt removal salt_smi = "CC(N)C(=O)[O-].[Na+]" clean_smi = PyPretreatMol.StandardSmi(salt_smi) print(f"\nSalt compound: {salt_smi}") print(f"After standardization: {clean_smi}") ``` -------------------------------- ### Build and Predict Random Forest Model Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/build/lib/PyBioMed/doc/application.md Builds a Random Forest Regressor model for aqueous solubility prediction and performs cross-validation and testing. Requires scikit-learn and numpy. Ensure data is preprocessed. ```python solubility_set_des = np.array(solubility_set_des) logS = np.array(logS) #============================================================================== # building the model and predict #============================================================================== train_set_des, test_set_des, train_logS, test_logS = train_test_split(solubility_set_des, logS, test_size = 0.33, random_state = 42) kf = cross_validation.KFold(train_set_des.shape[0], n_folds=10, random_state=0) clf = RandomForestRegressor(n_estimators=500, max_features='auto', n_jobs = -1) CV_pred_logS = [] VALIDATION_index = [] for train_index, validation_index in kf: VALIDATION_index = VALIDATION_index + list(validation_index) clf.fit(train_set_des[train_index ,:],train_logS[train_index]) pred_logS = clf.predict(train_set_des[validation_index,:]) CV_pred_logS = CV_pred_logS + list(pred_logS) CV_true_logS = train_logS[VALIDATION_index] r2_CV = metrics.r2_score(CV_true_logS, CV_pred_logS) clf.fit(train_set_des,train_logS) pred_logS_test = clf.predict(test_set_des) r2_test = metrics.r2_score(test_logS, pred_logS_test) ``` -------------------------------- ### Predict hERG Blockade with Ensemble Model (Multiple SMILES) Source: https://github.com/abdulk084/cardiotox/blob/master/README.md Loads the ensemble model and predicts hERG channel blockade for a list of molecules. Pass a list of SMILES strings to the predict method. ```python import cardiotox smiles = [ "CC(=O)SC1CC2=CC(=O)CCC2(C)C2CCC3C(CCC34CCC(=O)O4)C12", "CCCCCCCCCC[N+](CC)(CC)CC" ] model = cardiotox.load_ensemble() model.predict(smiles) ``` -------------------------------- ### Predict Toxicity with CardioTox Models Source: https://context7.com/abdulk084/cardiotox/llms.txt Demonstrates basic prediction workflows for different model types available in the CardioTox library. ```python # Descriptor-based model (uses Mordred descriptors) desc_model = DescModel() desc_prediction = desc_model.predict(smile) print(f"Descriptor model: {desc_prediction[0][0]:.3f}") # Fingerprint model (ECFP2 + PubChem fingerprints) fp_model = FingerprintModel() fp_prediction = fp_model.predict(smile) print(f"Fingerprint model: {fp_prediction[0][0]:.3f}") # SMILES Vector model (character-level CNN) sv_model = SVModel() sv_prediction = sv_model.predict(smile) print(f"SMILES Vector model: {sv_prediction[0][0]:.3f}") # Fingerprint Vector model (Morgan fingerprint embedding) fv_model = FVModel() fv_prediction = fv_model.predict(smile) print(f"Fingerprint Vector model: {fv_prediction[0][0]:.3f}") ``` -------------------------------- ### Check Parameters and Calculate PseDNC Descriptor Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/build/lib/PyBioMed/doc/User_guide.md Checks the parameters for PseDNC calculation and then computes the Pseudo Nucleotide Composition (PseDNC) descriptor for a given DNA sequence. Requires importing PyDNApsenac and GetPseDNC. ```python >>> from PyBioMed.PyDNA import PyDNApsenac >>> from PyBioMed.PyDNA.PyDNApsenac import GetPseDNC >>> dnaseq = 'GACTGAACTGCACTTTGGTTTCATATTATTTGCTC' >>> PyDNApsenac.CheckPsenac(lamada = 2, w = 0.05, k = 2) >>> psednc = GetPseDNC('ACCCCA',lamada=2, w=0.05) >>> print(psednc) {'PseDNC_18': 0.0521, 'PseDNC_16': 0.0, 'PseDNC_17': 0.0391, 'PseDNC_14': 0.0, 'PseDNC_15': 0.0, 'PseDNC_12': 0.0, 'PseDNC_13': 0.0, 'PseDNC_10': 0.0, 'PseDNC_11': 0.0, 'PseDNC_4': 0.0, 'PseDNC_5': 0.182, 'PseDNC_6': 0.545, 'PseDNC_7': 0.0, 'PseDNC_1': 0.0, 'PseDNC_2': 0.182, 'PseDNC_3': 0.0, 'PseDNC_8': 0.0, 'PseDNC_9': 0.0} ``` -------------------------------- ### Activate Conda Environment Source: https://github.com/abdulk084/cardiotox/blob/master/README.md Activates the 'cardiotox' conda environment. This must be done before running any project scripts. ```bash conda activate cardiotox ``` -------------------------------- ### Read DNA sequence from FASTA file Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/User_guide.md Reads a DNA sequence from a local FASTA file. Ensure the file path is correctly specified. ```pycon >>> from PyBioMed.PyGetMol.GetDNA import ReadFasta >>> f = open('./PyBioMed/test/test_data/example.fasta') #You should change the path to your own real path >>> dna_seq = ReadFasta(f) >>> print dna ['GACTGAACTGCACTTTGGTTTCATATTATTTGCTC'] ``` -------------------------------- ### Retrieve protein sequences from databases Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/User_guide.md Fetch protein sequences using PDB or UniProt identifiers via the GetProtein module. ```python >>> from PyBioMed.PyGetMol import GetProtein >>> GetProtein.GetPDB(['1atp']) >>> seq = GetProtein.GetSeqFromPDB('1atp.pdb') >>> print seq GNAAAAKKGSEQESVKEFLAKAKEDFLKKWETPSQNTAQLDQFDRIKTLGTGSFGRVMLVKHKESGNHYAMKILDKQKVVKLKQ IEHTLNEKRILQAVNFPFLVKLEFSFKDNSNLYMVMEYVAGGEMFSHLRRIGRFSEPHARFYAAQIVLTFEYLHSLDLIYRDLK PENLLIDQQGYIQVTDFGFAKRVKGRTWXLCGTPEYLAPEIILSKGYNKAVDWWALGVLIYEMAAGYPPFFADQPIQIYEKIVS GKVRFPSHFSSDLKDLLRNLLQVDLTKRFGNLKNGVNDIKNHKWFATTDWIAIYQRKVEAPFIPKFKGPGDTSNFDDYEEEEIR VXINEKCGKEFTEFTTYADFIASGRTGRRNAIHD >>> seq = GetProtein.GetProteinSequence('O00560') >>> print seq MSLYPSLEDLKVDKVIQAQTAFSANPANPAILSEASAPIPHDGNLYPRLYPELSQYMGLSLNEEEIRANVAVVSGAPLQGQLVA RPSSINYMVAPVTGNDVGIRRAEIKQGIREVILCKDQDGKIGLRLKSIDNGIFVQLVQANSPASLVGLRFGDQVLQINGENCAG WSSDKAHKVLKQAFGEKITMTIRDRPFERTITMHKDSTGHVGFIFKNGKITSIVKDSSAARNGLLTEHNICEINGQNVIGLKDS QIADILSTSGTVVTITIMPAFIFEHIIKRMAPSIMKSLMDHTIPEV ``` -------------------------------- ### Retrieve molecular structures from databases Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/User_guide.md Use the Getmol module to fetch SMILES strings for molecules using various database identifiers. ```python >>> from PyBioMed.PyGetMol import Getmol >>> DrugBankID = 'DB01014' >>> smi = Getmol.GetMolFromDrugbank(DrugBankID) >>> print smi N[C@@H](CO)C(=O)O >>> smi=Getmol.GetMolFromCAS(casid="50-12-4") >>> print smi CCC1(c2ccccc2)C(=O)N(C)C(=N1)O >>> smi=Getmol.GetMolFromNCBI(cid="2244") >>> print smi CC(=O)Oc1ccccc1C(=O)O >>> smi=Getmol.GetMolFromKegg(kid="D02176") >>> print smi C[N+](C)(C)C[C@H](O)CC(=O)[O-] ``` -------------------------------- ### Calculate Connectivity Descriptors Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/User_guide.md Use the GetConnectivity function from the connectivity module to calculate connectivity descriptors. The result is returned as a dictionary. ```python from PyBioMed.PyMolecule import connectivity from rdkit import Chem smi = 'CCC1(c2ccccc2)C(=O)N(C)C(=N1)O' mol = Chem.MolFromSmiles(smi) molecular_descriptor = connectivity.GetConnectivity(mol) print molecular_descriptor ``` -------------------------------- ### Calculate Chemical-Chemical Interaction Descriptors Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/User_guide.md Demonstrates calculating interaction features between two molecular descriptor sets using three different mathematical methods. ```python >>> from PyBioMed.PyInteraction import PyInteraction >>> from PyBioMed.PyMolecule import moe >>> from rdkit import Chem >>> smis = ['CCCC','CCCCC','CCCCCC','CC(N)C(=O)O','CC(N)C(=O)[O-].[Na+]'] >>> m = Chem.MolFromSmiles(smis[3]) >>> mol_des = moe.GetMOE(m) >>> mol_mol_interaction1 = PyInteraction.CalculateInteraction1(mol_des,mol_des) >>> print mol_mol_interaction1 {'slogPVSA6ex': 0.0, 'PEOEVSA10ex': 0.0,......, 'EstateVSA9ex': 4.795, 'slogPVSA2': 4.795, 'slogPVSA3': 0.0, 'slogPVSA0': 5.734, 'slogPVSA1': 17.118, 'slogPVSA6': 0.0, 'slogPVSA7': 0.0, 'slogPVSA4': 6.924, 'slogPVSA5': 0.0, 'slogPVSA8': 0.0, 'slogPVSA9': 0.0} >>> print len(mol_mol_interaction1) 120 >>> mol_mol_interaction2 = PyInteraction.CalculateInteraction2(mol_des,mol_des) >>> print len(mol_mol_interaction2) 3600 >>> mol_mol_interaction3 = PyInteraction.CalculateInteraction3(mol_des,mol_des) {'EstateVSA9*EstateVSA9': 22.992, 'EstateVSA9+EstateVSA9': 9.59, 'PEOEVSA1+PEOEVSA1': 9.59, 'VSAEstate10*VSAEstate10': 0.0, 'PEOEVSA3*PEOEVSA3': 0.0, 'PEOEVSA11*PEOEVSA11': 0.0, 'PEOEVSA4*PEOEVSA4': 0.0, 'VSAEstate2+VSAEstate2': 0.0, 'MRVSA0+MRVSA0': 19.802, 'MRVSA6+MRVSA6': 0.0......} >>> print len(mol_mol_interaction3) 120 ``` -------------------------------- ### Fetch Protein Sequence from Uniprot and Calculate CTD Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/User_guide.md Retrieve a protein sequence from Uniprot using its ID and then calculate its Composition, Transition, and Distribution (CTD) features. Requires importing GetProteinSequence from PyBioMed.PyProtein.GetUniprot. ```python from PyBioMed import Pyprotein from PyBioMed.PyProtein.GetProteinFromUniprot import GetProteinSequence uniprotID = 'P48039' protein_sequence = GetProteinSequence(uniprotID) print protein_sequence protein_class = Pyprotein.PyProtein(protein_sequence) CTD = protein_class.GetCTD() print len(CTD) ``` -------------------------------- ### Print Classification Metrics Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/build/lib/PyBioMed/doc/application.md Prints various classification metrics including sensitivity, specificity, accuracy, AUC, Matthews Correlation Coefficient, and F1 score. Ensure these variables are defined before execution. ```python print 'sensitivity:',TPR, 'specificity:', SPE, 'accuracy:', ACC, 'AUC:', AUC_score, 'MACCS:', matthews_corrcoef, 'F1:', f1_score ``` -------------------------------- ### Performance Metrics Output Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/build/lib/PyBioMed/doc/application.md Prints the calculated performance metrics for the cross-validation, including sensitivity, specificity, accuracy, AUC, MCC, and F1 score. ```python print 'sensitivity:',TPR, 'specificity:', SPE, 'accuracy:', ACC, 'AUC:', AUC_score, 'MCC:', matthews_corrcoef, 'F1:', f1_score ``` -------------------------------- ### Calculate All Protein Descriptors Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/build/lib/PyBioMed/doc/User_guide.md Calculates all available protein descriptors, excluding tri-peptide composition descriptors, using the PyProtein class. The output is the total count of descriptors calculated. ```python >>> from PyBioMed import Pyprotein >>> protein="ADGCGVGEGTGQGPMCNCMCMKWVYADEDAADLESDSFADEDASLESDSFPWSNQRVFCSFADEDAS" >>> protein_class = Pyprotein.PyProtein(protein) >>> print len(protein_class.GetALL()) 10049 ``` -------------------------------- ### Calculate All Protein Descriptors using PyProtein Object Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/User_guide.md Calculate all available protein descriptors, excluding tri-peptide composition, using the PyProtein class. This provides a comprehensive set of features for a protein sequence. ```python from PyBioMed import Pyprotein protein="ADGCGVGEGTGQGPMCNCMCMKWVYADEDAADLESDSFADEDASLESDSFPWSNQRVFCSFADEDAS" protein_class = Pyprotein.PyProtein(protein) print len(protein_class.GetALL()) ``` -------------------------------- ### Fetch PDB Sequences and Calculate CTD Descriptors Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/PyBioMed/doc/User_guide.md Fetches protein sequences from PDB IDs using PyBioMed.PyGetMol.GetProtein and calculates CTD descriptors using PyBioMed.PyProtein.CTD. Requires RDKit (Chem). ```python from PyBioMed.PyGetMol import GetProtein GetProtein.GetPDB(['1atp','1efz','1f88']) seq = GetProtein.GetSeqFromPDB('1atp.pdb') print seq from PyBioMed.PyProtein import CTD protein_descriptor = CTD.CalculateC(protein) print protein_descriptor ``` -------------------------------- ### Read DNA Sequence from FASTA File Source: https://github.com/abdulk084/cardiotox/blob/master/PyBioMed/build/lib/PyBioMed/doc/User_guide.md Reads DNA sequences from a FASTA file. Ensure the file path is correct. ```python from PyBioMed.PyGetMol.GetDNA import ReadFasta f = open('./PyBioMed/test/test_data/example.fasta') #You should change the path to your own real path dna_seq = ReadFasta(f) print dna ``` -------------------------------- ### Calculate Molecular Interaction Descriptors with PyBioMed Source: https://context7.com/abdulk084/cardiotox/llms.txt Demonstrates calculating molecular descriptors for two compounds using the MOE method and then computing interaction features using three different methods: concatenation, outer product, and element-wise operations. Requires RDKit for molecule parsing. ```python from PyBioMed.PyInteraction import PyInteraction from PyBioMed.PyMolecule import moe from PyBioMed.PyProtein import CTD from PyBioMed.PyDNA.PyDNAac import GetTCC from rdkit import Chem # Calculate molecular descriptors for two compounds mol1 = Chem.MolFromSmiles("CC(N)C(=O)O") # Alanine mol2 = Chem.MolFromSmiles("CC(C)CC(N)C(=O)O") # Leucine mol1_des = moe.GetMOE(mol1) mol2_des = moe.GetMOE(mol2) # Method 1: Concatenation (F_ab = [F_a, F_b]) interaction1 = PyInteraction.CalculateInteraction1(mol1_des, mol2_des) print(f"Concatenation features: {len(interaction1)}") # Method 2: Outer product (F = F_a(i) * F_b(j)) interaction2 = PyInteraction.CalculateInteraction2(mol1_des, mol2_des) print(f"Outer product features: {len(interaction2)}") # Method 3: Element-wise operations [F_a + F_b, F_a * F_b] # (Only for same-type descriptors) interaction3 = PyInteraction.CalculateInteraction3(mol1_des, mol2_des) print(f"Element-wise features: {len(interaction3)}") ``` -------------------------------- ### Calculate SC-PseDNC Descriptors Source: https://context7.com/abdulk084/cardiotox/llms.txt This snippet shows how to obtain SC-PseDNC (sequence correlation pseudo-dinucleotide composition) descriptors. Ensure the 'dna' object is properly initialized. ```python scpsednc = dna.GetSCPseDNC() print(f"SC-PseDNC descriptors: {len(scpsednc)} features") ```