### Clone and Setup Environment Source: https://github.com/ai-sandbox/gnomix/blob/main/README.md Initializes the project directory and creates a dedicated Conda environment for Gnomix. ```bash git clone https://github.com/AI-sandbox/gnomix cd gnomix conda create -n gnomix python=3.14 conda activate gnomix ``` -------------------------------- ### Install Dependencies Source: https://github.com/ai-sandbox/gnomix/blob/main/README.md Installs the required Python packages listed in requirements.txt using pip. ```bash pip install -r requirements.txt ``` -------------------------------- ### Define configuration arguments Source: https://github.com/ai-sandbox/gnomix/blob/main/demo.ipynb Set file paths and parameters for the Gnomix pipeline. ```python # Arguments data_path = "./demo/data/" query_file = data_path + "ALL.chr22.phase3_shapeit2_mvncall_integrated_v5a.20130502.genotypes.vcf.gz" genetic_map_file = data_path + "allchrs.b37.gmap" reference_file = data_path + "reference_1000g.vcf" sample_map_file = data_path + "1000g.smap" chm = "22" phase = "False" output_basename = "./demo/output" ``` -------------------------------- ### Run Gnomix Training Source: https://github.com/ai-sandbox/gnomix/blob/main/README.md Execute the Gnomix training process using a specific configuration file. ```bash $ python3 gnomix.py ``` -------------------------------- ### Run Gnomix Inference Demo Source: https://github.com/ai-sandbox/gnomix/blob/main/demo-pretrained.md Execute a sample inference task using the provided small query file and downloaded model. ```bash python3 gnomix.py demo/data/small_query_chr22.vcf.gz demo_output 22 True pretrained_gnomix_models/chr22/model_chm_22.pkl ``` -------------------------------- ### Execute Gnomix Training Source: https://github.com/ai-sandbox/gnomix/blob/main/README.md Command to initiate model training from scratch using the required input files and parameters. ```bash $ python3 gnomix.py ``` -------------------------------- ### Download Pre-Trained Models Source: https://github.com/ai-sandbox/gnomix/blob/main/demo-pretrained.md Use the provided shell script to download pre-trained models and associated .bim files for the human genome. ```bash sh download_pretrained_models.sh ``` -------------------------------- ### Load sample map Source: https://github.com/ai-sandbox/gnomix/blob/main/demo.ipynb Reads the sample mapping file into a DataFrame. ```python sample_map = pd.read_csv(sample_map_file, sep="\t") ``` -------------------------------- ### Subset reference data using bcftools Source: https://github.com/ai-sandbox/gnomix/blob/main/demo.ipynb Create a reference file by subsetting the query VCF based on a provided sample map. ```python sample_map = pd.read_csv(sample_map_file, sep="\t") samples = list(sample_map["#Sample"]) sample_file = data_path + "samples_1000g.tsv" np.savetxt(sample_file, samples, delimiter="\t", fmt="%s") subset_cmd = "bcftools view" + " -S " + sample_file + " -o " + reference_file + " " + query_file print("Running in command line: \n\t", subset_cmd) os.system(subset_cmd) ``` -------------------------------- ### Import Custom Gnomix Models Source: https://github.com/ai-sandbox/gnomix/blob/main/README.md Import base and smoother models to customize the Gnomix pipeline. ```python from src.Base.models import LogisticRegressionBase ``` ```python from src.Smooth.models import XGB_Smoother ``` -------------------------------- ### Configure inference mode Source: https://github.com/ai-sandbox/gnomix/blob/main/gnomix-best-practices.md Set the inference mode to fast for optimal performance. ```yaml inference: fast ``` -------------------------------- ### Initialize Gnomix with Custom Models Source: https://github.com/ai-sandbox/gnomix/blob/main/README.md Configure the Gnomix object within the train_model() function using custom base and smoother components. ```python model = Gnomix( ..., base = LogisticRegressionBase, smooth = XGB_Smoother, ... ) ``` -------------------------------- ### Train the Gnomix model Source: https://github.com/ai-sandbox/gnomix/blob/main/demo.ipynb Execute the training command via the Gnomix CLI and log the output. ```python train_cmd = " ".join(["python3 gnomix.py", query_file, genetic_map_file, output_basename, chm, phase, reference_file, sample_map_file]) + \ " > ./demo/training_log.txt" print("Running in command line: \n\t", train_cmd) os.system(train_cmd) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/ai-sandbox/gnomix/blob/main/demo.ipynb Initial imports required for data handling and system operations. ```python import numpy as np import os import pandas as pd ``` -------------------------------- ### Import analysis libraries Source: https://github.com/ai-sandbox/gnomix/blob/main/demo.ipynb Imports required modules for statistical analysis, visualization, and post-processing, and enables autoreload for development. ```python from scipy import stats from sklearn.metrics import confusion_matrix from src.postprocess import get_samples_from_msp_df from src.visualization import plot_cm, plot_chm %load_ext autoreload %autoreload 2 ``` -------------------------------- ### Execute Gnomix with a Pre-Trained Model Source: https://github.com/ai-sandbox/gnomix/blob/main/demo-pretrained.md Run the Gnomix prediction script by providing the query file, output directory, chromosome, phasing flag, and model path. ```bash $ python3 gnomix.py ``` -------------------------------- ### Configure r_admixed hyperparameter Source: https://github.com/ai-sandbox/gnomix/blob/main/gnomix-best-practices.md Increase r_admixed to trade longer training time for improved performance. ```yaml r_admixed: 2 ``` ```yaml r_admixed: 3 ``` -------------------------------- ### Configure context_ratio hyperparameter Source: https://github.com/ai-sandbox/gnomix/blob/main/gnomix-best-practices.md Adjust context_ratio to potentially improve results, with 1 being recommended for array data. ```yaml context_ratio: 0.5 ``` ```yaml context_ratio: 0 ``` ```yaml context_ratio: 1 ``` -------------------------------- ### Configure window_size_cM hyperparameter Source: https://github.com/ai-sandbox/gnomix/blob/main/gnomix-best-practices.md Modify window_size_cM to balance segment resolution and prediction smoothness. ```yaml window_size_cM: 0.2 ``` ```yaml window_size_cM: 0.1 ``` ```yaml window_size_cM: 0.4 ``` -------------------------------- ### Read MSP output into DataFrame Source: https://github.com/ai-sandbox/gnomix/blob/main/demo.ipynb Loads the query results from an MSP file into a pandas DataFrame, skipping the first header row. ```python # read the output file into a dataframe output_file = output_basename+"/query_results.msp" msp_df = pd.read_csv(output_file, sep="\t", skiprows=[0]) msp_df ``` -------------------------------- ### Visualize confusion matrix Source: https://github.com/ai-sandbox/gnomix/blob/main/demo.ipynb Generates and saves a normalized confusion matrix plot based on the population predictions. ```python # creating and visualizing the confusion matrix labs = np.unique(pred_df[['Population', 'Prediction']]) cm = confusion_matrix(pred_df.Population, pred_df.Prediction, labels=labs) cm_plot = plot_cm(cm, normalize=True, labels=labs) cm_plot.figure.savefig('./demo/imgs/single_ancestry_confusion_matrix.png') ``` -------------------------------- ### Cite Gnofix in BibTeX Source: https://github.com/ai-sandbox/gnomix/blob/main/src/Gnofix/README.md Use this BibTeX entry to cite the Gnofix and G-Nomix research paper in academic publications. ```bibtex @article {Hilmarsson2021.09.19.460980, author = {Hilmarsson, Helgi and Kumar, Arvind S and Rastogi, Richa and Bustamante, Carlos D and Mas Montserrat, Daniel and Ioannidis, Alexander G}, title = {High Resolution Ancestry Deconvolution for Next Generation Genomic Data}, elocation-id = {2021.09.19.460980}, year = {2021}, doi = {10.1101/2021.09.19.460980}, publisher = {Cold Spring Harbor Laboratory}, abstract = {As genome-wide association studies and genetic risk prediction models are extended to globally diverse and admixed cohorts, ancestry deconvolution has become an increasingly important tool. Also known as local ancestry inference (LAI), this technique identifies the ancestry of each region of an individual{\textquoteright}s genome, thus permitting downstream analyses to account for genetic effects that vary between ancestries. Since existing LAI methods were developed before the rise of massive, whole genome biobanks, they are computationally burdened by these large next generation datasets. Current LAI algorithms also fail to harness the potential of whole genome sequences, falling well short of the accuracy that such high variant densities can enable. Here we introduce G-Nomix, a set of algorithms that address each of these points, achieving higher accuracy and swifter computational performance than any existing LAI method, while also enabling portable models that are particularly useful when training data are not shareable due to privacy or other restrictions. We demonstrate G-Nomix (and its swift phase correction counterpart Gnofix) on worldwide whole-genome data from both humans and canids and utilize its high resolution accuracy to identify the location of ancient New World haplotypes in the Xoloitzcuintle, dating back over 100 generations. Code is available at https://github.com/AI-sandbox/gnomixCompeting Interest StatementCDB is the founder and CEO of Galatea Bio Inc and on the boards of Genomics PLC and Etalon.}, URL = {https://www.biorxiv.org/content/early/2021/09/21/2021.09.19.460980}, eprint = {https://www.biorxiv.org/content/early/2021/09/21/2021.09.19.460980.full.pdf}, journal = {bioRxiv} } ``` -------------------------------- ### Configure gens hyperparameter Source: https://github.com/ai-sandbox/gnomix/blob/main/gnomix-best-practices.md Adjust the gens list to control prediction smoothness or segment detection sensitivity. ```yaml gens: [0, 2, 4, 6, 8, 12, 16, 24] ``` ```yaml gens: [0, 2, 4, 6] ``` ```yaml gens: [0, 2, 4, 6, 8, 12, 16, 24, 48, 64, 128] ``` -------------------------------- ### Visualize chromosome predictions with Tagore Source: https://github.com/ai-sandbox/gnomix/blob/main/demo.ipynb Uses the plot_chm function to generate a visualization for a specific sample and chromosome, then displays the resulting image file. ```python from IPython.display import Image sample_id = "HG00096" # looking at just one random sample img_name = "./demo/imgs/chm_img" plot_chm(sample_id, msp_df, img_name=img_name) Image(filename=img_name+".png") ``` -------------------------------- ### Merge true labels with predictions Source: https://github.com/ai-sandbox/gnomix/blob/main/demo.ipynb Reads ancestry labels from a metadata file and merges them into the existing prediction dataframe. ```python # adding the true labels sample_map_file = "./demo/data/1000g.meta" # find the true labels in the sample map file sample_map_df = pd.read_csv(sample_map_file, sep="\t") true_labels_df = sample_map_df[["Sample", "Superpopulation code"]] true_labels_df.columns = ["Sample", "Population"] pred_df = pred_df.merge(true_labels_df) pred_df ``` -------------------------------- ### Predict single ancestry Source: https://github.com/ai-sandbox/gnomix/blob/main/demo.ipynb Calculates individual ancestry predictions by taking the mode of local predictions across intervals and maps them to population labels. ```python # reading the sample-ids query_samples = get_samples_from_msp_df(msp_df) # reading predictions for each of the intervals pred_labels = (np.array(msp_df)[:,6:].T).astype(int) # reducing it to only 1 of maternal/paternal prediction single_ind_idx = np.arange(0,len(query_samples)*2,2) pred_labels_single_ind = pred_labels[single_ind_idx,:] # predicting single ancestry by taking mode of local predictions for each individual y_pred = stats.mode(pred_labels_single_ind,axis=1)[0].squeeze() # get model population order from first line of file and convert from numeric predictions with open(output_file, "r") as f: pop = np.array([p.split("=")[0] for p in f.readline().split()[2:]]) pred_pop = [pop[pop_ind] for pop_ind in y_pred] # put it together in dataframe pred_df = pd.DataFrame({"Sample": query_samples, "Prediction": pred_pop}) pred_df ``` -------------------------------- ### Calculate prediction accuracy Source: https://github.com/ai-sandbox/gnomix/blob/main/demo.ipynb Computes the mean accuracy by comparing the predicted population labels against the true labels. ```python # Getting the prediction accuracy acc = np.mean(pred_df.Population == pred_df.Prediction) print("Accuracy for single ancestry: ", acc*100, "%", sep="") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.