From a204beeeea026d637ea5cd4ae4e800b4d07c9d7e Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Mon, 30 Sep 2024 14:16:25 -0400 Subject: [PATCH 01/40] Update train.md Added missing argument in example command. --- docs/readme/train.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/readme/train.md b/docs/readme/train.md index d0f759e..cf4f6ef 100644 --- a/docs/readme/train.md +++ b/docs/readme/train.md @@ -42,7 +42,7 @@ For every TF model, one cell type and 2 chromosomes are held out for independent ## Example ```bash -maxatac train --arch DCNN_V2 --sequence hg38.2bit --meta_file CTCF_meta.tsv --output ./CTCF_DCNN --prefix CTCF_DCNN --shuffle_cell_type --rev_comp +maxatac train --genome hg38 --arch DCNN_V2 --sequence hg38.2bit --meta_file CTCF_meta.tsv --output ./CTCF_DCNN --prefix CTCF_DCNN --shuffle_cell_type --rev_comp ``` ## Required Arguments From adc9f8ef54a5b0bd217f3d68edad8e6e596193f6 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Mon, 30 Sep 2024 14:17:06 -0400 Subject: [PATCH 02/40] Update predict.md Corrected error in example command. --- docs/readme/predict.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/readme/predict.md b/docs/readme/predict.md index 2572889..a4032fb 100644 --- a/docs/readme/predict.md +++ b/docs/readme/predict.md @@ -5,7 +5,7 @@ The `predict` function will use a maxATAC model to predict TF binding in a new c ## Example ```bash -maxatac predict --models CTCF.h5 --signal GM12878.bigwig +maxatac predict --model CTCF.h5 --signal GM12878.bigwig ``` or From 362dd86dcd431e43c0a40e8dee30a1df7a41a43c Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Mon, 30 Sep 2024 15:32:09 -0400 Subject: [PATCH 03/40] Update train.md Added message to include only unzipped files in the meta file. --- docs/readme/train.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/readme/train.md b/docs/readme/train.md index d0f759e..00587fe 100644 --- a/docs/readme/train.md +++ b/docs/readme/train.md @@ -17,6 +17,7 @@ The `train` function will train a maxATAC model using the supplied ATAC-seq and ## Approach The meta file described above is used to locate all the input files for all the training data. +**Note: all files specified in the meta file should be in unzipped format. General Steps: From 317c4b7cf15b5590e2afe1bcf5cf9bc71a50afc1 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 1 Oct 2024 16:08:12 -0400 Subject: [PATCH 04/40] Update predict.md Added additional options available for certain arguments, based on parser.py. --- docs/readme/predict.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/readme/predict.md b/docs/readme/predict.md index a4032fb..d1431d3 100644 --- a/docs/readme/predict.md +++ b/docs/readme/predict.md @@ -18,15 +18,15 @@ maxatac predict --tf CTCF --signal GM12878.bigwig ### `-tf, --tf_name` or `-m, --model` -The user must provide either the TF name that they want to make predictions for or the h5 model file they desire. If the user provides a TF name, the best model will be used and the correct threshold file will be provided for peak calling. +The user must provide either the TF name that they want to make predictions for OR the h5 model file they desire (note that these are mutually exclusive). If the user provides a TF name, the best model will be used and the correct threshold file will be provided for peak calling. ### `-s, --signal, -i` -The ATAC-seq signal bigwig track that will be used to make predictions of TF binding. +The ATAC-seq signal bigwig track that will be used to make TF binding predictions. ### `-n, --name, --prefix` -Output filename prefix to use. Default `maxatac_predict`. +Output filename prefix (without extension) to use. Default `maxatac_predict`. ## Optional Arguments @@ -34,15 +34,15 @@ Output filename prefix to use. Default `maxatac_predict`. This argument specifies the path to the 2bit DNA sequence for the genome of interest. maxATAC models are trained with hg38 so you will need the correct `.2bit` file. -### `"-cutoff_type", "--cutoff_type"` +### `"-ct", "-cutoff_type", "--cutoff_type"` The cutoff type (i.e. `Precision`, `Recall`, `F1`, `log2FC`). (F1 = F1-score, and log2FC = Log2( Precision : Random Precision)). Default: F1. -### `"-cutoff_value", "--cutoff_value"` +### `"-cv", "-cutoff_value", "--cutoff_value"` -The cutoff value for the cutoff type provided. Note precision, recall, and F1-scores range 0-1, while better-than-random log2FC scores range from 0 to infinity. Example: .7 +The cutoff value for the cutoff type provided. Note precision, recall, and F1-scores range 0-1, while better-than-random log2FC scores range from 0 to infinity. Example: 0.7. -### `-cutoff_file, --cutoff_file` +### `"-cf", -cutoff_file, --cutoff_file` The cutoff file provided in /data/models that corresponds to the average validation performance metrics for the TF model. @@ -52,11 +52,11 @@ Output directory path. Default: `./prediction_results` ### `-bl, --blacklist` -The path to a bigwig file that has regions to exclude. Default: maxATAC-defined blacklist. +The path to a bigWig file that has regions to exclude. Default: maxATAC-defined blacklist. ### `--bed, --peaks, --regions, , --roi, -roi` -The path to a bed file that contains the genomic regions to focus TF predictions on. These peaks will be used to refine the prediction windows. +The path to a BED file containing genomic regions to focus TF predictions on. These peaks will be used to refine the prediction windows. Default: whole-chromosome predictions. ### `--batch_size` @@ -72,7 +72,7 @@ The path to the chromosome sizes file. This is used to generate the bigwig signa ### `-c, -chroms, --chromosomes` -The chromosomes to make predictions on. Our models do not currently considered chromosomes X or Y. This means that most of the files will not contain this information. You should not predict in chrX or chrY unless you know your bigwig contains these chromosomes. Default: Autosomal chromosomes 1-22. +The chromosomes to make predictions on. Our models do not currently consider chromosomes X or Y. This means that most of the files will not contain this information. You should not predict in chrX or chrY unless you know your bigWig contains these chromosomes. Default: autosomal chromosomes 1-22. ### `--loglevel` @@ -84,4 +84,4 @@ The windows to use for prediction. These windows must be 1,024 bp wide and have ### `-skip_call_peaks, --skip_call_peaks` -This will skip calling peaks at the end of predictions. +This will skip calling peaks on prediction tracks. From 6b13d1098c0c7886309dc2dd7c790eba804ae3e9 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 1 Oct 2024 16:32:29 -0400 Subject: [PATCH 05/40] Update train.md Added multiple options for maxatac train() not previously described in this document. --- docs/readme/train.md | 61 +++++++++++++++++++++++++++----------------- 1 file changed, 37 insertions(+), 24 deletions(-) diff --git a/docs/readme/train.md b/docs/readme/train.md index 54e8a3f..de36c1c 100644 --- a/docs/readme/train.md +++ b/docs/readme/train.md @@ -47,18 +47,18 @@ maxatac train --genome hg38 --arch DCNN_V2 --sequence hg38.2bit --meta_file CTCF ``` ## Required Arguments -### `--genome` - -Specify which genome build this task is specified for (i.e. hg38). ### `--sequence` This argument specifies the path to the 2bit DNA sequence for the genome of interest ### `--meta_file` -This argument specifies the path to the meta file that describes the training data available. This meta file described above. +This argument specifies the path to the meta file that describes the training data available. This meta file is described above. ## Optional Arguments +### `--genome` + +Specify which genome build this task is specified for (i.e. hg38). ### `--prefix` @@ -66,80 +66,79 @@ This argument is reserved for the prefix used to build the output filename. This ### `--train_roi` -This argument is used to input the bed file that you want to use to define the training regions of interest. If you set this option you will randomly select regions from this file for training instead of using the meta data to build the training data pool. +This argument is used to input the BED file that you want to use to define the training regions of interest. If you set this option, you will randomly select regions from this file for training instead of using the meta data to build the training data pool. ### `--validate_roi` -This argument is used to input the bed file that you want to use to define the validation regions of interest. If you set this option you will randomly select regions from this file for validation instead of using the meta data to build the validation data pool. +This argument is used to input the BED file that you want to use to define the validation regions of interest. If you set this option, you will randomly select regions from this file for validation instead of using the meta data to build the validation data pool. ### `--target_scale_factor` The scaling factor for scaling model targets signal. Used only for quantitative models. Default: `1` - ### `--output_activation` The output activation to use for the model. No other options are considered in the publication. Test at your own risk. Default: `sigmoid` ### `--chroms` -The list of chromosomes to limit the study to. These include the training and validation chromosomes. Default: ```["chr2", "chr3", "chr4", "chr5", "chr6", "chr7", "chr9", "chr10", "chr11", "chr12", "chr13", "chr14", "chr15", "chr16", "chr17", "chr18", "chr19", "chr20", "chr21", "chr22", "chrX"]``` +The list of chromosomes to limit the study to. These include the training and validation chromosomes. Default: ```["chr2", "chr3", "chr4", "chr5", "chr6", "chr7", "chr9", "chr10", "chr11", "chr12", "chr13", "chr14", "chr15", "chr16", "chr17", "chr18", "chr19", "chr20", "chr21", "chr22", "chrX"]```. ### `--tchroms` -The list of chromosomes to use for training only. Default: ```["chr3", "chr4", "chr5", "chr6", "chr7", "chr9", "chr10", "chr11", "chr12", "chr13", "chr14", "chr15", "chr16", "chr17", "chr18", "chr20", "chr21", "chr22"]``` +The list of chromosomes to use for training only. Default: ```["chr3", "chr4", "chr5", "chr6", "chr7", "chr9", "chr10", "chr11", "chr12", "chr13", "chr14", "chr15", "chr16", "chr17", "chr18", "chr20", "chr21", "chr22"]```. ### `--vchroms` -The list of chromosomes to use for validation only. Default: ```["chr2", "chr19"]``` +The list of chromosomes to use for validation only. Default: ```["chr2", "chr19"]```. ### `--arch` -The architecture to use for the neural network. Default: `DCNN_V2` +The architecture to use for the neural network. maxATAC-v1.0.6 supported architectures include `DCNN_V2, RES_DCNN_V2, MM_DCNN_V2 and MM_Res_DCNN_V2`. Default: `DCNN_V2`. ### `--rand_ratio` -The proportion of random regions to use per training and validation batch. This corresponds to the number of regions that are randomly selected form the genome as opposed to being created based on the ATAC-seq or ChIP-seq peaks. Default: `0` +The proportion of random regions to use per training and validation batch. This corresponds to the number of regions that are randomly selected form the genome as opposed to being created based on the ATAC-seq or ChIP-seq peaks. Default: `0`. ### `--seed` -The seed to use for the model in case of reproducibility. Default: `random.randint(1, 99999)` +The seed to use for the model in case of reproducibility. Default: `random.randint(1, 99999)`. ### `--weights` -The weights to use to initialize a model. Default: `do not initialize with weights` +The weights to use for initializing a model prior to training. Default: `do not initialize with weights`. ### `--epochs` -The number of epochs to train the model for. Default: `20` +The number of epochs to train the model for. Default: `20`. ### `--batches` -The number of batches to use per stochastic gradient descent step. Default: `100` +The number of batches to use per stochastic gradient descent step. Default: `100`. ### `--batch_size` -The number of examples to use per training batch. Default: `1000` +The number of examples to use per training batch. Default: `1000`. ### `--val_batch_size` -The number of examples to use per validation batch. Default `1000` +The number of examples to use per validation batch. Default `1000`. ### `--output` -The output directory name to save results to. Default: `./training_results` +The output directory name to save results to. Default: `./training_results`. ### `--plot` -Whether to plot the model structure or training history. Default: `True` +Whether to plot the model structure or training history. Default: `True`. ### `--dense` -Used if you want to use a dense layer at the end of the neural network. Default: `False` +Used if you want to use a dense layer at the end of the neural network. Default: `False`. ### `--threads` -Use to change the number of threads used per job. Default: `get available` +Use to change the number of threads used per job. Default: `get available`. ### `--loglevel` @@ -147,9 +146,23 @@ This argument is used to set the logging level. Currently, the only working logg ### `--rev_comp` -If rev_comp_train, then use the reverse complement sequence in addition to the reference sequence. Default: `False` +If rev_comp is `True`, then use the reverse complement sequence in addition to the reference sequence. Default: `False`. ### `--shuffle_cell_type` -If shuffle_cell_type, then shuffle training ROI cell type label. This is related to "pan-cell" training as described in the maxATAC manuscript. Default: `True` +If shuffle_cell_type is `True`, then shuffle training ROI cell type label. This is related to "pan-cell" training as described in the maxATAC manuscript. Default: `True`. + +### `--multiprocessing` + +If set, this option supports parallelization of training. Default: `False`. + +### `--max_queue_size` + +### `--blacklist` + +The path to a BED file that has regions to exclude. + +### `--chrom_sizes` + +The path to the chromosome sizes file. From ab69135be965f6081f2cdf8773f9868e351425c3 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 1 Oct 2024 20:45:01 -0400 Subject: [PATCH 06/40] Update predict.md Fixed wording. Thanks, Faiz! --- docs/readme/predict.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/readme/predict.md b/docs/readme/predict.md index d1431d3..62f91e7 100644 --- a/docs/readme/predict.md +++ b/docs/readme/predict.md @@ -18,7 +18,7 @@ maxatac predict --tf CTCF --signal GM12878.bigwig ### `-tf, --tf_name` or `-m, --model` -The user must provide either the TF name that they want to make predictions for OR the h5 model file they desire (note that these are mutually exclusive). If the user provides a TF name, the best model will be used and the correct threshold file will be provided for peak calling. +The user must provide either the TF name that they want to make predictions for OR the h5 model file they desire. If the user provides a TF name, the best model will be used and the correct threshold file will be provided for peak calling. ### `-s, --signal, -i` From cfc89649e6e58be0a19d86e22f3ef1b73e8d915f Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 1 Oct 2024 20:46:58 -0400 Subject: [PATCH 07/40] Update train.md Removed options no longer supported by maxATAC. Thanks, Faiz! --- docs/readme/train.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/readme/train.md b/docs/readme/train.md index de36c1c..b06263f 100644 --- a/docs/readme/train.md +++ b/docs/readme/train.md @@ -94,7 +94,7 @@ The list of chromosomes to use for validation only. Default: ```["chr2", "chr19" ### `--arch` -The architecture to use for the neural network. maxATAC-v1.0.6 supported architectures include `DCNN_V2, RES_DCNN_V2, MM_DCNN_V2 and MM_Res_DCNN_V2`. Default: `DCNN_V2`. +The architecture to use for the neural network. Default: `DCNN_V2`. ### `--rand_ratio` From e7ba3a9188efde3064c7d0284b0e8f140a5cb54a Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Mon, 7 Oct 2024 22:07:28 -0400 Subject: [PATCH 08/40] Update plot.py Fixed invalid plotting parameter (i.e., style), which will permit plotting of figures generated through maxATAC train(). --- maxatac/utilities/plot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maxatac/utilities/plot.py b/maxatac/utilities/plot.py index 2e83306..28013b4 100644 --- a/maxatac/utilities/plot.py +++ b/maxatac/utilities/plot.py @@ -20,7 +20,7 @@ def export_model_structure(model, file_location, suffix="_model_structure", ext= def export_binary_metrics(history, tf, RR, ARC, file_location, best_epoch, suffix="_model_dice_acc", ext=".png", - style="seaborn-whitegrid", log_base=10, skip_tags="_{epoch}"): + style="seaborn_v0_8-whitegrid", log_base=10, skip_tags="_{epoch}"): plt.style.use(style) fig, ((ax1, ax2)) = plt.subplots(1, 2, sharex=False, sharey=False, figsize=(18, 6), dpi=200) fig.suptitle('Loss and Dice Coefficient with random ratio set at ' + str(RR) + ' for ' + tf + ' using the ' + ARC + ' architecture', fontsize=22) From fdffcb0fb3d675f0eb0ccc73d1229b9efeab72d1 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Fri, 18 Oct 2024 11:51:28 -0400 Subject: [PATCH 09/40] Update benchmark.py Fixed issue regarding plotting of PR curves. Please see the patch opened for parser.py on 10/18/2024 to see additional information. --- maxatac/analyses/benchmark.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/maxatac/analyses/benchmark.py b/maxatac/analyses/benchmark.py index 7dae2cc..f056361 100644 --- a/maxatac/analyses/benchmark.py +++ b/maxatac/analyses/benchmark.py @@ -63,7 +63,7 @@ def run_benchmarking(args): args.agg_function, results_filename, args.round_predictions, - plot=args.skip_plot) + plot=args.plot) # Measure End Time of Training stopTime = timeit.default_timer() @@ -73,4 +73,4 @@ def run_benchmarking(args): mins, secs = divmod(totalTime, 60) hours, mins = divmod(mins, 60) - logging.info("Total Benchmarking time: %d:%d:%d.\n" % (hours, mins, secs)) \ No newline at end of file + logging.info("Total Benchmarking time: %d:%d:%d.\n" % (hours, mins, secs)) From df0adb881eed0ea44be5b5d32d9899de0f7e98ab Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Fri, 18 Oct 2024 11:53:17 -0400 Subject: [PATCH 10/40] Update parser.py Fixed issue regarding plotting of PR curves. --- maxatac/utilities/parser.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/maxatac/utilities/parser.py b/maxatac/utilities/parser.py index 1ce7b01..840e748 100644 --- a/maxatac/utilities/parser.py +++ b/maxatac/utilities/parser.py @@ -757,12 +757,12 @@ def get_parser(): help="The blacklisted regions to exclude in BigWig format" ) - benchmark_parser.add_argument("-skip_plot", "--skip_plot", - dest="skip_plot", + benchmark_parser.add_argument("-plot", "--plot", + dest="plot", action="store_true", default=False, required=False, - help="Skip PR curve plotting" + help="Plot the PR curve." ) ############################################# # Peaks subparser From 85bd03987fe5da858352f0bed82d2d6e01e2b8c4 Mon Sep 17 00:00:00 2001 From: Emily Miraldi Date: Fri, 11 Apr 2025 15:14:37 -0400 Subject: [PATCH 11/40] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ba289b5..a46f56f 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ This version requires python 3.9, `bedtools`, `samtools`, `pigz`, `wget`, `git`, ### Downloading required reference data -In order to run the maxATAC models that were described in the [maxATAC pre-print](https://www.biorxiv.org/content/10.1101/2022.01.28.478235v1), the following files are required to be downloaded from the [maxATAC_data](https://github.com/MiraldiLab/maxATAC_data) repository and installed in the correct directory: +To run the maxATAC models described in [Cazares et al. (2023) PLoS Comp Bio](https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1010863), the following files are required to be downloaded from the [maxATAC_data](https://github.com/MiraldiLab/maxATAC_data) repository and installed in the correct directory: * hg38 reference genome `.2bit` file * hg38 chromosome sizes file From 081f690e8f905608dade127ef7244ba1b145be20 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Wed, 12 Nov 2025 14:13:34 -0500 Subject: [PATCH 12/40] Update threshold.py Fix error that arises due to deprecated pandas functions (pd.append). --- maxatac/analyses/threshold.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/maxatac/analyses/threshold.py b/maxatac/analyses/threshold.py index c60171e..c8ebac8 100644 --- a/maxatac/analyses/threshold.py +++ b/maxatac/analyses/threshold.py @@ -78,7 +78,7 @@ def run_thresholding(args): df['GoldStandard'] = OUT[0][i][1][:bin_count].tolist() gs_bins = OUT[0][i][2] - DF = DF.append(df) + DF = pd.concat([DF, df], ignore_index = True) total_gs_bins.append(gs_bins) @@ -98,7 +98,7 @@ def run_thresholding(args): #Extend last row of entries to threshold of 1 new_row = PR_CURVE_DF.tail(n=1) new_row.Threshold = 1 - PR_CURVE_DF = PR_CURVE_DF.append(new_row) + PR_CURVE_DF = pd.concat([PR_CURVE_DF, new_row], ignore_index = True) # total_gs_bins: Total GS bins across for each CT PR_CURVE_DF["Total_Avg_GoldStandard_Bins"] = int(np.mean(total_gs_bins)) From d57f64ccfa08e78279754a96546ccf2892f07425 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Thu, 13 Nov 2025 21:38:38 -0500 Subject: [PATCH 13/40] Update threshold.py --- maxatac/analyses/threshold.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maxatac/analyses/threshold.py b/maxatac/analyses/threshold.py index c60171e..8f75088 100644 --- a/maxatac/analyses/threshold.py +++ b/maxatac/analyses/threshold.py @@ -140,7 +140,7 @@ def run_thresholding(args): del PR_CURVE_DF['Random_Precision'] - PR_CURVE_DF.columns = ['Monotonic_Precision', 'Monotonic_Recall', 'Threshold', 'Monotonic_log2FC', 'Monotonic_F1'] + PR_CURVE_DF.columns = ['Monotonic_Avg_Precision', 'Monotonic_Avg_Recall', 'Standard_Thresh', 'Monotonic_Avg_log2FC', 'Avg_F1'] PR_CURVE_DF.to_csv(results_filename, sep="\t", header=True, index=False) From 7f496eeaa6d5240756e188f60f1dc6af19e6a25b Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Thu, 19 Mar 2026 17:50:23 -0400 Subject: [PATCH 14/40] Update parser.py Added a new argument ("genome") for the maxATAC average, normalize, predict, benchmark, and prepare functions. This allows users to specify other genomes for e.g., preparation of mm10 ATAC-seq bigWig files and mm10 predictions. Without this argument, the default behavior of the above functions is to use hg38 genome files for all activities, even when genome files from other builds are specified. --- maxatac/utilities/parser.py | 40 ++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/maxatac/utilities/parser.py b/maxatac/utilities/parser.py index 840e748..db963b1 100644 --- a/maxatac/utilities/parser.py +++ b/maxatac/utilities/parser.py @@ -175,6 +175,14 @@ def get_parser(): default=AUTOSOMAL_CHRS, help="Chromosomes for averaging. Default: 1-22" ) + + average_parser.add_argument("--genome", + dest="genome", + type=str, + default="hg38", + required=False, + help="The reference genome build to use." + ) average_parser.add_argument("-o", "--output", "--output_dir", dest="output_dir", @@ -223,6 +231,13 @@ def get_parser(): help="Genome sequence 2bit file." ) + predict_parser.add_argument("--genome", + dest="genome", + type=str, + default="hg38", + required=False, + help="The reference genome build to use.") + predict_parser.add_argument("-i", "-s", "--signal", dest="signal", type=str, @@ -600,9 +615,17 @@ def get_parser(): type=str, nargs="+", default=AUTOSOMAL_CHRS, - help="Chromosomes for normalization. Default: 1-22" + help="Chromosomes for normalization. Default: 1-22 from the hg38 genome" ) + normalize_parser.add_argument("--genome", + dest="genome", + type=str, + default="hg38", + required=False, + help="The reference genome build to use." + ) + normalize_parser.add_argument("-o", "--output", "--output_dir", dest="output_dir", type=str, @@ -722,6 +745,13 @@ def get_parser(): max, mean, min" ) + benchmark_parser.add_argument("--genome", + dest="genome", + type=str, + default="hg38", + required=False, + help="The reference genome build to use.") + benchmark_parser.add_argument("--round_predictions", dest="round_predictions", type=int, @@ -1015,6 +1045,14 @@ def get_parser(): help="The chromosomes to include in the final output." ) + prepare_parser.add_argument("--genome", + dest="genome", + type=str, + default="hg38", + required=False, + help="The reference genome build to use." + ) + prepare_parser.add_argument("-t", "-threads", "--threads", dest="threads", type=int, From 972d918125976205acde198664a848c8bb6aa56d Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 12:30:36 -0400 Subject: [PATCH 15/40] Update normalize.py Issue: the default behavior of maxATAC functions that generate averaged/normalized bigWig files is to generate bigWig files with 10 zoom levels (i.e., pre-computed summary statistics that enable quick zooming of bigWig files). This is extremely memory-intensive, but lower values of this parameter result in delayed loading of files in e.g., IGV. Solution: 1) Added a new argument ("max_zooms") for the maxATAC average and normalize functions in parser.py, which defaults to 5. This will allow users to specify how many zoom levels they wish to retain in the final bigWig file (0-10). I successfully tested the argument for the above functions by specifying --max_zooms 5 in my function call. 2) Also added code to convert values in the array used to generate the bigWig file from FP32 to FP16 values. This code was also successfully tested and resulted in additional memory savings of ~4%. --- maxatac/analyses/normalize.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/maxatac/analyses/normalize.py b/maxatac/analyses/normalize.py index 1aa0809..76b3353 100644 --- a/maxatac/analyses/normalize.py +++ b/maxatac/analyses/normalize.py @@ -30,7 +30,7 @@ def run_normalization(args): 3) Find the genomic min and max values by looping through each chromosome 5) Loop through each chromosome and minmax normalize the values based on the genomic values. - :param args: signal, output_dir, chromosome_sizes, chromosomes, max_percentile, method, blacklist + :param args: signal, output_dir, chromosome_sizes, chromosomes, max_percentile, method, blacklist, max_zooms :return: A minmax normalized bigwig file """ @@ -83,7 +83,7 @@ def run_normalization(args): with pyBigWig.open(args.signal) as input_bw, pyBigWig.open(output_filename, "w") as output_bw: header = [(x, chromosome_length_dictionary[x]) for x in sorted(args.chromosomes)] - output_bw.addHeader(header) + output_bw.addHeader(header, maxZooms = args.max_zooms) # For every chromosome in header, perform normalization for chrom_name, chrom_length in header: @@ -115,7 +115,7 @@ def run_normalization(args): ends=chrom_length, span=1, step=1, - values=normalized_signal.tolist() + values=normalized_signal.astype(np.float16).tolist() ) # Measure time of averaging From 8dd0b0c0721705ada44f79ac2e3dff49462aba85 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 12:52:33 -0400 Subject: [PATCH 16/40] Update prepare.py Issue: the default behavior of maxATAC functions that generate averaged/normalized bigWig files is to generate bigWig files with 10 zoom levels (i.e., pre-computed summary statistics that enable quick zooming of bigWig files). This is extremely memory-intensive, but lower values of this parameter result in delayed loading of files in e.g., IGV. Solution: Added a new argument ("max_zooms") for the maxATAC average and normalize functions in parser.py, which defaults to 5. This will allow users to specify how many zoom levels they wish to retain in the final bigWig file (0-10). I successfully tested the argument for the above functions by specifying --max_zooms 5 in my function call. Also added code to convert values in the array used to generate the bigWig file from FP32 to FP16 values. This code was also successfully tested and resulted in additional memory savings of ~4%. The only change made to this script added an explicit argument for the new max_zooms parameter to be passed into the call to normalize(). --- maxatac/analyses/prepare.py | 1 + 1 file changed, 1 insertion(+) diff --git a/maxatac/analyses/prepare.py b/maxatac/analyses/prepare.py index adb0995..fa0219b 100644 --- a/maxatac/analyses/prepare.py +++ b/maxatac/analyses/prepare.py @@ -154,6 +154,7 @@ def run_prepare(args): args.max = False args.max_percentile = 99 args.clip = False + args.max_zooms = 5 # Minmax normalize signal tracks run_normalization(args) From 19a711b1f74101b262fad66b194929bea2a0487c Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 13:03:30 -0400 Subject: [PATCH 17/40] Update average.py Issue: the default behavior of maxATAC functions that generate averaged/normalized bigWig files is to generate bigWig files with 10 zoom levels (i.e., pre-computed summary statistics that enable quick zooming of bigWig files). This is extremely memory-intensive, but lower values of this parameter result in delayed loading of files in e.g., IGV. Solution: Added a new argument ("max_zooms") for the maxATAC average and normalize functions in parser.py, which defaults to 5. This will allow users to specify how many zoom levels they wish to retain in the final bigWig file (0-10). I successfully tested the argument for the above functions by specifying --max_zooms 5 in my function call. Also added code to convert values in the array used to generate the bigWig file from FP32 to FP16 values. This code was also successfully tested and resulted in additional memory savings of ~4%. --- maxatac/analyses/average.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/maxatac/analyses/average.py b/maxatac/analyses/average.py index 4352a55..8b4d392 100644 --- a/maxatac/analyses/average.py +++ b/maxatac/analyses/average.py @@ -24,7 +24,7 @@ def run_averaging(args): 4) Loop through each entry in the chromosome sizes dictionary and calculate the average across all inputs 5) Write the bigwig file - :param args: bigwig_files, output_dir, name, chromosomes, chromosome_sizes + :param args: bigwig_files, output_dir, name, chromosomes, chromosome_sizes, max_zooms :return: A bigwig file """ @@ -60,7 +60,7 @@ def run_averaging(args): header = [(x, chromosome_sizes_dictionary[x]) for x in sorted(args.chromosomes)] # Write the header to the file - output_bw.addHeader(header) + output_bw.addHeader(header, maxZooms = args.max_zooms) # TODO Use parallel processing to speed up. Must write chromosomes in same order as header # Loop through the chromosomes and average the values across files @@ -86,7 +86,7 @@ def run_averaging(args): ends=chrom_length, span=1, step=1, - values=chrom_vals.tolist() + values=chrom_vals.astype(np.float16).tolist() ) # Measure time of averaging @@ -99,4 +99,4 @@ def run_averaging(args): logging.info("Total averaging time: %d:%d:%d.\n" % (hours, mins, secs)) - logging.info("Results saved to: " + output_bigwig_filename) \ No newline at end of file + logging.info("Results saved to: " + output_bigwig_filename) From 99481e416d7d090f3cbb74f30e2ae9282ce3cd57 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 14:08:30 -0400 Subject: [PATCH 18/40] Update prepare.md --- docs/readme/prepare.md | 40 ++++++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/docs/readme/prepare.md b/docs/readme/prepare.md index a43d0ef..9306e16 100644 --- a/docs/readme/prepare.md +++ b/docs/readme/prepare.md @@ -54,38 +54,42 @@ This argument is used to set the prefix for setting the filenames. The default values for the optional arguments are based on the testing performed in the maxATAC publication. See the [Methods](https://www.biorxiv.org/content/10.1101/2022.01.28.478235v1.article-metrics) of our publication for a detailed explanation of each parameter choice. -### `-skip_dedup`, `--skip_deduplication` +### `--blacklist` -It is important to remove PCR duplicates from your ATAC-seq data if you have not done so already. Include this flag to perform PCR deduplication of the input BAM file if you know that it has not been deduplicated. Skipping this step will speed up data processing. Defualt: False +The path to the blacklist BED file. Default: maxATAC-defined blacklisted regions for hg38. -### `-slop`, `--slop` +### `--blacklist_bw` -The slop size used to smooth sparse Tn5 cut sites' signal. Each Tn5 cut site will be extended +/- the slop size (in bp). Because maxATAC models were trained using slop size of 20bp (a value that approximates the size of Tn5 transposase), **this parameter should not be changed from default (20 bp) when using the trained models provided by maxATAC**. Default: 20 bp. +The path to the blacklist bigWig file. Default: maxATAC-defined blacklist for hg38 as a bigWig file. -### `-rpm`, `--rpm_factor` +### `-c`, `-chroms`, `--chromosomes` -The reads per million (RPM) factor used for read-depth normalization of signal. Most groups use RPM and therefore 1,000,000 as a scaling factor, but maxATAC uses RP20M and therefore 20,000,000 because it is approximately the median sequencing depth of the ATAC-seq data used for training. Changing from the default (20000000) is not problematic for maxATAC prediction, as this track is only used for visualization. (Predictions are made on a min-max-like normalized signal track, also an output from `maxatac prepare`.) Default: 20000000. +The chromosomes to use for the final output. Default: Human autosomal chromosomes chr1-22. Note: this argument MUST be specified in conjunction with `--genome` if the input BAM file was aligned to a genome build other than hg38. -### `--blacklist` +### `-cs`, `--chrom_sizes`, `--chromosome_sizes` -The path to the blacklist bed file. Default: maxATAC defined blacklisted regions for hg38. +The chromosome sizes file. Default: hg38 chrom sizes. -### `--blacklist_bw` +### --genome -The path to the blacklist bigwig file. Default: maxATAC defined blacklist for hg38 as a bigwig file. +The genome build that was used for alignment of the input BAM file. Default: hg38. -### `-cs`, `--chrom_sizes`, `--chromosome_sizes` +### `--loglevel` -The chromosome sizes file. Default: hg38 chrom sizes. +The log level to use for printing messages. -### `-c`, `-chroms`, `--chromosomes` +### `-rpm`, `--rpm_factor` -The chromosomes to use for the final output. Default: Autosomal chromosomes chr1-22. +The reads per million (RPM) factor used for read-depth normalization of signal. Most groups use RPM and therefore 1,000,000 as a scaling factor, but maxATAC uses RP20M and therefore 20,000,000 because it is approximately the median sequencing depth of the ATAC-seq data used for training. Changing from the default (20000000) is not problematic for maxATAC prediction, as this track is only used for visualization. (Predictions are made on a min-max-like normalized signal track, also an output from `maxatac prepare`.) Default: 20000000. -### `-t`, `-threads` +### `-skip_dedup`, `--skip_deduplication` -The number of threads to use. Default: Get available CPU count. +It is important to remove PCR duplicates from your ATAC-seq data if you have not done so already. Include this flag to perform PCR deduplication of the input BAM file if you know that it has not been deduplicated. Skipping this step will speed up data processing. Defualt: False -### `--loglevel` +### `-slop`, `--slop` -The log level to use for printing messages. +The slop size used to smooth sparse Tn5 cut sites' signal. Each Tn5 cut site will be extended +/- the slop size (in bp). Because maxATAC models were trained using slop size of 20bp (a value that approximates the size of Tn5 transposase), **this parameter should not be changed from default (20 bp) when using the trained models provided by maxATAC**. Default: 20 bp. + +### `-t`, `-threads` + +The number of threads to use. Default: Get available CPU count. From a6e7503f6365fe0dec49acead804714d33405397 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 14:15:22 -0400 Subject: [PATCH 19/40] Update prepare.md --- docs/readme/prepare.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/readme/prepare.md b/docs/readme/prepare.md index 9306e16..8ff2170 100644 --- a/docs/readme/prepare.md +++ b/docs/readme/prepare.md @@ -64,11 +64,11 @@ The path to the blacklist bigWig file. Default: maxATAC-defined blacklist for hg ### `-c`, `-chroms`, `--chromosomes` -The chromosomes to use for the final output. Default: Human autosomal chromosomes chr1-22. Note: this argument MUST be specified in conjunction with `--genome` if the input BAM file was aligned to a genome build other than hg38. +The chromosomes to use for the final output. Default: Human autosomal chromosomes chr1-22. Note: this argument MUST be specified in conjunction with `--genome` and `--chrom_sizes` if the input BAM file was aligned to a genome build other than hg38. ### `-cs`, `--chrom_sizes`, `--chromosome_sizes` -The chromosome sizes file. Default: hg38 chrom sizes. +The chromosome sizes file. Default: hg38 chrom sizes. Note: this argument MUST be specified in conjunction with `--genome` and `--chromosomes` if the input BAM file was aligned to a genome build other than hg38. ### --genome From 40a97e8ce2858e8567d219ba9f5d409b7344287c Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 14:22:43 -0400 Subject: [PATCH 20/40] Update prepare.md --- docs/readme/prepare.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/readme/prepare.md b/docs/readme/prepare.md index 8ff2170..7ca8d3b 100644 --- a/docs/readme/prepare.md +++ b/docs/readme/prepare.md @@ -72,7 +72,7 @@ The chromosome sizes file. Default: hg38 chrom sizes. Note: this argument MUST b ### --genome -The genome build that was used for alignment of the input BAM file. Default: hg38. +The genome build that was used for alignment of the input file. Default: hg38. ### `--loglevel` From 9ea2d0f8739383644d51cb503da0a0b5f1310b91 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 14:33:11 -0400 Subject: [PATCH 21/40] Update normalize.md Updated the prepare documentation to: 1) include a description of the --genome argument, and 2) include a description of the --max_zooms argument. Also alphabetized optional arguments. --- docs/readme/normalize.md | 62 +++++++++++++++++++++++----------------- 1 file changed, 36 insertions(+), 26 deletions(-) diff --git a/docs/readme/normalize.md b/docs/readme/normalize.md index a91a573..e347d38 100644 --- a/docs/readme/normalize.md +++ b/docs/readme/normalize.md @@ -24,50 +24,60 @@ The name used to build the output filename. This can be any string. ## Optional Arguments -### `--method` +### `--blacklist_bw` -The method to use for normalization. Default: `min-max` +The path to the blacklist bigWig file. This file is used to remove all the regions that are considered to have high technical noise. Default: maxATAC publication-defined blacklist bigWig file. -* `min-max`: Find the genomic min and max values, then scale them between `[0,1]` or some user-defined range. The max value can be calculated as (1) the absolute max value across the genome (traditional definition of min-max) or (2) you can set a percentile cutoff to use as the max value. Option 2 improved robustness to outlying high ATAC-seq signal and maxATAC prediction accuracy. Specifically, we use the 99th-percentile max value instead of the absolute max value, and, given important performance ramifications, is the default. -* `zscore`: Set the mean value to 0 with a standard deviation of 1. -* `arcsinh`: Transform the values using an inverse hyperbolic sin transformation (arcsinh) +### `-c`, `--chroms`, `--chromosomes` -### `--max_percentile` +Define the chromosomes that are normalized. Only the chromosomes in this list will be written to the output file. The current default list of chromosomes are restricted to the human autosomal chromosomes: -If method is `min-max` this argument will set the percentile value to use as the reported max value. The default is `99`, so that default will be consistent with the ATAC-seq processing for the maxATAC models, where the 99th percentile value was used as the max value. +```pre +chr1, chr2, chr3, chr4, chr5, chr6, chr7, chr8, chr9, chr10, chr11, chr12, chr13, chr14, chr15, chr16, chr17, chr18, chr19, chr20, chr21, chr22 +``` -### `--min` +Note: this argument MUST be specified in conjunction with `--genome` and `--chrom_sizes` if the input BAM file was aligned to a genome build other than hg38. -The minimum value for `min-max` normalization. Default: `0` +### `--clip` -### `--max` +This flag determines whether to clip the values that are above the max value used in `min-max` normalization or to leave them as their real value. Default: `False` -The maximum value for `min-max` normalization. Default: `False`, so that max is calculated based on the ATAC signal track. +### `-cs`, `--chrom_sizes`, `--chromosome_sizes` -### `--clip` +Define the chromosome sizes file. The current default file are the chromosome sizes for hg38. Note: this argument MUST be specified in conjunction with `--genome` and `--chromosomes` if the input BAM file was aligned to a genome build other than hg38. -This flag determines whether to clip the values that are above the max value used in `min-max` normalization or to leave them as their real value. Default: `False` +### --genome -### `-c`, `--chroms`, `--chromosomes` +The genome build that was used for alignment of the input file. Default: hg38. -Define the chromosomes that are normalized. Only the chromosomes in this list will be written to the output file. The current default list of chromosomes are restricted to the autosomal chromosomes: +### `--loglevel` -```pre -chr1, chr2, chr3, chr4, chr5, chr6, chr7, chr8, chr9, chr10, chr11, chr12, chr13, chr14, chr15, chr16, chr17, chr18, chr19, chr20, chr21, chr22 -``` +Set the logging level. Currently, the only working logging level is `ERROR`. -### `-cs`, `--chrom_sizes`, `--chromosome_sizes` +### `--max` -Define the chromosome sizes file. The current default file are the chromosome sizes for hg38. +The maximum value for `min-max` normalization. Default: `False`, so that max is calculated based on the ATAC-seq signal track. -### `--blacklist_bw` +### `--max_percentile` -The path to the blacklist bigwig file. This file is used to remove all the regions that are considered to have high technical noise. Default: maxATAC publication-defined blacklist. +If the specified method is `min-max`, this argument will set the percentile value to use as the reported max value. The default is `99`, so that default will be consistent with the ATAC-seq processing for the maxATAC models, where the 99th percentile value was used as the max value. -### `-o`, `--output`, `--output_dir` +### `--max_zooms` -Define the output directory. If the output directory is not supplied a directory called `./normalize` will be created in the current working directory. +The number of zoom levels that should be computed for the normalized bigWig file. Zoom levels are pre-computed summary statistics that enable fast zooming into/out of a genomic region in a bigWig file when a visualization tool (e.g., IGV, UCSC Genome Browser). Lower values of this parameter result in slower loading of bigWig files in visualization tools, while higher values of this parameter result in a large memory overhead. The range of potential parameter values is (0-10). Default: 5. Note: if this argument is set to 0, the resulting bigWig files are NOT compatible with other bigWig tools (e.g., deepTools) and cannot be visualized using tools like IGV and the UCSC Genome Browser. Please see: https://github.com/deeptools/pyBigWig/blob/master/README.md for additional details. -### `--loglevel` +### `--method` -Set the logging level. Currently, the only working logging level is `ERROR`. +The method to use for normalization. Default: `min-max` + +* `min-max`: Find the genomic min and max values, then scale them between `[0,1]` or some user-defined range. The max value can be calculated as (1) the absolute max value across the genome (traditional definition of min-max) or (2) you can set a percentile cutoff to use as the max value. Option 2 improved robustness to outlying high ATAC-seq signal and maxATAC prediction accuracy. Specifically, we use the 99th-percentile max value instead of the absolute max value, and, given important performance ramifications, is the default. +* `zscore`: Set the mean value to 0 with a standard deviation of 1. +* `arcsinh`: Transform the values using an inverse hyperbolic sin transformation (arcsinh) + +### `--min` + +The minimum value for `min-max` normalization. Default: `0` + +### `-o`, `--output`, `--output_dir` + +Define the output directory. If the output directory is not supplied, a directory called `./normalize` will be created in the current working directory. From 1bc03097824441641c258cc0f3c7ca9ac77d1626 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 14:46:22 -0400 Subject: [PATCH 22/40] Update prepare.md --- docs/readme/prepare.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/readme/prepare.md b/docs/readme/prepare.md index 7ca8d3b..690313b 100644 --- a/docs/readme/prepare.md +++ b/docs/readme/prepare.md @@ -64,11 +64,11 @@ The path to the blacklist bigWig file. Default: maxATAC-defined blacklist for hg ### `-c`, `-chroms`, `--chromosomes` -The chromosomes to use for the final output. Default: Human autosomal chromosomes chr1-22. Note: this argument MUST be specified in conjunction with `--genome` and `--chrom_sizes` if the input BAM file was aligned to a genome build other than hg38. +The chromosomes to use for the final output. Default: Human autosomal chromosomes chr1-22. Note: this argument MUST be specified in conjunction with `--genome` and `--chrom_sizes` if the input file was aligned to a genome build other than hg38. ### `-cs`, `--chrom_sizes`, `--chromosome_sizes` -The chromosome sizes file. Default: hg38 chrom sizes. Note: this argument MUST be specified in conjunction with `--genome` and `--chromosomes` if the input BAM file was aligned to a genome build other than hg38. +The chromosome sizes file. Default: hg38 chrom sizes. Note: this argument MUST be specified in conjunction with `--genome` and `--chromosomes` if the input file was aligned to a genome build other than hg38. ### --genome From c6563cabbfba7717a5accededdad7145899250a7 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 14:47:49 -0400 Subject: [PATCH 23/40] Update normalize.md --- docs/readme/normalize.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/readme/normalize.md b/docs/readme/normalize.md index e347d38..3d982de 100644 --- a/docs/readme/normalize.md +++ b/docs/readme/normalize.md @@ -16,7 +16,7 @@ maxatac normalize -i GM12878_RP20M.bw -name GM12878_minmax -o ./test --method mi ### `-i`, `--signal` -The input bigwig file to be normalized. +The input bigWig file to be normalized. ### `-n`, `--name`, `--prefix` @@ -36,7 +36,7 @@ Define the chromosomes that are normalized. Only the chromosomes in this list wi chr1, chr2, chr3, chr4, chr5, chr6, chr7, chr8, chr9, chr10, chr11, chr12, chr13, chr14, chr15, chr16, chr17, chr18, chr19, chr20, chr21, chr22 ``` -Note: this argument MUST be specified in conjunction with `--genome` and `--chrom_sizes` if the input BAM file was aligned to a genome build other than hg38. +Note: this argument MUST be specified in conjunction with `--genome` and `--chrom_sizes` if the input file was aligned to a genome build other than hg38. ### `--clip` @@ -44,7 +44,7 @@ This flag determines whether to clip the values that are above the max value use ### `-cs`, `--chrom_sizes`, `--chromosome_sizes` -Define the chromosome sizes file. The current default file are the chromosome sizes for hg38. Note: this argument MUST be specified in conjunction with `--genome` and `--chromosomes` if the input BAM file was aligned to a genome build other than hg38. +Define the chromosome sizes file. The current default file are the chromosome sizes for hg38. Note: this argument MUST be specified in conjunction with `--genome` and `--chromosomes` if the input file was aligned to a genome build other than hg38. ### --genome From dcdf6b6ba82a7a5e2d2e04068fb90f51651085b4 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 14:51:22 -0400 Subject: [PATCH 24/40] Update average.md Updated the prepare documentation to include: A description of the --genome argument A description of the --max_zooms argument Also alphabetized optional arguments. --- docs/readme/average.md | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/docs/readme/average.md b/docs/readme/average.md index e0b4d78..85c6c28 100644 --- a/docs/readme/average.md +++ b/docs/readme/average.md @@ -28,22 +28,27 @@ The name string used to build the output filename. The extension `.bw` will be a ## Optional Arguments -### `-cs`, `--chrom_sizes`, `--chromosome_sizes` - -The chromosome sizes file for the reference genome used during alignment. The current default is set for hg38. - ### `-c`, `--chroms`, `--chromosomes` -The chromosomes that are averaged together and written to output. Only the chromosomes in this list will be written to the output file. The current default list of chromosomes are restricted to the autosomal chromosomes: +The chromosomes that are averaged together and written to output. Only the chromosomes in this list will be written to the output file. The current default list of chromosomes are restricted to the human autosomal chromosomes: ```bash chr1 chr2 chr3 chr4 chr5 chr6 chr7 chr8 chr9 chr10 chr11 chr12 chr13 chr14 chr15 chr16 chr17 chr18 chr19 chr20 chr21 chr22 ``` -### `-o`, `--output`, `--output_dir` +Note: this argument MUST be specified in conjunction with `--genome` and `--chrom_sizes` if the input file was aligned to a genome build other than hg38. + +### `-cs`, `--chrom_sizes`, `--chromosome_sizes` + +The chromosome sizes file for the reference genome used during alignment. The current default is set for hg38. Note: this argument MUST be specified in conjunction with `--genome` and `--chromosomes` if the input file was aligned to a genome build other than hg38. -The output directory. If the output directory is not supplied the file will be created in the current working directory. +### `--max_zooms` +The number of zoom levels that should be computed for the normalized bigWig file. Zoom levels are pre-computed summary statistics that enable fast zooming into/out of a genomic region in a bigWig file when a visualization tool (e.g., IGV, UCSC Genome Browser). Lower values of this parameter result in slower loading of bigWig files in visualization tools, while higher values of this parameter result in a large memory overhead. The range of potential parameter values is (0-10). Default: 5. Note: if this argument is set to 0, the resulting bigWig files are NOT compatible with other bigWig tools (e.g., deepTools) and cannot be visualized using tools like IGV and the UCSC Genome Browser. Please see: https://github.com/deeptools/pyBigWig/blob/master/README.md for additional details. ### `--loglevel` Set the logging level. Currently, the only working logging level is `ERROR`. + +### `-o`, `--output`, `--output_dir` + +The output directory. If the output directory is not supplied, the file will be created in the current working directory. From d42e0a9aab3dec00e4577a7e3a83163d2486656f Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 14:57:34 -0400 Subject: [PATCH 25/40] Update normalize.md --- docs/readme/normalize.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/readme/normalize.md b/docs/readme/normalize.md index 3d982de..36fe19b 100644 --- a/docs/readme/normalize.md +++ b/docs/readme/normalize.md @@ -46,7 +46,7 @@ This flag determines whether to clip the values that are above the max value use Define the chromosome sizes file. The current default file are the chromosome sizes for hg38. Note: this argument MUST be specified in conjunction with `--genome` and `--chromosomes` if the input file was aligned to a genome build other than hg38. -### --genome +### `--genome` The genome build that was used for alignment of the input file. Default: hg38. From de1c4a0374855b4a9325afb8f56980e2870ad6a3 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 14:59:15 -0400 Subject: [PATCH 26/40] Update benchmark.md Updated the benchmark.py documentation to include a description of the --genome argument. Also alphabetized optional arguments. --- docs/readme/benchmark.md | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/docs/readme/benchmark.md b/docs/readme/benchmark.md index 782762f..6f1518f 100644 --- a/docs/readme/benchmark.md +++ b/docs/readme/benchmark.md @@ -12,11 +12,11 @@ maxatac benchmark --prediction GM12878_CTCF_chr1.bw --gold_standard GM12878_CTCF ### `--prediction` -The input bigwig file of transcription factor binding predictions. This file can also be any bigwig signal track that you want to compare against a gold standard. +The input bigWig file of transcription factor binding predictions. This file can also be any bigWig signal track that you want to compare against a gold standard. ### `--gold_standard` -The input gold standard bigwig file. This file needs to be a binary signal track that has 1 corresponding to TFBS (e.g., from ChIP-seq) and 0 in positions with no TFBS. +The input gold standard bigWig file. This file needs to be a binary signal track that has 1 corresponding to TFBS (e.g., from ChIP-seq) and 0 in positions with no TFBS. ### `--prefix` @@ -24,32 +24,36 @@ The output filename prefix to use. Default: `maxatac_benchmark` ## Optional Arguments -### `--chromosomes` +### `--agg` + +The method to use for aggregating the single base-pair predictions into larger bins. Options include `max`, `min`, and `mean`. Default: `max` score found in the window. -The chromosomes to benchmark the predictions for. Default: `chr1` is the held out test chromosome. +See the [pyBigWig documentation](https://github.com/deeptools/pyBigWig#compute-summary-information-on-a-range) for more details. ### `--bin_size` The size of the bin to use for aggregating the single base-pair predictions. Default: `200` is the size used by the [ENCODE-DREAM in vivo TFBS Prediction Challenge](https://www.synapse.org/#!Synapse:syn6131484/wiki/402026) -### `--agg` +### `--blacklist_bw` -The method to use for aggregating the single base-pair predictions into larger bins. Options include `max`, `min`, and `mean`. Default: `max` score found in the window. +The path to the blacklist bigWig signal track of regions that should be excluded. Default: `hg38_maxatac_blacklist.bw`, which contains regions that are specific to ATAC-seq. -See the [pyBigWig documentation](https://github.com/deeptools/pyBigWig#compute-summary-information-on-a-range) for more details. +### `--chromosomes` -### `--round_predictions` +The chromosomes to benchmark the predictions for. Default: `chr1` is a held-out test chromosome. -This flag will set the precision of the predictions signal track. Provide an integer that represents the number of floats before rounding. Currently, the predictions go from `0 - .0000000001`. Default: `9` is the limit of precision from TensorFlow. +### `--genome` -### `--output_directory` +The genome build that was used for the prediction file. Default: hg38. -The output directory to write the results to. Default: `./prediction_results` +### `--loglevel` -### `--blacklist_bw` +This argument is used to set the logging level. Currently, the only working logging level is `ERROR`. + +### `--output_directory` -The path to the blacklist bigwig signal track of regions that should be excluded. Default: `hg38_maxatac_blacklist.bed` which contains regions that are specific to ATAC-seq. +The output directory to write the results to. Default: `./prediction_results` -### `--loglevel` +### `--round_predictions` -This argument is used to set the logging level. Currently, the only working logging level is `ERROR`. +This flag will set the precision of the predictions signal track. Provide an integer that represents the number of floats before rounding. Currently, the predictions go from `0 - .0000000001`. Default: `9` is the limit of precision from TensorFlow. From 9eda2103dd5bd06e9f566b177b1707d02979088e Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 15:20:24 -0400 Subject: [PATCH 27/40] Update average.md --- docs/readme/average.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/readme/average.md b/docs/readme/average.md index 85c6c28..d3a6189 100644 --- a/docs/readme/average.md +++ b/docs/readme/average.md @@ -43,7 +43,7 @@ Note: this argument MUST be specified in conjunction with `--genome` and `--chro The chromosome sizes file for the reference genome used during alignment. The current default is set for hg38. Note: this argument MUST be specified in conjunction with `--genome` and `--chromosomes` if the input file was aligned to a genome build other than hg38. ### `--max_zooms` -The number of zoom levels that should be computed for the normalized bigWig file. Zoom levels are pre-computed summary statistics that enable fast zooming into/out of a genomic region in a bigWig file when a visualization tool (e.g., IGV, UCSC Genome Browser). Lower values of this parameter result in slower loading of bigWig files in visualization tools, while higher values of this parameter result in a large memory overhead. The range of potential parameter values is (0-10). Default: 5. Note: if this argument is set to 0, the resulting bigWig files are NOT compatible with other bigWig tools (e.g., deepTools) and cannot be visualized using tools like IGV and the UCSC Genome Browser. Please see: https://github.com/deeptools/pyBigWig/blob/master/README.md for additional details. +The number of zoom levels that should be computed for the averaged bigWig file. Zoom levels are pre-computed summary statistics that enable fast zooming into/out of a genomic region in a bigWig file when a visualization tool (e.g., IGV, UCSC Genome Browser). Lower values of this parameter result in slower loading of bigWig files in visualization tools, while higher values of this parameter result in a large memory overhead. The range of potential parameter values is (0-10). Default: 5. Note: if this argument is set to 0, the resulting bigWig files are NOT compatible with other bigWig tools (e.g., deepTools) and cannot be visualized using tools like IGV and the UCSC Genome Browser. Please see: https://github.com/deeptools/pyBigWig/blob/master/README.md for additional details. ### `--loglevel` From f40be4f11a3588ac5542998fe0a82feb1118db56 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 15:21:07 -0400 Subject: [PATCH 28/40] Update predict.md Updated the normalize.py documentation to include: A description of the --genome argument A description of the --max_zooms argument Missing default values Also alphabetized optional arguments. --- docs/readme/predict.md | 62 ++++++++++++++++++++++++------------------ 1 file changed, 35 insertions(+), 27 deletions(-) diff --git a/docs/readme/predict.md b/docs/readme/predict.md index 62f91e7..b068724 100644 --- a/docs/readme/predict.md +++ b/docs/readme/predict.md @@ -22,7 +22,7 @@ The user must provide either the TF name that they want to make predictions for ### `-s, --signal, -i` -The ATAC-seq signal bigwig track that will be used to make TF binding predictions. +The ATAC-seq signal bigWig track that will be used to make TF binding predictions. ### `-n, --name, --prefix` @@ -30,58 +30,66 @@ Output filename prefix (without extension) to use. Default `maxatac_predict`. ## Optional Arguments -### `--sequence, --seq` +### `--batch_size` -This argument specifies the path to the 2bit DNA sequence for the genome of interest. maxATAC models are trained with hg38 so you will need the correct `.2bit` file. +The number of regions to predict on per batch. Default `10000`. Decrease this value if you are having memory issues. -### `"-ct", "-cutoff_type", "--cutoff_type"` +### `--bed, --peaks, --regions, , --roi, -roi` -The cutoff type (i.e. `Precision`, `Recall`, `F1`, `log2FC`). (F1 = F1-score, and log2FC = Log2( Precision : Random Precision)). Default: F1. +The path to a BED file containing genomic regions to focus TF predictions on. These peaks will be used to refine the prediction windows. Default: whole-chromosome predictions. -### `"-cv", "-cutoff_value", "--cutoff_value"` +### `-bl, --blacklist` -The cutoff value for the cutoff type provided. Note precision, recall, and F1-scores range 0-1, while better-than-random log2FC scores range from 0 to infinity. Example: 0.7. +The path to a bigWig file that has regions to exclude. Default: maxATAC-defined blacklist. + +### `-c, -chroms, --chromosomes` + +The chromosomes to make predictions on. Our models do not currently consider chromosomes X or Y. This means that most of the files will not contain this information. You should not predict in chrX or chrY unless you know your bigWig contains these chromosomes. Default: human autosomal chromosomes 1-22. Note: this argument MUST be specified in conjunction with `--genome`, `-sequence`, and `--chrom_sizes` if the input file was aligned to a genome build other than hg38. + +### `-cs, --chrom_sizes, -chrom_sizes, --chromosome_sizes` + +The path to the chromosome sizes file. This is used to generate the bigwig signal tracks. Note: this argument MUST be specified in conjunction with `--genome`, `-sequence`, and `--chromosomes` if the input file was aligned to a genome build other than hg38. ### `"-cf", -cutoff_file, --cutoff_file` The cutoff file provided in /data/models that corresponds to the average validation performance metrics for the TF model. -### `-o, --output` +### `"-ct", "-cutoff_type", "--cutoff_type"` -Output directory path. Default: `./prediction_results` +The cutoff type (i.e. `Precision`, `Recall`, `F1`, `log2FC`). (F1 = F1-score, and log2FC = Log2( Precision : Random Precision)). Default: F1. -### `-bl, --blacklist` +### `"-cv", "-cutoff_value", "--cutoff_value"` -The path to a bigWig file that has regions to exclude. Default: maxATAC-defined blacklist. +The cutoff value for the cutoff type provided. Note: precision, recall, and F1-scores range from 0-1, while better-than-random log2FC scores range from 0 to infinity. Example: 0.7. -### `--bed, --peaks, --regions, , --roi, -roi` +### `--genome` -The path to a BED file containing genomic regions to focus TF predictions on. These peaks will be used to refine the prediction windows. Default: whole-chromosome predictions. +The genome build that was used for alignment of the ATAC-seq signal file. Default: hg38. -### `--batch_size` +### `--max_zooms` -The number of regions to predict on per batch. Default `10000`. Decrease this value if you are having memory issues. +The number of zoom levels that should be computed for the output bigWig file. Zoom levels are pre-computed summary statistics that enable fast zooming into/out of a genomic region in a bigWig file when a visualization tool (e.g., IGV, UCSC Genome Browser). Lower values of this parameter result in slower loading of bigWig files in visualization tools, while higher values of this parameter result in a large memory overhead. The range of potential parameter values is (0-10). Default: 5. Note: if this argument is set to 0, the resulting bigWig files are NOT compatible with other bigWig tools (e.g., deepTools) and cannot be visualized using tools like IGV and the UCSC Genome Browser. Please see: https://github.com/deeptools/pyBigWig/blob/master/README.md for additional details. -### `--step_size` +### `--loglevel` -The step size to use for building the prediction intervals. Overlapping prediction bins will be averaged together. Default: `INPUT_LENGTH/4`, where INPUT_LENGTH is the maxATAC model input size of 1,024 bp. +This argument is used to set the logging level. Currently, the only working logging level is `ERROR`. -### `-cs, --chrom_sizes, -chrom_sizes, --chromosome_sizes` +### `-o, --output` -The path to the chromosome sizes file. This is used to generate the bigwig signal tracks. +Output directory path. Default: `./prediction_results` -### `-c, -chroms, --chromosomes` +### `--sequence, --seq` -The chromosomes to make predictions on. Our models do not currently consider chromosomes X or Y. This means that most of the files will not contain this information. You should not predict in chrX or chrY unless you know your bigWig contains these chromosomes. Default: autosomal chromosomes 1-22. +This argument specifies the path to the 2bit DNA sequence for the genome of interest. maxATAC models are trained with hg38, so you will need the correct `.2bit` file. Note: this argument MUST be specified (with a valid 2bit file) in conjunction with `--genome`, `--chrom_sizes`, and `--chromosomes` if the input file was aligned to a genome build other than hg38. -### `--loglevel` +### `-skip_call_peaks, --skip_call_peaks` -This argument is used to set the logging level. Currently, the only working logging level is `ERROR`. +This will skip calling peaks on prediction tracks. Default: `False` -### `-w, --windows` +### `--step_size` -The windows to use for prediction. These windows must be 1,024 bp wide and have a consistent step size. +The step size to use for building the prediction intervals. Overlapping prediction bins will be averaged together. Default: `INPUT_LENGTH/4`, where INPUT_LENGTH is the maxATAC model input size of 1,024 bp. -### `-skip_call_peaks, --skip_call_peaks` +### `-w, --windows` -This will skip calling peaks on prediction tracks. +The windows to use for prediction. These windows must be 1,024 bp wide and have a consistent step size. From c7a6d9b7c5214121cb0ea04951b2258dfd954b94 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 15:27:50 -0400 Subject: [PATCH 29/40] Update parser.py Issue: the default behavior of maxATAC functions that generate averaged/normalized bigWig files is to generate bigWig files with 10 zoom levels (i.e., pre-computed summary statistics that enable quick zooming of bigWig files). This is extremely memory-intensive, but lower values of this parameter result in delayed loading of files in e.g., IGV. Solution: Added a new argument ("max_zooms") for the maxATAC average and normalize functions in parser.py, which defaults to 5. This will allow users to specify how many zoom levels they wish to retain in the final bigWig file (0-10). I successfully tested the argument for the above functions by specifying all possible values of --max_zooms in my function call. Also added code to convert values in the array used to generate the bigWig file from FP32 to FP16 values. This code was also successfully tested and resulted in additional memory savings of ~4%. --- maxatac/utilities/parser.py | 113 +++++++++++++++++++++++++++++++----- 1 file changed, 99 insertions(+), 14 deletions(-) diff --git a/maxatac/utilities/parser.py b/maxatac/utilities/parser.py index 840e748..43dccdb 100644 --- a/maxatac/utilities/parser.py +++ b/maxatac/utilities/parser.py @@ -176,6 +176,22 @@ def get_parser(): help="Chromosomes for averaging. Default: 1-22" ) + average_parser.add_argument("--genome", + dest="genome", + type=str, + default="hg38", + required=False, + help="The reference genome build to which the input file was aligned." + ) + + average_parser.add_argument("--max_zooms", + dest="max_zooms", + type=int, + default=5, + required=False, + help="The number of zoom levels that should be computed for the averaged bigWig file." + ) + average_parser.add_argument("-o", "--output", "--output_dir", dest="output_dir", type=str, @@ -222,6 +238,22 @@ def get_parser(): type=str, help="Genome sequence 2bit file." ) + + predict_parser.add_argument("--genome", + dest="genome", + type=str, + default="hg38", + required=False, + help="The reference genome build to which the input file was aligned." + ) + + average_parser.add_argument("--max_zooms", + dest="max_zooms", + type=int, + default=5, + required=False, + help="The number of zoom levels that should be computed for the output bigWig file." + ) predict_parser.add_argument("-i", "-s", "--signal", dest="signal", @@ -329,6 +361,13 @@ def get_parser(): required=False, help="Skip calling peaks on prediction tracks" ) + + predict_parser.add_argument("--threads", + dest="threads", + type=int, + default=24, + help="Number of processes to run prediction in parallel. Default: 24." + ) ############################################# # Train parser @@ -347,7 +386,7 @@ def get_parser(): type=str, default="hg38", required=False, - help="The reference genome build to use." + help="The reference genome build to which the input file was aligned." ) train_parser.add_argument("--sequence", @@ -580,20 +619,20 @@ def get_parser(): type=str, required=True, help="Input .bigwig file." - ) + ) normalize_parser.add_argument("-n", "--name", "--prefix", required=True, dest="name", type=str, help="Name to use for filename" - ) + ) normalize_parser.add_argument("-cs", "--chrom_sizes", "--chromosome_sizes", dest="chrom_sizes", type=str, help="Chrom sizes file" - ) + ) normalize_parser.add_argument("-c", "--chroms", "--chromosomes", dest="chromosomes", @@ -601,14 +640,30 @@ def get_parser(): nargs="+", default=AUTOSOMAL_CHRS, help="Chromosomes for normalization. Default: 1-22" - ) + ) + + normalize_parser.add_argument("--genome", + dest="genome", + type=str, + default="hg38", + required=False, + help="The reference genome build to which the input file was aligned." + ) + + normalize_parser.add_argument("--max_zooms", + dest="max_zooms", + type=int, + default=5, + required=False, + help="The number of zoom levels that should be computed for the normalized bigWig file." + ) normalize_parser.add_argument("-o", "--output", "--output_dir", dest="output_dir", type=str, default=os.getcwd(), help="Output directory. Default: Output to current working directory." - ) + ) normalize_parser.add_argument("--min", dest="min", @@ -616,7 +671,7 @@ def get_parser(): type=int, default=0, help="The minimum value to use for normalization" - ) + ) normalize_parser.add_argument("--max", dest="max", @@ -624,7 +679,7 @@ def get_parser(): required=False, default=False, help="The maximum value to use for normalization" - ) + ) normalize_parser.add_argument("--clip", dest="clip", @@ -632,21 +687,21 @@ def get_parser(): required=False, default=False, help="Whether to clip minmax values to the range 0,1" - ) + ) normalize_parser.add_argument("--method", dest="method", type=str, default="min-max", help="The method to use for normalization" - ) + ) normalize_parser.add_argument("--max_percentile", dest="max_percentile", type=int, default=99, help="The maximum percentile to use for normalization" - ) + ) normalize_parser.add_argument("--loglevel", dest="loglevel", @@ -654,13 +709,13 @@ def get_parser(): default="info", choices=LOG_LEVELS.keys(), help="Logging level. Default: " + DEFAULT_LOG_LEVEL - ) + ) normalize_parser.add_argument("--blacklist_bw", dest="blacklist_bw", type=str, help="The blacklisted regions to exclude (BigWig file format)" - ) + ) ############################################# # Benchmark subparser @@ -722,6 +777,14 @@ def get_parser(): max, mean, min" ) + benchmark_parser.add_argument("--genome", + dest="genome", + type=str, + default="hg38", + required=False, + help="The reference genome build to which the input file was aligned." + ) + benchmark_parser.add_argument("--round_predictions", dest="round_predictions", type=int, @@ -887,7 +950,7 @@ def get_parser(): type=str, default="hg38", required=False, - help="The reference genome build to use." + help="The reference genome build to which the input file was aligned." ) variants_parser.add_argument("-s", "--sequence", @@ -1015,6 +1078,14 @@ def get_parser(): help="The chromosomes to include in the final output." ) + prepare_parser.add_argument("--genome", + dest="genome", + type=str, + default="hg38", + required=False, + help="The reference genome build to which the input file was aligned." + ) + prepare_parser.add_argument("-t", "-threads", "--threads", dest="threads", type=int, @@ -1091,12 +1162,26 @@ def get_parser(): choices=LOG_LEVELS.keys(), help="Logging level. Default: " + DEFAULT_LOG_LEVEL ) + + threshold_parser.add_argument("--genome", + dest="genome", + type=str, + default="hg38", + required=False, + help="The reference genome build to which the input BAM file was aligned." + ) threshold_parser.add_argument("--blacklist_bw", dest="blacklist_bw", type=str, help="The blacklisted regions to exclude in bigwig format." ) + + threshold_parser.add_argument("--blacklist_bed", + dest="blacklist_bed", + type=str, + help="The blacklisted regions to exclude in bigwig format." + ) threshold_parser.add_argument("--meta_file", dest="meta_file", From d4380aa6490d1f95ca3520bd6562f46f9b97bf9d Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 15:33:15 -0400 Subject: [PATCH 30/40] Update predict.py Issue: the default behavior of maxATAC functions that generate averaged/normalized bigWig files is to generate bigWig files with 10 zoom levels (i.e., pre-computed summary statistics that enable quick zooming of bigWig files). This is extremely memory-intensive, but lower values of this parameter result in delayed loading of files in e.g., IGV. Solution: Added a new argument ("max_zooms") for the maxATAC average and normalize functions in parser.py, which defaults to 5. This will allow users to specify how many zoom levels they wish to retain in the final bigWig file (0-10). I successfully tested the argument for the above functions by specifying all possible values of --max_zooms in my function call. Also added code to convert values in the array used to generate the bigWig file from FP32 to FP16 values. This code was also successfully tested and resulted in additional memory savings of ~4%. --- maxatac/analyses/predict.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/maxatac/analyses/predict.py b/maxatac/analyses/predict.py index f6c9c47..32565b2 100644 --- a/maxatac/analyses/predict.py +++ b/maxatac/analyses/predict.py @@ -119,7 +119,8 @@ def run_prediction(args): write_predictions_to_bigwig(prediction_bedgraph, output_filename=outfile_name_bigwig, chrom_sizes_dictionary=chrom_sizes_dict, - chromosomes=chrom_list + chromosomes=chrom_list, + max_zooms = args.max_zooms ) # If a cutoff file is provided, call peaks @@ -160,7 +161,6 @@ def run_prediction(args): index=False, header=False) - # Measure end time of training stopTime = timeit.default_timer() totalTime = stopTime - startTime From 4d632204f83130f104ffa9e31bdcd4990bbe5979 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Tue, 14 Jul 2026 15:41:00 -0400 Subject: [PATCH 31/40] Update prediction_tools.py Issue: the default behavior of maxATAC predict is to generate bigWig files with 10 zoom levels (i.e., pre-computed summary statistics that enable quick zooming of bigWig files). This is extremely memory-intensive, but lower values of this parameter result in delayed loading of files in e.g., IGV. Solution: Added a new argument ("max_zooms") for the maxATAC predict function in parser.py, which defaults to 5. This will allow users to specify how many zoom levels they wish to retain in the final bigWig file (0-10). I successfully tested the argument for the above functions by specifying all possible values of --max_zooms in my function call. Also added code to convert values in the array used to generate the bigWig file from FP32 to FP16 values in prediction_tools.py. This code was also successfully tested. --- maxatac/utilities/prediction_tools.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/maxatac/utilities/prediction_tools.py b/maxatac/utilities/prediction_tools.py index c793014..b9a0c55 100644 --- a/maxatac/utilities/prediction_tools.py +++ b/maxatac/utilities/prediction_tools.py @@ -1,5 +1,4 @@ import logging - import numpy as np import pandas as pd import pybedtools @@ -31,6 +30,7 @@ def write_predictions_to_bigwig(df: pd.DataFrame, output_filename: str, chrom_sizes_dictionary: dict, chromosomes: list, + max_zooms: int, agg_mean: bool = True ): """Write the predictions dataframe into a bigwig file @@ -40,10 +40,11 @@ def write_predictions_to_bigwig(df: pd.DataFrame, output_filename (str): The output bigwig filename chrom_sizes_dictionary (dict): A dictionary of chromosome sizes used to form the bigwig file chromosomes (list): A list of chromosomes that you are predicting in - agg_mean (bool, optional): use aggregation method of mean. Defaults to True. + max_zooms (int, optional): The desired number of zoom levels to be retained in the output bigWig file. Defaults to 5. + agg_mean (bool, optional): Use aggregation method of mean. Defaults to True. Returns: - Writes a bigwig file + Writes a bigWig file Example: @@ -63,7 +64,7 @@ def write_predictions_to_bigwig(df: pd.DataFrame, header = [(x, chrom_sizes_dictionary[x]) for x in chromosomes] # Add header to bigwig - data_stream.addHeader(header) + data_stream.addHeader(header, maxZooms = max_zooms) for chromosome in chromosomes: # Create a tmp df from the predictions dataframe for each chrom @@ -76,10 +77,9 @@ def write_predictions_to_bigwig(df: pd.DataFrame, data_stream.addEntries(chroms=tmp_chrom_df["chr"].tolist(), starts=tmp_chrom_df["start"].tolist(), ends=tmp_chrom_df["stop"].tolist(), - values=tmp_chrom_df["score"].tolist() + values=tmp_chrom_df["score"].astype(np.float16).tolist() ) - def import_prediction_regions(bed_file: str, chromosomes: list, chrom_sizes_dictionary: dict, @@ -220,7 +220,6 @@ def create_prediction_regions(chromosomes: list, return df - class PredictionDataGenerator(tf.keras.utils.Sequence): def __init__(self, signal, @@ -327,7 +326,6 @@ def __get_region_values__(self, roi_pool): return np.array(inputs_batch) - def make_stranded_predictions(roi_pool: pd.DataFrame, signal: str, sequence: str, From a84247d7a87dd236c7bf6be1fab18611a65a7ed7 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Wed, 5 Aug 2026 12:45:41 -0400 Subject: [PATCH 32/40] Update train.md **Problem**: The published maxATAC models underwent 100 epochs of training. However, the README.md and constants.py set the default number of epochs to 20. ** Fix**: Updated the default number of epochs from 20 to 100 to match the value used in (Cazares et al., 2023). --- docs/readme/train.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/readme/train.md b/docs/readme/train.md index b06263f..b111f01 100644 --- a/docs/readme/train.md +++ b/docs/readme/train.md @@ -110,7 +110,7 @@ The weights to use for initializing a model prior to training. Default: `do not ### `--epochs` -The number of epochs to train the model for. Default: `20`. +The number of epochs to train the model for. Default: `100`. ### `--batches` From 022f7a4c8bf4eb7d4519bb8ca8497a56815c4b06 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Wed, 5 Aug 2026 12:46:43 -0400 Subject: [PATCH 33/40] Update constants.py **Problem**: The published maxATAC models underwent 100 epochs of training. However, the README.md and constants.py set the default number of epochs to 20. **Fix**: Updated the default number of epochs from 20 to 100 to match the value used in (Cazares et al., 2023). --- maxatac/utilities/constants.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maxatac/utilities/constants.py b/maxatac/utilities/constants.py index 122948c..14e047f 100644 --- a/maxatac/utilities/constants.py +++ b/maxatac/utilities/constants.py @@ -67,7 +67,7 @@ DEFAULT_LOG_LEVEL = "info" -DEFAULT_TRAIN_EPOCHS = 20 +DEFAULT_TRAIN_EPOCHS = 100 DEFAULT_TRAIN_BATCHES_PER_EPOCH = 100 From c74896ca24d7498d204482699f413c921ac1cb53 Mon Sep 17 00:00:00 2001 From: "Akshata N. Rudrapatna" <139808049+ANRudrapatna@users.noreply.github.com> Date: Mon, 14 Sep 2026 14:40:49 -0400 Subject: [PATCH 34/40] Update parser.py Removed duplicate entries in the parser. --- maxatac/utilities/parser.py | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/maxatac/utilities/parser.py b/maxatac/utilities/parser.py index abce03c..bd7534e 100644 --- a/maxatac/utilities/parser.py +++ b/maxatac/utilities/parser.py @@ -175,14 +175,6 @@ def get_parser(): default=AUTOSOMAL_CHRS, help="Chromosomes for averaging. Default: 1-22" ) - - average_parser.add_argument("--genome", - dest="genome", - type=str, - default="hg38", - required=False, - help="The reference genome build to use." - ) average_parser.add_argument("--genome", dest="genome", @@ -263,13 +255,6 @@ def get_parser(): help="The number of zoom levels that should be computed for the output bigWig file." ) - predict_parser.add_argument("--genome", - dest="genome", - type=str, - default="hg38", - required=False, - help="The reference genome build to use.") - predict_parser.add_argument("-i", "-s", "--signal", dest="signal", type=str, From a3d5fc93b8eacf7743f9d4a9d52c11241f691aca Mon Sep 17 00:00:00 2001 From: XC Date: Sun, 20 Sep 2026 22:49:23 -0400 Subject: [PATCH 35/40] q-maxATAC v2 preview (improved documentation, main branch changes merged, code review issues mostly addressed) --- docs/readme/normalize.md | 3 +- docs/readme/threshold.md | 8 +- maxatac/analyses/normalize.py | 5 +- maxatac/analyses/predict.py | 10 +- maxatac/analyses/threshold.py | 79 +- maxatac/analyses/train.py | 7 +- maxatac/architectures/dcnn.py | 20 +- maxatac/utilities/benchmarking_tools.py | 39 +- maxatac/utilities/callbacks.py | 12 +- maxatac/utilities/constants.py | 2 + maxatac/utilities/genome_tools.py | 42 - maxatac/utilities/losses.py | 116 +- maxatac/utilities/normalization_tools.py | 12 +- maxatac/utilities/parser.py | 16 +- .../utilities/save_predictions_callback.py | 43 - maxatac/utilities/training_tools.py | 18 +- setup.py | 10 +- tests/test_benchmark.py | 31 + tests/test_parser.py | 1005 +---------------- 19 files changed, 207 insertions(+), 1271 deletions(-) delete mode 100644 maxatac/utilities/save_predictions_callback.py diff --git a/docs/readme/normalize.md b/docs/readme/normalize.md index c95ee6c..2725920 100644 --- a/docs/readme/normalize.md +++ b/docs/readme/normalize.md @@ -6,7 +6,6 @@ The `normalize` function will normalize an input bigwig file based on the follow * `zscore`: Set the mean value to 0 with a standard deviation of 1. * Variance-stabilizing transforms, provided for preparing **quantitative ChIP-seq target tracks** for `--quant` training and benchmarking: * `arcsinh`: inverse hyperbolic sine, `arcsinh(x)` - * `log2`: `log2(x) + 1` * `log1p`: natural log of one plus the value, `log(1 + x)` * `sqrt`: square root, `x^(1/2)` * `three_fourths`: `x^(3/4)` @@ -37,7 +36,7 @@ The name used to build the output filename. This can be any string; `.bw` is app ### `--method` -The method to use for normalization: `min-max`, `zscore`, `arcsinh`, `log2`, `log1p`, `sqrt`, `three_fourths` or `three_eighths` (see above). Default: `min-max` +The method to use for normalization: `min-max`, `zscore`, `arcsinh`, `log1p`, `sqrt`, `three_fourths` or `three_eighths` (see above). Default: `min-max` ### `--max_percentile` diff --git a/docs/readme/threshold.md b/docs/readme/threshold.md index ccfa05b..120ec33 100644 --- a/docs/readme/threshold.md +++ b/docs/readme/threshold.md @@ -8,7 +8,7 @@ Because quantitative models output predicted ChIP-seq signal rather than probabi For every cell type listed in the meta file: -1. The prediction bigwig and the binary gold standard bigwig are binned at `--bin_size` (max per bin) on `--chromosomes`, excluding blacklisted bins. +1. The prediction bigwig and the binary gold standard bigwig are binned at `--bin_size` (max per bin) on the single held-out chromosome given by `--chromosomes`, excluding blacklisted bins. 2. A precision-recall curve is computed from the binned prediction scores against the binned gold standard, giving precision, recall, F1 and log2(precision / random precision) for every threshold. 3. The curve is re-binned on a 0.01 grid of Precision, Recall and F1 values so that each metric value maps to the threshold that achieves it. @@ -23,12 +23,12 @@ A tab-separated file with one row per cell type: | `Prediction` | Path to the prediction bigwig for this cell type (from `maxatac predict`, quantitative or binary) | | `Binding_File` | Path to the binary gold standard bigwig for this cell type (1 = TF bound, 0 = unbound) | -Additional columns (e.g. `Cell_Line`, `TF`) are ignored. Use validation cell types / chromosomes that were not used to train the model. +Additional columns (e.g. `Cell_Line`, `TF`) are ignored. Use validation cell types and a chromosome that were not used to train the model. ## Example ```bash -maxatac threshold --prefix CTCF --meta_file CTCF_threshold_meta.tsv --chromosomes chr2 chr19 --bin_size 200 --output ./threshold +maxatac threshold --prefix CTCF --meta_file CTCF_threshold_meta.tsv --chromosomes chr2 --bin_size 200 --output ./threshold ``` ## Outputs @@ -53,7 +53,7 @@ The meta file described above. ### `--chromosomes` -The chromosomes used to calibrate the thresholds. Default: `chr2 chr19` (the default validation chromosomes). +The single held-out chromosome used to calibrate the thresholds. Exactly one chromosome must be given; `threshold` exits with an error otherwise. Default: `chr2`. ### `--bin_size` diff --git a/maxatac/analyses/normalize.py b/maxatac/analyses/normalize.py index d164c3d..b698406 100644 --- a/maxatac/analyses/normalize.py +++ b/maxatac/analyses/normalize.py @@ -7,7 +7,7 @@ from maxatac.utilities.system_tools import get_dir, Mute from maxatac.utilities.genome_tools import build_chrom_sizes_dict, chromosome_blacklist_mask from maxatac.utilities.normalization_tools import minmax_normalize_array, zscore_normalize_array, get_genomic_stats, \ - arcsinh_normalize_array, log2_normalize_array, log1p_normalize_array, sqrt_normalize_array, three_fourth_normalize_array, \ + arcsinh_normalize_array, log1p_normalize_array, sqrt_normalize_array, three_fourth_normalize_array, \ three_eighths_normalize_array @@ -99,9 +99,6 @@ def run_normalization(args): elif args.method == "arcsinh": normalized_signal = arcsinh_normalize_array(chr_vals) - elif args.method == "log2": - normalized_signal = log2_normalize_array(chr_vals) - elif args.method == "log1p": normalized_signal = log1p_normalize_array(chr_vals) diff --git a/maxatac/analyses/predict.py b/maxatac/analyses/predict.py index f7e3345..5b7196d 100644 --- a/maxatac/analyses/predict.py +++ b/maxatac/analyses/predict.py @@ -51,7 +51,15 @@ def run_prediction(args): # If the user provides the TF name, if args.TF: - args.model = glob.glob(os.path.join(args.DATA_PATH, "models", args.TF, args.TF + "*.h5"))[0] + model_files = glob.glob(os.path.join(args.DATA_PATH, "models", args.TF, args.TF + "*.h5")) + + if not model_files: + raise FileNotFoundError( + f"No model (*.h5) found for {args.TF} in {os.path.join(args.DATA_PATH, 'models', args.TF)}. " + "Download the models with `maxatac data`, or pass a model with --model." + ) + + args.model = model_files[0] # An explicitly provided --cutoff_file wins; only fall back to the bundled table. if not args.cutoff_file: diff --git a/maxatac/analyses/threshold.py b/maxatac/analyses/threshold.py index 60b0516..8d5ae39 100644 --- a/maxatac/analyses/threshold.py +++ b/maxatac/analyses/threshold.py @@ -2,7 +2,7 @@ import pandas as pd import os import multiprocessing -from multiprocessing import Pool, Manager +from multiprocessing import Pool import time from maxatac.utilities.genome_tools import build_chrom_sizes_dict, get_bigwig_stats from maxatac.utilities.system_tools import get_dir @@ -15,24 +15,23 @@ def extract_pred_gs_bw(bigwig_file, training_data_dict, chrom_name, chrom_length, bin_count): + """ + Bin one cell type's prediction bigwig and its binary gold standard on one chromosome. + + :return: (predictions, gold_standard, tot_gs_bins) with predictions and gold_standard + both of length bin_count and aligned bin-for-bin. + """ start = time.time() - bw_name = bigwig_file.split("/")[-1] - chrom_vals = get_bigwig_stats(bigwig_file, chrom_name, chrom_length, bin_count) - print(training_data_dict[bigwig_file]) - - - predictions = np.empty(1, dtype=np.float64) - gold_standard = np.empty(1, dtype=np.float64) - goldstandard_array = import_GoldStandard_array(training_data_dict[bigwig_file], chrom_name, chrom_length, bin_count) - - tot_gs_bins = len(np.argwhere(goldstandard_array == True)) - - predictions = np.concatenate([predictions, chrom_vals]) - gold_standard = np.concatenate([gold_standard, goldstandard_array]) - - end = time.time() - print('total time (s)= ' + str(end-start), "____________", bw_name) - + bw_name = os.path.basename(bigwig_file) + + predictions = get_bigwig_stats(bigwig_file, chrom_name, chrom_length, bin_count) + gold_standard = import_GoldStandard_array(training_data_dict[bigwig_file], chrom_name, chrom_length, bin_count) + + tot_gs_bins = int(np.count_nonzero(gold_standard)) + + logging.info(f"Binned {bw_name} vs {os.path.basename(training_data_dict[bigwig_file])} " + f"on {chrom_name} in {time.time() - start:.1f} s") + return predictions, gold_standard, tot_gs_bins def run_thresholding(args): @@ -40,46 +39,44 @@ def run_thresholding(args): :param args: :return: """ + # Calibration is done on exactly one held-out chromosome: the per-cell-type arrays, + # the blacklist mask and the random-precision denominator all refer to that chromosome. + if len(args.chromosomes) != 1: + raise ValueError("maxatac threshold calibrates on exactly one chromosome; " + f"got --chromosomes {' '.join(args.chromosomes)}") + # Make the output directory output_dir = get_dir(args.output_dir) chromosome_sizes_dictionary = build_chrom_sizes_dict(args.chromosomes, args.chrom_sizes) + (chrom_name, chrom_length), = chromosome_sizes_dictionary.items() meta_DF = pd.read_table(args.meta_file) training_data_dict = pd.Series(meta_DF["Binding_File"].values,index=meta_DF["Prediction"]).to_dict() - # Loop through the chromosomes and average the values across files - OUT=[] - for chrom_name, chrom_length in chromosome_sizes_dictionary.items(): - bin_count = int(int(chrom_length) / int(args.bin_size)) # need to floor the number - - blacklist_mask = import_blacklist_mask(args.blacklist_bw, chrom_name, chrom_length, bin_count) + bin_count = int(int(chrom_length) / int(args.bin_size)) # need to floor the number + + blacklist_mask = import_blacklist_mask(args.blacklist_bw, chrom_name, chrom_length, bin_count) - lst_of_bws=list(training_data_dict.keys()) - - pool = Pool(int(multiprocessing.cpu_count())) + lst_of_bws = list(training_data_dict.keys()) + + # Bin every cell type's prediction and gold standard in parallel + with Pool(int(multiprocessing.cpu_count())) as pool: output = pool.starmap( extract_pred_gs_bw, [(bigwig, training_data_dict, chrom_name, chrom_length, bin_count) for bigwig in lst_of_bws] - ) - OUT.append(output) - + ) # Stack each cell type's Prediction/GoldStandard as a pair of columns - DF=pd.DataFrame([]) + DF = pd.DataFrame([]) total_gs_bins = [] - for i in range(len(OUT[0])): - df = pd.DataFrame([]) - - df['Prediction'] = OUT[0][i][0][:bin_count].tolist() - df['GoldStandard'] = OUT[0][i][1][:bin_count].tolist() - - gs_bins = OUT[0][i][2] + for predictions, gold_standard, gs_bins in output: + df = pd.DataFrame({'Prediction': predictions, 'GoldStandard': gold_standard}) DF = pd.concat([DF, df], axis=1, ignore_index=True) total_gs_bins.append(gs_bins) - num_cell_types = len(OUT[0]) + num_cell_types = len(output) # Create a bedtools object that is a windowed genome BED_df_bedtool = pybedtools.BedTool().window_maker(g=args.chrom_sizes, w=args.bin_size) @@ -98,8 +95,8 @@ def run_thresholding(args): # Rename the columns df.columns = ["chr", "start", "stop"] - # Find the number of non-blacklisted bins in chr of interest (log2FC denominator) - rand_bins = df.query('chr == @args.chromosomes').shape[0] + # Find the number of non-blacklisted bins in the chromosome of interest (log2FC denominator) + rand_bins = df.query('chr == @chrom_name').shape[0] logging.info("Building per-cell-type calibration curves") diff --git a/maxatac/analyses/train.py b/maxatac/analyses/train.py index 8c4891b..49556f1 100644 --- a/maxatac/analyses/train.py +++ b/maxatac/analyses/train.py @@ -1,8 +1,7 @@ import logging -import sys import timeit -from tensorflow.python.keras.utils.data_utils import OrderedEnqueuer +from tensorflow.keras.utils import OrderedEnqueuer from maxatac.utilities.constants import TRAIN_MONITOR, INPUT_LENGTH from maxatac.utilities.system_tools import Mute @@ -246,6 +245,4 @@ def run_training(args): mins, secs = divmod(totalTime, 60) hours, mins = divmod(mins, 60) - logging.info("Total training time: %d:%d:%d.\n" % (hours, mins, secs)) - - sys.exit() \ No newline at end of file + logging.info("Total training time: %d:%d:%d.\n" % (hours, mins, secs)) \ No newline at end of file diff --git a/maxatac/architectures/dcnn.py b/maxatac/architectures/dcnn.py index 8b234dc..cea697c 100644 --- a/maxatac/architectures/dcnn.py +++ b/maxatac/architectures/dcnn.py @@ -43,9 +43,22 @@ def pearson(y_true, y_pred): return score def spearman(y_true, y_pred): + """ + Spearman correlation over all values in the batch, as a scalar metric. scipy's spearmanr + on 2-D inputs returns a (correlation matrix, p-value matrix) pair, so flatten first. + """ from scipy.stats import spearmanr - - return ( tf.py_function(spearmanr, [tf.cast(y_pred, tf.float32), tf.cast(y_true, tf.float32)], Tout = tf.float32) ) + import numpy as np + + def _spearman(a, b): + rho = spearmanr(a.numpy().ravel(), b.numpy().ravel())[0] + # A constant batch has no rank correlation; report 0 rather than NaN so one + # degenerate batch does not poison the epoch mean. + return np.float32(0.0 if np.isnan(rho) else rho) + + score = tf.py_function(_spearman, [tf.cast(y_true, tf.float32), tf.cast(y_pred, tf.float32)], Tout=tf.float32) + score.set_shape(()) + return score def dice_coef( y_true, @@ -356,9 +369,8 @@ def get_dilated_cnn( beta_2=adam_beta_2, weight_decay=adam_decay ), - run_eagerly=True, # TODO: for debugging loss fn remove loss=loss_function, - metrics=[loss_function, coeff_determination, pearson, spearman] #mse + metrics=[coeff_determination, pearson, spearman] # tf.keras.metrics.RootMeanSquaredError(), tf.keras.metrics.Precision(), tf.keras.metrics.Recall(), # Can not use Precision and Recall metrics with quant models and a softplus activation since values will # go greater than 1, will kick back an error diff --git a/maxatac/utilities/benchmarking_tools.py b/maxatac/utilities/benchmarking_tools.py index 54866ac..3e2f4b1 100644 --- a/maxatac/utilities/benchmarking_tools.py +++ b/maxatac/utilities/benchmarking_tools.py @@ -16,15 +16,24 @@ def Precision_for_Recall(df, percent_recall): - percent_recall = percent_recall - upper_lim_recall = df.iloc[(df['Recall'] - percent_recall).abs().argsort()[:2]].Recall.tolist()[0] - lower_lim_recall = df.iloc[(df['Recall'] - percent_recall).abs().argsort()[:2]].Recall.tolist()[1] - upper_lim_precision = df.iloc[(df['Recall'] - percent_recall).abs().argsort()[:2]].Precision.tolist()[0] - lower_lim_precision = df.iloc[(df['Recall'] - percent_recall).abs().argsort()[:2]].Precision.tolist()[1] - val = (upper_lim_precision * abs(percent_recall - upper_lim_recall) + lower_lim_precision * abs( - percent_recall - lower_lim_recall)) / 2 - sp_precision = lower_lim_precision + val - return sp_precision + """ + Precision at a given recall, linearly interpolated between the two points of the + precision-recall curve that bracket percent_recall. Outside the curve's recall range the + nearest endpoint's precision is returned. + + :param df: DataFrame with 'Recall' and 'Precision' columns (any order) + :param percent_recall: recall at which to evaluate precision, e.g. 0.1 + """ + curve = df[['Recall', 'Precision']].dropna().sort_values('Recall') + recall = curve['Recall'].to_numpy() + precision = curve['Precision'].to_numpy() + + # Collapse duplicate recall values (a PR curve is a step function) to their max precision + # so np.interp sees strictly increasing x. + unique_recall, first_idx = np.unique(recall, return_index=True) + max_precision = np.maximum.reduceat(precision, first_idx) + + return float(np.interp(percent_recall, unique_recall, max_precision)) def calculate_sse(vector1, vector2): """ @@ -282,16 +291,18 @@ def __plot__(self): x = plot_df.y_obs y = plot_df.y_pred - # Fit a line of best fit - (m, b), (SSE,), *_ = np.polyfit(x, y, deg=1, full=True) - # set y-intercept = 0 - b=0 + # Least-squares fit of y = m * x through the origin, and the SSE of that line + x_arr = np.asarray(x, dtype=float) + y_arr = np.asarray(y, dtype=float) + m = float(np.dot(x_arr, y_arr) / np.dot(x_arr, x_arr)) + b = 0 + SSE = float(np.sum((y_arr - m * x_arr) ** 2)) from matplotlib.ticker import MaxNLocator import matplotlib.ticker as ticker # Generate values for the line of best fit xseq = np.linspace(min(x) - 1, max(x) + 1, num=100) - ax.plot(xseq, m * xseq + b, color='r', lw=2.5, label=f'Best Fit: y = {m:.2f}x + {b:.2f}\nSSE = {SSE:.2f}') + ax.plot(xseq, m * xseq + b, color='r', lw=2.5, label=f'Best Fit: y = {m:.2f}x\nSSE = {SSE:.2f}') ax.yaxis.set_major_locator(MaxNLocator(integer=True)) ax.xaxis.set_major_locator(MaxNLocator(integer=True)) diff --git a/maxatac/utilities/callbacks.py b/maxatac/utilities/callbacks.py index ee8db87..7ce6723 100644 --- a/maxatac/utilities/callbacks.py +++ b/maxatac/utilities/callbacks.py @@ -1,5 +1,7 @@ from tensorflow.keras.callbacks import ModelCheckpoint, CSVLogger, TensorBoard -from .batch_logger import BatchLossLogger # import your custom logger +import os + +from .batch_logger import BatchLossLogger def get_callbacks(model_location, log_location, @@ -10,7 +12,7 @@ def get_callbacks(model_location, append_log=False, tensor_board_write_images=False, tensor_board_write_graph=True, - batch_log_location=False, # new argument + batch_log_location=False, # True: also write a per-batch loss log next to log_location ): callbacks = [ ModelCheckpoint(filepath=model_location, @@ -27,9 +29,9 @@ def get_callbacks(model_location, ] if batch_log_location: - list = log_location.split("/")[:-1] - list.append('ELK1_quant_batch_log.csv') - batch_log_location = "/".join(list) + # Name the batch log after the run's epoch log, e.g. .csv -> _batch.csv + stem, ext = os.path.splitext(log_location) + batch_log_location = stem + "_batch" + (ext or ".csv") callbacks.append(BatchLossLogger(batch_log_location)) return callbacks diff --git a/maxatac/utilities/constants.py b/maxatac/utilities/constants.py index 8b92038..9735b67 100644 --- a/maxatac/utilities/constants.py +++ b/maxatac/utilities/constants.py @@ -62,6 +62,8 @@ "chr18", "chr20", "chr21", "chr22"] DEFAULT_VALIDATE_CHRS = ["chr2", "chr19"] +# maxatac threshold calibrates on exactly one held-out chromosome +DEFAULT_THRESHOLD_CHR = "chr2" DEFAULT_TEST_CHRS = ["chr1", "chr8"] diff --git a/maxatac/utilities/genome_tools.py b/maxatac/utilities/genome_tools.py index f8533e9..3a62e95 100644 --- a/maxatac/utilities/genome_tools.py +++ b/maxatac/utilities/genome_tools.py @@ -156,48 +156,6 @@ def get_target_matrix(binding, # TODO play with this parameter of 0.5 -def get_synced_chroms(chroms, ignore_regions=None): - """ - This function will generate a nested dictionary of chromosome sizes and the regions available for training. - - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]} - } - - If ignore_regions is True, set regions to the whole chromosome length - Returns something like this - - """ - chroms_and_regions = {} - for chrom in chroms: - chrom_name, *region = chrom.replace(",", "").split(":") # region is either [] or ["start-end", ...] - chroms_and_regions[chrom_name] = None - if not ignore_regions: - try: - chroms_and_regions[chrom_name] = [int(i) for i in region[0].split("-")] - except (IndexError, ValueError): - pass - - loaded_chroms = set() - - synced_chroms = {} - for chrom_name, chrom_length in loaded_chroms: - if chrom_name not in chroms_and_regions: continue - region = chroms_and_regions[chrom_name] - if not region or \ - region[0] < 0 or \ - region[1] <= 0 or \ - region[0] >= region[1] or \ - region[1] > chrom_length: - region = [0, chrom_length] - synced_chroms[chrom_name] = { - "length": chrom_length, - "region": region - } - return synced_chroms - - class EmptyStream(): def __enter__(self): return None diff --git a/maxatac/utilities/losses.py b/maxatac/utilities/losses.py index ebd435e..2298cb2 100644 --- a/maxatac/utilities/losses.py +++ b/maxatac/utilities/losses.py @@ -1,4 +1,4 @@ -import pandas as pd +import logging from maxatac.utilities.system_tools import Mute import tensorflow as tf @@ -88,7 +88,7 @@ def __init__(self, name="pearsonr_mse", **kwargs): super().__init__(name=name) self.alpha = kwargs.get('loss_params') if not self.alpha: - print('ALPHA SET TO DEFAULT VALUE!') + logging.info('loss_params not provided, using the default alpha') self.alpha = 0.001 #best def call(self, y_true, y_pred): #multinomial part of loss function @@ -104,7 +104,7 @@ def __init__(self, name="pearsonr_poisson", **kwargs): super().__init__(name=name) self.alpha = kwargs.get('loss_params') if not self.alpha: - print('ALPHA SET TO DEFAULT VALUE!') + logging.info('loss_params not provided, using the default alpha') self.alpha = 0.1 ###TODO: SET TO 0.001 def call(self, y_true, y_pred): #multinomial part of loss function @@ -129,7 +129,6 @@ def __init__(self, name="mse", **kwargs): super().__init__(name=name) def call(self, y_true, y_pred): - print("value: ", tf.keras.losses.MSE(y_true,y_pred)) return tf.keras.losses.MSE(y_true,y_pred) class multinomialnll(tf.keras.losses.Loss): @@ -140,11 +139,11 @@ def call(self, y_true, y_pred): logits_perm = y_pred true_counts_perm = y_true - #import numpy - #np.savetxt("/Users/war9qi/Project_Data/maxATAC_sample/ELK1_quantitative_output/true_counts_perm.tsv", true_counts_perm, delimiter='\t') - #np.savetxt("/Users/war9qi/Project_Data/maxATAC_sample/ELK1_quantitative_output/logits_perm.tsv", logits_perm, delimiter='\t') - - import tensorflow_probability as tfp # optional dependency, only needed for multinomial losses + try: + import tensorflow_probability as tfp # optional dependency, only needed for multinomial losses + except ImportError as err: + raise ImportError("The multinomial losses need tensorflow-probability: " + "pip install 'maxatac[multinomial]'") from err counts_per_example = tf.reduce_sum(true_counts_perm, axis=-1) dist = tfp.distributions.Multinomial(total_count=counts_per_example, @@ -161,9 +160,8 @@ def __init__(self, name="multinomialnll_mse", **kwargs): super().__init__(name=name) self.alpha = kwargs.get('loss_params') if not self.alpha: - print('ALPHA SET TO DEFAULT VALUE!') + logging.info('loss_params not provided, using the default alpha') self.alpha = 0.0000001 - self.counter=1 def call(self, y_true, y_pred): # GOPHER implementation of loss @@ -176,7 +174,11 @@ def call(self, y_true, y_pred): true_counts_perm = y_true - import tensorflow_probability as tfp # optional dependency, only needed for multinomial losses + try: + import tensorflow_probability as tfp # optional dependency, only needed for multinomial losses + except ImportError as err: + raise ImportError("The multinomial losses need tensorflow-probability: " + "pip install 'maxatac[multinomial]'") from err counts_per_example = tf.reduce_sum(true_counts_perm, axis=-1) dist = tfp.distributions.Multinomial(total_count=counts_per_example, @@ -221,13 +223,6 @@ def call(self, y_true, y_pred): # multinomial loss multinomial_loss = multinomialnll()(y_true, logits) - ''' - np.savetxt("/Users/war9qi/Project_Data/maxATAC_sample/ELK1_quantitative_output/y_true.tsv", y_true, - delimiter='\t') - np.savetxt("/Users/war9qi/Project_Data/maxATAC_sample/ELK1_quantitative_output/y_pred.tsv", y_pred, - delimiter='\t') - ''' - MSE_loss = tf.keras.losses.MSE([K.log(1 + K.sum(y_true, axis=(-2, -1)))], [K.log(1 + K.sum(y_pred, axis=(-2, -1)))]) @@ -236,27 +231,6 @@ def call(self, y_true, y_pred): total_loss = bpnet_loss - ''' - if self.counter in range(0,40): - epoch = 1 - elif self.counter in range(40,80): - epoch = 2 - elif self.counter in range(80,120): - epoch = 3 - elif self.counter in range(120,160): - epoch = 4 - else: - epoch = 5 - - tf.print("epoch: ", epoch, "multinomialnll_GOPHER: ", total_loss, "multinomialnll_BPnet: ", bpnet_loss) - self.counter = self.counter +1 - - if self.counter == 39 or self.counter ==79 or self.counter == 119 or self.counter == 159 or self.counter==199: - - df=pd.DataFrame([[total_loss.numpy(), bpnet_loss.numpy()]], columns=['GOPHER_multinomialnll', 'BPnet_multinomialnll']) - - df.to_csv("/Users/war9qi/Project_Data/maxATAC_sample/ELK1_quantitative_output/Epoch_"+str(epoch)+"_loss_comp.tsv", sep = '\t')''' - return total_loss class multinomialnll_mse_bpnet(tf.keras.losses.Loss): @@ -264,7 +238,7 @@ def __init__(self, name="multinomialnll_mse_bpnet", **kwargs): super().__init__(name=name) self.alpha = kwargs.get('loss_params') if not self.alpha: - print('ALPHA SET TO DEFAULT VALUE!') + logging.info('loss_params not provided, using the default alpha') self.alpha = 0.0000001 def call(self, y_true, y_pred): @@ -276,11 +250,6 @@ def call(self, y_true, y_pred): # multinomial loss multinomial_loss = multinomialnll()(y_true, logits) - np.savetxt("/Users/war9qi/Project_Data/maxATAC_sample/ELK1_quantitative_output/y_true.tsv", y_true, - delimiter='\t') - np.savetxt("/Users/war9qi/Project_Data/maxATAC_sample/ELK1_quantitative_output/y_pred.tsv", y_pred, - delimiter='\t') - mse_loss = tf.keras.losses.MSE([K.log(1 + K.sum(y_true, axis=(-2, -1)))], [K.log(1 + K.sum(y_pred, axis=(-2, -1)))]) @@ -293,7 +262,7 @@ def __init__(self, name="multinomialnll_mse_reg", **kwargs): super().__init__(name=name) self.alpha = kwargs.get('loss_params') if not self.alpha: - print('ALPHA SET TO DEFAULT VALUE!') + logging.info('loss_params not provided, using the default alpha') self.alpha = 0.0000001 # self.alpha=0.001 def call(self, y_true, y_pred): @@ -347,16 +316,8 @@ def __init__(self, name="r2", **kwargs): super().__init__(name=name) def call(self, y_true, y_pred): - print(y_true) - print(y_pred) y_true = tf.cast(y_true, 'float32') y_pred = tf.cast(y_pred, 'float32') - print("y_true shape") - print(y_true.shape) - print(y_true) - print("y_pred shape") - print(y_pred.shape) - print(y_pred) shape = y_true.shape[-1] true_sum = tf.reduce_sum(y_true, axis=[0,1]) @@ -367,18 +328,14 @@ def call(self, y_true, y_pred): count = tf.reduce_sum(count, axis=[0,1]) true_mean = tf.divide(true_sum, count) - print(true_mean) true_mean2 = tf.math.square(true_mean) - print(true_mean2) total = true_sumsq - tf.multiply(count, true_mean2) - print(total) resid1 = pred_sumsq resid2 = -2*product resid3 = true_sumsq resid = resid1 + resid2 + resid3 - print(resid) r2 = tf.ones_like(shape, dtype=tf.float32) - tf.divide(resid, total) return -tf.reduce_mean(r2) @@ -406,34 +363,31 @@ def __init__(self, name="kl_divergence", **kwargs): super().__init__(name=name) def call(self, y_true, y_pred): - from sklearn.preprocessing import normalize - - # KLD call - - '''loss = tf.keras.losses.KLDivergence().call(y_true=tf.linalg.normalize(y_true, ord=1, axis=1)[0], - y_pred=tf.linalg.normalize(y_pred, ord=1, axis=1)[0])''' - + """ + KL(p || q) = sum_i p_i * (log p_i - log q_i), with p = y_true and q = y_pred each + L1-normalized along the output axis so every example is treated as a distribution + over bins. Averaged over the batch. + """ epsilon = 1e-8 - y_true = tf.where(tf.math.is_nan(y_true), epsilon * tf.ones_like(y_true), y_true) - y_pred = tf.where(tf.math.is_nan(y_pred), epsilon * tf.ones_like(y_pred), y_pred) - - y_true = tf.where(tf.math.is_inf(y_true), epsilon * tf.ones_like(y_true), y_true) - y_pred = tf.where(tf.math.is_inf(y_pred), epsilon * tf.ones_like(y_pred), y_pred) - - y_true = tf.clip_by_value(y_true, epsilon, 1.0) - y_pred = tf.clip_by_value(y_pred, epsilon, 1.0) - - y_true_normalized = tf.linalg.normalize(y_true, ord=1, axis=1)[0] - y_pred_normalized = tf.linalg.normalize(y_pred, ord=1, axis=1)[0] + y_true = tf.cast(y_true, 'float32') + y_pred = tf.cast(y_pred, 'float32') + # Replace NaN/inf and keep the inputs strictly positive before normalizing. No upper + # clip here: quantitative targets are unbounded signal, not probabilities. + y_true = tf.where(tf.math.is_finite(y_true), y_true, epsilon * tf.ones_like(y_true)) + y_pred = tf.where(tf.math.is_finite(y_pred), y_pred, epsilon * tf.ones_like(y_pred)) + y_true = tf.maximum(y_true, epsilon) + y_pred = tf.maximum(y_pred, epsilon) - log_y_pred = tf.math.log(y_pred_normalized) + p = tf.linalg.normalize(y_true, ord=1, axis=1)[0] + q = tf.linalg.normalize(y_pred, ord=1, axis=1)[0] - # Compute the KL divergence manually - loss = tf.reduce_sum(y_true_normalized * log_y_pred, axis=1) + p = tf.clip_by_value(p, epsilon, 1.0) + q = tf.clip_by_value(q, epsilon, 1.0) + kl = tf.reduce_sum(p * (tf.math.log(p) - tf.math.log(q)), axis=1) - return loss + return tf.reduce_mean(kl) class cauchy_lf(tf.keras.losses.Loss): def __init__(self, name="cauchy_lf", **kwargs): diff --git a/maxatac/utilities/normalization_tools.py b/maxatac/utilities/normalization_tools.py index 94000a8..f65aed4 100644 --- a/maxatac/utilities/normalization_tools.py +++ b/maxatac/utilities/normalization_tools.py @@ -56,7 +56,7 @@ def get_genomic_stats(bigwig_path: str, minmax_results.append([chromosome, np.min(chr_vals[blacklist_mask]), np.max(chr_vals[blacklist_mask]), - np.median(chr_vals[blacklist_mask] > 0) + np.median(chr_vals[blacklist_mask][chr_vals[blacklist_mask] > 0]) ]) # Append chrom values to an array with genome-wide values @@ -143,16 +143,6 @@ def arcsinh_normalize_array(array): """ return np.arcsinh(array) -def log2_normalize_array(array): - """ - log2() normalize the numpy array - - :param array: Input array of bigwig values - - :return: log2 normalized array - """ - return np.log2(array) + 1 - def log1p_normalize_array(array): """ log1p()normalize the numpy array diff --git a/maxatac/utilities/parser.py b/maxatac/utilities/parser.py index a14c52c..e4bcfb0 100644 --- a/maxatac/utilities/parser.py +++ b/maxatac/utilities/parser.py @@ -34,6 +34,7 @@ INPUT_LENGTH, DEFAULT_TRAIN_CHRS, DEFAULT_VALIDATE_CHRS, + DEFAULT_THRESHOLD_CHR, DEFAULT_ROUND, DEFAULT_TEST_CHRS, DEFAULT_BENCHMARKING_AGGREGATION_FUNCTION, @@ -781,11 +782,11 @@ def get_parser(): dest="method", type=str, default="min-max", - choices=["min-max", "zscore", "arcsinh", "log2", "log1p", "sqrt", + choices=["min-max", "zscore", "arcsinh", "log1p", "sqrt", "three_fourths", "three_eighths"], help="The method to use for normalization. min-max is the ATAC-seq input " "normalization used by maxATAC; the variance-stabilizing transforms " - "(arcsinh, log2, log1p, sqrt, three_fourths, three_eighths) are provided " + "(arcsinh, log1p, sqrt, three_fourths, three_eighths) are provided " "for preparing quantitative ChIP-seq target tracks. Default: min-max" ) @@ -1323,8 +1324,10 @@ def get_parser(): dest="chromosomes", type=str, nargs="+", - default=DEFAULT_VALIDATE_CHRS, - help="Chromosomes used to calibrate thresholds. Default: " + " ".join(DEFAULT_VALIDATE_CHRS) + default=[DEFAULT_THRESHOLD_CHR], + help="The single held-out chromosome used to calibrate thresholds. Exactly one " + "chromosome must be given. Default: " + + DEFAULT_THRESHOLD_CHR ) threshold_parser.add_argument("--bin_size", @@ -1433,6 +1436,11 @@ def parse_arguments(argsl, cwd_abs_path=None): if args.quant and args.loss == BINARY_LOSS: parser.error(f"--loss {BINARY_LOSS} is for binary models; choose one of {', '.join(QUANT_LOSSES)} with --quant") + if args.func == run_thresholding and len(args.chromosomes) != 1: + # parse_known_args would otherwise silently drop the extras with nargs=1 + parser.error("threshold calibrates on exactly one chromosome; got --chromosomes " + + " ".join(args.chromosomes)) + if args.func == run_benchmarking and args.quant: missing = [flag for flag, value in (("--quant_gold_standard", args.quant_gold_standard), ("--quant_gs_null", args.quant_gs_null)) if not value] diff --git a/maxatac/utilities/save_predictions_callback.py b/maxatac/utilities/save_predictions_callback.py deleted file mode 100644 index da0f98c..0000000 --- a/maxatac/utilities/save_predictions_callback.py +++ /dev/null @@ -1,43 +0,0 @@ -import numpy as np -import os -from tensorflow.keras.callbacks import Callback - -class SavePredictionsCallback(Callback): - def __init__(self, save_dir, prefix="train", save_format="npz"): - super().__init__() - self.save_dir = save_dir - self.prefix = prefix - self.save_format = save_format - os.makedirs(self.save_dir, exist_ok=True) - self.reset_storage() - - def reset_storage(self): - self.all_y_true = [] - self.all_y_pred = [] - - def on_epoch_begin(self, epoch, logs=None): - self.reset_storage() - self.epoch = epoch - - def on_train_batch_end(self, batch, logs=None): - # Ensure model has access to y_true/y_pred - x, y_true = self.model._last_train_batch - y_pred = self.model(x, training=False) - self.all_y_true.append(y_true.numpy()) - self.all_y_pred.append(y_pred.numpy()) - - def on_epoch_end(self, epoch, logs=None): - y_true_all = np.concatenate(self.all_y_true, axis=0) - y_pred_all = np.concatenate(self.all_y_pred, axis=0) - - filename = f"{self.prefix}_epoch{self.epoch:02d}.{self.save_format}" - save_path = os.path.join(self.save_dir, filename) - - if self.save_format == "npz": - np.savez(save_path, y_true=y_true_all, y_pred=y_pred_all) - elif self.save_format == "csv": - np.savetxt(save_path.replace(".csv", "_true.csv"), y_true_all, delimiter=",") - np.savetxt(save_path.replace(".csv", "_pred.csv"), y_pred_all, delimiter=",") - else: - raise ValueError("Unsupported save_format: use 'npz' or 'csv'") - diff --git a/maxatac/utilities/training_tools.py b/maxatac/utilities/training_tools.py index f6b6cb0..b49d5aa 100644 --- a/maxatac/utilities/training_tools.py +++ b/maxatac/utilities/training_tools.py @@ -78,8 +78,11 @@ def __init__(self, self.target_scale_factor = target_scale_factor self.loss = loss - # Set the random seed for the model + # Seed every RNG that training draws from: python (ROI sampling), numpy + # (shuffles / random regions) and TensorFlow (weight init, dropout) random.seed(seed) + np.random.seed(seed) + tf.random.set_seed(seed) # Import meta txt as dataframe self.meta_dataframe = pd.read_csv(self.meta_path, sep='\t', header=0, index_col=None) @@ -305,9 +308,9 @@ def get_target_matrix(binding_stream, if target_vector.shape[0] == 0: target_vector = np.zeros(INPUT_LENGTH) - except: - # TODO change length of array - target_vector = np.zeros(1024) + except (RuntimeError, KeyError, ValueError): + # pyBigWig raises RuntimeError when a chromosome is absent from the file + target_vector = np.zeros(INPUT_LENGTH) # change nan to numbers target_vector = np.nan_to_num(target_vector, 0.0) @@ -906,7 +909,12 @@ def model_selection(training_history, output_dir): def model_selection_v2(training_history, output_dir): """ - This function will take the training history and output the best model based on the dice coefficient value. + Select the best epoch for a quantitative model from the training history. + + Starting at the epoch with the minimum validation loss, pick the epoch (at or after it) + with the smallest normalized train/validation gap |val_loss - loss| / max(val_loss, loss), + so the chosen checkpoint has both low validation loss and little overfitting. + Writes best_epoch.txt with the checkpoint path and returns the 1-based epoch number. """ # Create a dataframe from the history object df = pd.DataFrame(training_history.history) diff --git a/setup.py b/setup.py index b0d80cb..216d699 100644 --- a/setup.py +++ b/setup.py @@ -79,8 +79,11 @@ def get_description(): "tests" ] ), + python_requires=">=3.9", install_requires=[ - "tensorflow", + # Keras 2 API: tf.keras.utils.OrderedEnqueuer and Adam(weight_decay=) need >=2.11, + # and both were dropped with Keras 3 in TF 2.16 + "tensorflow>=2.14,<2.16", "tensorboard", "biopython", "py2bit", @@ -88,6 +91,7 @@ def get_description(): "pydot", "matplotlib", "scikit-learn", + "scipy", "pybedtools", "pandas", "pyfiglet", @@ -98,6 +102,10 @@ def get_description(): "tqdm", "ushuffle" ], + extras_require={ + # Only the multinomialnll* losses need it + "multinomial": ["tensorflow-probability>=0.22,<0.24"], + }, zip_safe=False, scripts=["maxatac/bin/maxatac"], classifiers=[] diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py index 10f421f..2704b66 100644 --- a/tests/test_benchmark.py +++ b/tests/test_benchmark.py @@ -40,3 +40,34 @@ def test_parse_benchmark_with_alternative_prediction_arguments(): assert args.alternative_prediction.endswith("predict_signal_cell_GM12878.bigwig") assert args.prediction_combine_operation == "max" + + +def test_precision_for_recall_interpolates_between_bracketing_points(): + import pandas as pd + from maxatac.utilities.benchmarking_tools import Precision_for_Recall + + # PR curve given in sklearn order (recall descending), including the (R=0, P=1) sentinel + curve = pd.DataFrame({ + "Recall": [0.30, 0.20, 0.05, 0.0], + "Precision": [0.40, 0.60, 0.90, 1.0], + }) + + # 0.1 lies between (0.05, 0.90) and (0.20, 0.60): 0.90 + (0.60 - 0.90) * (0.05 / 0.15) + assert Precision_for_Recall(curve, 0.10) == pytest.approx(0.80) + # Exact hits return the point itself + assert Precision_for_Recall(curve, 0.20) == pytest.approx(0.60) + # Beyond the curve's max recall, hold the endpoint + assert Precision_for_Recall(curve, 0.50) == pytest.approx(0.40) + + +def test_precision_for_recall_collapses_duplicate_recall_to_max_precision(): + import pandas as pd + from maxatac.utilities.benchmarking_tools import Precision_for_Recall + + curve = pd.DataFrame({ + "Recall": [0.2, 0.1, 0.1, 0.0], + "Precision": [0.5, 0.7, 0.9, 1.0], + }) + + assert Precision_for_Recall(curve, 0.10) == pytest.approx(0.9) + assert Precision_for_Recall(curve, 0.15) == pytest.approx(0.7) diff --git a/tests/test_parser.py b/tests/test_parser.py index 0fa0680..609b5d3 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -2,1015 +2,12 @@ import os from maxatac.utilities.system_tools import get_files -from maxatac.utilities.parser import ( - get_synced_chroms, - parse_arguments -) +from maxatac.utilities.parser import parse_arguments DATA_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp")) -@pytest.mark.parametrize( - "chroms, filenames, ignore_regions, control_synced_chroms", - [ - # correct inputs without regions - ( - [], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {} - ), - ( - [], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {} - ), - ( - ["chr1"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - - # correct inputs with regions - ( - ["chr1:10-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [10, 100]}} - ), - ( - ["chr1:10-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [10, 100]}} - ), - ( - ["chr1:10-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [10, 100]}} - ), - ( - ["chr1:10-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [10, 100]}} - ), - ( - ["chr1:10-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [10, 249250621]}} - ), - ( - ["chr1:10-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [10, 249250621]}} - ), - ( - ["chr1:10-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [10, 249250621]}} - ), - ( - ["chr1:10-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [10, 249250621]}} - ), - ( - ["chr1:10-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - - # not correct inputs without regions - ( - ["chrA"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {} - ), - ( - ["chrA"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {} - ), - ( - ["chrA"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {} - ), - ( - ["chrA"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {} - ), - ( - ["chrA"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {} - ), - ( - ["chrA"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {} - ), - - # not correct inputs with regions - ( - ["chr1:"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:-100-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:-100-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:-100-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:-100-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:-100-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:-100-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:100-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:100-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:100-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:100-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:100-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:100-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-500000000"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-500000000"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-500000000"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-500000000"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-500000000"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-500000000"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-0"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-0"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-0"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-0"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-0"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-0"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - - # combination of mutiple files - ( - ["chr1"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig" - ], - None, - {} - ), - ( - ["chr1"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {} - ), - ( - ["chr2"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig" - ], - None, - {"chr2": {"length": 243199373, "region": [0, 243199373]}} - ), - ( - ["chr2"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr2": {"length": 243199373, "region": [0, 243199373]}} - ), - ( - ["chr2", "chr3:10-100"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig" - ], - None, - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [10, 100]} - } - ), - ( - ["chr2", "chr3:10-100"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [10, 100]} - } - ), - ( - ["chr2", "chr3:10-100"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig" - ], - True, - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]} - } - ), - ( - ["chr2", "chr3:10-100"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]} - } - ), - ( - ["chr1", "chr2", "chr3:10-100"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig" - ], - None, - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [10, 100]} - } - ), - ( - ["chr1", "chr2", "chr3:10-100"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [10, 100]} - } - ), - ( - ["chr1", "chr2", "chr3:10-100"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig" - ], - True, - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]} - } - ), - ( - ["chr1", "chr2", "chr3:10-100"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]} - } - ), - ( - ["chr1"], - [ - "validate_sites_cell_HCT116_tf_CTCF.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig" - ], - None, - {} - ), - ( - ["chr1"], - [ - "validate_sites_cell_HCT116_tf_CTCF.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {} - ), - ( - ["chr1"], - [ - "validate_sites_cell_HCT116_tf_CTCF.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - None - ], - None, - {} - ), - ( - ["chr1"], - [ - "validate_sites_cell_HCT116_tf_CTCF.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - None, - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {} - ) - ] -) -def test_get_synced_chroms(chroms, filenames, ignore_regions, control_synced_chroms): - locations = list(get_files(DATA_FOLDER, "|".join([f for f in filenames if f is not None])).values()) - locations += [f for f in filenames if f is None] - synced_chroms = get_synced_chroms(chroms, locations, ignore_regions) - assert synced_chroms == control_synced_chroms - - # For not direct testing of assert_and_fix_args_for_training @pytest.mark.parametrize( From f1157186487b83962b356a60ae89c23f7bfa924d Mon Sep 17 00:00:00 2001 From: XC Date: Sun, 20 Sep 2026 23:26:00 -0400 Subject: [PATCH 36/40] q-maxATAC v2 preview (improved documentation, main branch changes merged, code review issues mostly addressed, update 2) --- docs/readme/predict.md | 4 ++++ docs/readme/train.md | 2 +- maxatac/analyses/predict.py | 8 ++++++- maxatac/analyses/train.py | 6 ++++- maxatac/utilities/constants.py | 8 +++++++ maxatac/utilities/genome_tools.py | 30 ------------------------ maxatac/utilities/normalization_tools.py | 11 +++++---- maxatac/utilities/parser.py | 9 ++++--- maxatac/utilities/threshold_tools.py | 20 +++++++++++++--- maxatac/utilities/training_tools.py | 13 +++++++--- 10 files changed, 65 insertions(+), 46 deletions(-) diff --git a/docs/readme/predict.md b/docs/readme/predict.md index 64ec702..b73ea37 100644 --- a/docs/readme/predict.md +++ b/docs/readme/predict.md @@ -88,6 +88,10 @@ The windows to use for prediction. These windows must be 1,024 bp wide and have The number of regions to predict on per batch. Default: `10000`. Decrease this value if you are having memory issues. +### `--threads` + +The maximum number of chromosomes to predict in parallel. Each process loads the full model and the 2bit genome, so memory, not CPU count, usually sets the practical limit; lower this value if prediction runs out of memory. The pool is also capped by the number of chromosomes requested and the available CPUs. Default: `24` + ### `--step_size` The step size to use for building the prediction intervals. Overlapping prediction bins will be averaged together. Default: `INPUT_LENGTH/4` = 256 bp, where `INPUT_LENGTH` is the maxATAC model input size of 1,024 bp. diff --git a/docs/readme/train.md b/docs/readme/train.md index d39852e..3f53c57 100644 --- a/docs/readme/train.md +++ b/docs/readme/train.md @@ -33,7 +33,7 @@ General Steps: Every 1,024 bp training example is split into 32 bins of 32 bp. The per-bin target depends on the model type: * **`--quant` (quantitative model):** the target is the *mean* ChIP-seq signal of `Binding_File` across the 32 bp, multiplied by `--target_scale_factor`. The model uses a `softplus` output layer and a regression loss (`--loss`, default `mse`). Predictions are therefore on the same (scaled) units as the ChIP-seq targets. -* **Binary model (default):** the target is `1` if more than half of the 32 bp overlap a ChIP-seq peak in `Binding_File`, else `0`. The model uses a `sigmoid` output layer and cross-entropy loss (maxATAC v1 behaviour). +* **Binary model (default):** the target is `1` if more than half of the 32 bp overlap a ChIP-seq peak in `Binding_File` (the fraction is `BINARY_TARGET_MIN_PEAK_FRACTION = 0.5` in `maxatac/utilities/constants.py`; `Binding_File` must be a 0/1 peak track), else `0`. The model uses a `sigmoid` output layer and cross-entropy loss (maxATAC v1 behaviour). ### Model selection diff --git a/maxatac/analyses/predict.py b/maxatac/analyses/predict.py index 5b7196d..f2aefec 100644 --- a/maxatac/analyses/predict.py +++ b/maxatac/analyses/predict.py @@ -136,12 +136,18 @@ def run_prediction(args): "Chromosomes in final prediction set: \n - " + "\n -".join(chrom_list) + "\n" + f"Output directory: {output_directory} \n" + f"Batch Size: {args.batch_size} \n" + + f"Threads: {args.threads} \n" + f"Ablation type: {args.ablation_type} \n" + f"Ablation value: {args.ablation_value} \n" + f"Output filename: {outfile_name_bigwig}" ) - with Pool(int(multiprocessing.cpu_count())) as p: + # One worker per chromosome, capped by --threads: every worker loads the full model and the + # 2bit genome, so the pool is bounded by memory rather than by cores. + n_workers = max(1, min(args.threads, len(chrom_list), multiprocessing.cpu_count())) + logging.info(f"Predicting {len(chrom_list)} chromosome(s) with {n_workers} process(es) (--threads {args.threads})") + + with Pool(n_workers) as p: forward_strand_predictions = p.starmap(make_stranded_predictions, [(regions_pool, args.signal, diff --git a/maxatac/analyses/train.py b/maxatac/analyses/train.py index 49556f1..b2ee012 100644 --- a/maxatac/analyses/train.py +++ b/maxatac/analyses/train.py @@ -1,7 +1,11 @@ import logging import timeit -from tensorflow.keras.utils import OrderedEnqueuer +try: + from tensorflow.keras.utils import OrderedEnqueuer # public API on Keras 2 (TF <= 2.15, or tf_keras) +except ImportError: + # Keras 3 (TF >= 2.16) dropped the public name; TF still ships the legacy copy + from tensorflow.python.keras.utils.data_utils import OrderedEnqueuer from maxatac.utilities.constants import TRAIN_MONITOR, INPUT_LENGTH from maxatac.utilities.system_tools import Mute diff --git a/maxatac/utilities/constants.py b/maxatac/utilities/constants.py index 9735b67..7a27291 100644 --- a/maxatac/utilities/constants.py +++ b/maxatac/utilities/constants.py @@ -65,6 +65,9 @@ # maxatac threshold calibrates on exactly one held-out chromosome DEFAULT_THRESHOLD_CHR = "chr2" +# maxatac predict: upper bound on chromosomes predicted in parallel (one model + genome per process) +DEFAULT_PREDICT_THREADS = 24 + DEFAULT_TEST_CHRS = ["chr1", "chr8"] DEFAULT_LOG_LEVEL = "info" @@ -99,6 +102,11 @@ DNA_INPUT_CHANNELS = 4 DILATION_RATE = [1, 1, 2, 4, 8, 16] BP_RESOLUTION = 32 + +# Binary-model training target: a 32 bp bin is labelled bound (1) when more than this fraction +# of its bases fall inside a ChIP-seq peak in Binding_File (maxATAC v1 rule; Binding_File must be +# a 0/1 peak track for this to mean 'fraction of bases'). Quant models ignore it and use the bin mean. +BINARY_TARGET_MIN_PEAK_FRACTION = 0.5 OUTPUT_FILTERS = 1 OUTPUT_KERNEL_SIZE = 1 POOL_SIZE = 2 diff --git a/maxatac/utilities/genome_tools.py b/maxatac/utilities/genome_tools.py index 3a62e95..114711d 100644 --- a/maxatac/utilities/genome_tools.py +++ b/maxatac/utilities/genome_tools.py @@ -126,36 +126,6 @@ def get_bigwig_stats(bigwig_path, chrom_name, chrom_end, bin_count, agg_function )) -def get_target_matrix(binding, - chromosome, - start, - end, - bp_resolution): - """ - Get the values from a ChIP-seq signal file - - :param binding: ChIP-seq signal file - :param chromosome: chromosome name: chr1 - :param start: start - :param end: end - :param bp_resolution: Prediction resolution in base pairs - - :return: Returns a vector of binary values - """ - target_vector = np.array(binding.values(chromosome, start, end)).T - - target_vector = np.nan_to_num(target_vector, 0.0) - - n_bins = int(target_vector.shape[0] / bp_resolution) - - split_targets = np.array(np.split(target_vector, n_bins, axis=0)) - - bin_sums = np.sum(split_targets, axis=1) - - return np.where(bin_sums > 0.5 * bp_resolution, 1.0, 0.0) - # TODO play with this parameter of 0.5 - - class EmptyStream(): def __enter__(self): return None diff --git a/maxatac/utilities/normalization_tools.py b/maxatac/utilities/normalization_tools.py index f65aed4..d1deba8 100644 --- a/maxatac/utilities/normalization_tools.py +++ b/maxatac/utilities/normalization_tools.py @@ -52,11 +52,14 @@ def get_genomic_stats(bigwig_path: str, chrom_sizes_dict[chromosome] ) - # Append minmax results to list + # Per-chromosome stats over non-blacklisted bases; median is of the non-zero signal, + # matching the genome-wide median below, and 0 for a chromosome with no signal at all + chr_vals_masked = chr_vals[blacklist_mask] + chr_nonzero = chr_vals_masked[chr_vals_masked > 0] minmax_results.append([chromosome, - np.min(chr_vals[blacklist_mask]), - np.max(chr_vals[blacklist_mask]), - np.median(chr_vals[blacklist_mask][chr_vals[blacklist_mask] > 0]) + np.min(chr_vals_masked), + np.max(chr_vals_masked), + np.median(chr_nonzero) if chr_nonzero.size else 0.0 ]) # Append chrom values to an array with genome-wide values diff --git a/maxatac/utilities/parser.py b/maxatac/utilities/parser.py index e4bcfb0..bb238ae 100644 --- a/maxatac/utilities/parser.py +++ b/maxatac/utilities/parser.py @@ -35,6 +35,7 @@ DEFAULT_TRAIN_CHRS, DEFAULT_VALIDATE_CHRS, DEFAULT_THRESHOLD_CHR, + DEFAULT_PREDICT_THREADS, DEFAULT_ROUND, DEFAULT_TEST_CHRS, DEFAULT_BENCHMARKING_AGGREGATION_FUNCTION, @@ -427,12 +428,14 @@ def get_parser(): help="Skip calling peaks on prediction tracks" ) - # TODO: inherited from upstream main but unused; run_prediction sizes its Pool with multiprocessing.cpu_count() predict_parser.add_argument("--threads", dest="threads", type=int, - default=24, - help="Number of processes to run prediction in parallel. Default: 24." + default=DEFAULT_PREDICT_THREADS, + help="Maximum number of chromosomes to predict in parallel. Each process loads " + "the full model and genome, so lower this if you run out of memory. " + "Capped by the number of chromosomes and available CPUs. Default: " + + str(DEFAULT_PREDICT_THREADS) ) ############################################# diff --git a/maxatac/utilities/threshold_tools.py b/maxatac/utilities/threshold_tools.py index d37baed..0b20a10 100644 --- a/maxatac/utilities/threshold_tools.py +++ b/maxatac/utilities/threshold_tools.py @@ -5,6 +5,20 @@ from sklearn.metrics import precision_recall_curve +def f1_from_precision_recall(precision, recall): + """ + F1 = 2PR / (P + R), defined as 0 where P = R = 0 (e.g. a cell type with no reachable bins) + instead of NaN, so a single degenerate row cannot propagate through the binning, the + cross-cell-type medians, or the max-F1 lookups. + """ + precision = np.asarray(precision, dtype=float) + recall = np.asarray(recall, dtype=float) + denominator = precision + recall + + return np.divide(2 * precision * recall, denominator, + out=np.zeros_like(denominator), where=denominator > 0) + + def import_blacklist_mask(bigwig_path, chromosome, chromosome_length, bin_count): """ Import the chromosome signal from a blacklist bigwig file and convert to a numpy array to use to mask out @@ -71,7 +85,7 @@ def compute_calibration_curve(goldstandard, prediction, gs_bins=None, rand_bins= random_precision = gs_bins / rand_bins curve_df['log2FC'] = np.log2(curve_df['Precision'] / random_precision) - curve_df['F1'] = 2 * (curve_df['Precision'] * curve_df['Recall']) / (curve_df['Precision'] + curve_df['Recall']) + curve_df['F1'] = f1_from_precision_recall(curve_df['Precision'], curve_df['Recall']) return curve_df @@ -114,7 +128,7 @@ def extend_bins_to_full_grid(binned_df, full_bins=None): extended['Metric'] = extended['Metric'].ffill().bfill() # Recompute F1 from interpolated P/R for internal consistency - extended['F1'] = 2 * extended['Precision'] * extended['Recall'] / (extended['Precision'] + extended['Recall']) + extended['F1'] = f1_from_precision_recall(extended['Precision'], extended['Recall']) return extended[['Metric', 'Bin', 'Precision', 'Recall', 'Threshold', 'F1']] @@ -141,7 +155,7 @@ def recompute_f1(median_table): consistent (medians taken per column need not satisfy F1 = 2PR/(P+R)). """ out = median_table.copy() - out['F1'] = 2 * out['Precision'] * out['Recall'] / (out['Precision'] + out['Recall']) + out['F1'] = f1_from_precision_recall(out['Precision'], out['Recall']) return out diff --git a/maxatac/utilities/training_tools.py b/maxatac/utilities/training_tools.py index b49d5aa..9dba423 100644 --- a/maxatac/utilities/training_tools.py +++ b/maxatac/utilities/training_tools.py @@ -13,7 +13,7 @@ from maxatac.architectures.dcnn import get_dilated_cnn from maxatac.utilities.constants import BP_RESOLUTION, BATCH_SIZE, CHR_POOL_SIZE, INPUT_LENGTH, INPUT_CHANNELS, \ - BP_ORDER, TRAIN_SCALE_SIGNAL + BP_ORDER, TRAIN_SCALE_SIGNAL, BINARY_TARGET_MIN_PEAK_FRACTION from maxatac.utilities.genome_tools import load_bigwig, load_2bit, get_one_hot_encoded, build_chrom_sizes_dict from maxatac.utilities.system_tools import get_dir, remove_tags, replace_extension @@ -299,6 +299,13 @@ def get_target_matrix(binding_stream, quant, bp_resolution, target_scale_factor): + """ + Build the per-bin training target for one 1,024 bp window from the Binding_File bigwig. + + quant=True: mean signal per bp_resolution bin, times target_scale_factor. + quant=False: 1.0 where more than BINARY_TARGET_MIN_PEAK_FRACTION of the bin's bases are + inside a peak (Binding_File is a 0/1 peak track), else 0.0 (maxATAC v1 rule). + """ # Some bigwig files do not have signal for some chromosomes because they do not have peaks # in those regions # Our workaround for issue#42 is to provide a zero matrix for that position @@ -330,9 +337,9 @@ def get_target_matrix(binding_stream, bin_vector = bin_vector * target_scale_factor else: - # TODO we might want to test what happens if we change the + # Number of peak bases per bin; bound if more than the configured fraction of the bin bin_sums = np.sum(split_targets, axis=1) - bin_vector = np.where(bin_sums > 0.5 * bp_resolution, 1.0, 0.0) + bin_vector = np.where(bin_sums > BINARY_TARGET_MIN_PEAK_FRACTION * bp_resolution, 1.0, 0.0) return bin_vector From eab36dcd7604444fb41dfb438ee2cd2557052ce2 Mon Sep 17 00:00:00 2001 From: XC Date: Mon, 28 Sep 2026 15:29:43 -0400 Subject: [PATCH 37/40] q-maxATAC v2 preview (improved documentation, main branch changes merged, code review issues mostly addressed, update 2, add unique peak % recovered) --- docs/readme/peaks.md | 2 +- docs/readme/predict.md | 2 +- docs/readme/threshold.md | 9 +- maxatac/analyses/peaks.py | 2 +- maxatac/analyses/threshold.py | 86 ++++++++++++---- maxatac/utilities/parser.py | 14 ++- maxatac/utilities/peak_tools.py | 16 ++- maxatac/utilities/plot.py | 28 +++--- maxatac/utilities/threshold_tools.py | 143 ++++++++++++++++++++++++--- 9 files changed, 240 insertions(+), 62 deletions(-) diff --git a/docs/readme/peaks.md b/docs/readme/peaks.md index 754aeba..e90be0b 100644 --- a/docs/readme/peaks.md +++ b/docs/readme/peaks.md @@ -30,7 +30,7 @@ The threshold calibration table written by `maxatac threshold`, provided in `/da ### `-cutoff_type, --cutoff_type` -The metric whose calibration grid is used to pick the threshold (`Precision`, `Recall`, or `F1`). Default: `F1`. +The metric whose calibration grid is used to pick the threshold (`Precision`, `Recall`, `F1`, or `Peak_Recall`, the fraction of unique ChIP-seq peaks recovered). `Peak_Recall` needs a table written by a `maxatac threshold` version that includes it. Default: `F1`. ### `-cutoff_value, --cutoff_value` diff --git a/docs/readme/predict.md b/docs/readme/predict.md index b73ea37..91224e2 100644 --- a/docs/readme/predict.md +++ b/docs/readme/predict.md @@ -54,7 +54,7 @@ The threshold calibration table (`_cross_celltype.tsv`) written by [`max ### `-cutoff_type, --cutoff_type` -The metric whose calibration grid is used to pick the threshold (`Precision`, `Recall`, or `F1`). Default: `F1`. +The metric whose calibration grid is used to pick the threshold (`Precision`, `Recall`, `F1`, or `Peak_Recall`, the fraction of unique ChIP-seq peaks recovered). `Peak_Recall` needs a table written by a `maxatac threshold` version that includes it. Default: `F1`. ### `-cutoff_value, --cutoff_value` diff --git a/docs/readme/threshold.md b/docs/readme/threshold.md index 120ec33..f382d64 100644 --- a/docs/readme/threshold.md +++ b/docs/readme/threshold.md @@ -10,7 +10,8 @@ For every cell type listed in the meta file: 1. The prediction bigwig and the binary gold standard bigwig are binned at `--bin_size` (max per bin) on the single held-out chromosome given by `--chromosomes`, excluding blacklisted bins. 2. A precision-recall curve is computed from the binned prediction scores against the binned gold standard, giving precision, recall, F1 and log2(precision / random precision) for every threshold. -3. The curve is re-binned on a 0.01 grid of Precision, Recall and F1 values so that each metric value maps to the threshold that achieves it. +3. Alongside the bin-level Recall, a peak-level **Peak_Recall** is computed per threshold: the fraction of unique ChIP-seq peaks with at least one non-blacklisted bin whose prediction is ≥ the threshold. Peaks are the unique intervals of the optional `ChIP_peaks` BED, or runs of consecutive gold-standard bins when it is not given. Fully blacklisted peaks are not counted. +4. The curve is re-binned on a 0.01 grid of Precision, Recall, F1 and Peak_Recall values so that each metric value maps to the threshold that achieves it. The per-metric grids are then combined across cell types by taking the median threshold per grid bin (only thresholds are aggregated, never raw signal), producing the cross-cell-type table. `predict`/`peaks` look up the lowest grid bin that still meets the requested `--cutoff_value` (or the max-F1 bin when `--cutoff_type F1` is used without a value). @@ -22,6 +23,7 @@ A tab-separated file with one row per cell type: | -------------- | ---------------------------------------------------------------------------------------------------- | | `Prediction` | Path to the prediction bigwig for this cell type (from `maxatac predict`, quantitative or binary) | | `Binding_File` | Path to the binary gold standard bigwig for this cell type (1 = TF bound, 0 = unbound) | +| `ChIP_peaks` | *(Optional)* ChIP-seq peak BED for this cell type, defining the unique peaks counted by `Peak_Recall`. If the column is missing or a cell is empty, runs of consecutive gold-standard bins are used as peaks (peaks less than one bin apart then merge) | Additional columns (e.g. `Cell_Line`, `TF`) are ignored. Use validation cell types and a chromosome that were not used to train the model. @@ -35,9 +37,10 @@ maxatac threshold --prefix CTCF --meta_file CTCF_threshold_meta.tsv --chromosome | Filename | Description | |-----------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------| -| `_cross_celltype.tsv` | The calibration table used by `predict`/`peaks`. Columns: `Metric` (`Precision`, `Recall` or `F1`), `Bin` (metric value on the 0.01 grid), `Precision`, `Recall`, `Threshold`, `F1` | +| `_cross_celltype.tsv` | The calibration table used by `predict`/`peaks`. Columns: `Metric` (`Precision`, `Recall`, `F1` or `Peak_Recall`), `Bin` (metric value on the 0.01 grid), `Precision`, `Recall`, `Threshold`, `F1`, `Peak_Recall` (fraction of unique ChIP-seq peaks recovered at that threshold) | | `.tsv` | The same table for each individual cell type in the meta file | -| `*_validationPerformance_vs_thresholdCalibration.png` | Precision, log2FC, recall and F1 vs. threshold for every cell type, with the cross-cell-type median in black | +| `_peak_recovery.tsv` | Per cell type: peak source, number of unique peaks, and `Peak_Recall` at that cell type's own max-F1 threshold and at the cross-cell-type max-F1 threshold | +| `*_validationPerformance_vs_thresholdCalibration.png` | Precision, recall, F1 and fraction of unique peaks recovered vs. threshold for every cell type, with the cross-cell-type median in black | ## Required Arguments diff --git a/maxatac/analyses/peaks.py b/maxatac/analyses/peaks.py index 4a7bff0..f02eff7 100644 --- a/maxatac/analyses/peaks.py +++ b/maxatac/analyses/peaks.py @@ -16,7 +16,7 @@ def run_call_peaks(args): chromosomes: The list of chromosomes to call peaks for BIN_SIZE: The size of the bin to use for peak calling prefix: The prefix for the output filename - cutoff_type: Choose between Precision, Recall, and F1 to choose your cutoffs + cutoff_type: Choose between Precision, Recall, F1, and Peak_Recall to choose your cutoffs cutoff_value: The value associated to cutoff type, i.e. Precision 0.75 cutoff_file: Threshold calibration table written by `maxatac threshold`, i.e. /maxATAC/data/models/YOUR_TF_MODEL/YOUR_TF_MODEL_cross_celltype.tsv diff --git a/maxatac/analyses/threshold.py b/maxatac/analyses/threshold.py index 8d5ae39..245fc5a 100644 --- a/maxatac/analyses/threshold.py +++ b/maxatac/analyses/threshold.py @@ -6,7 +6,7 @@ import time from maxatac.utilities.genome_tools import build_chrom_sizes_dict, get_bigwig_stats from maxatac.utilities.system_tools import get_dir -from maxatac.utilities.threshold_tools import import_blacklist_mask, import_GoldStandard_array, calculate_AUC_per_rank, compute_calibration_curve, bin_curve_by_metric, extend_bins_to_full_grid, bin_median_table_by_f1, merge_binned_metrics, build_cross_cell_type_threshold_table +from maxatac.utilities.threshold_tools import import_blacklist_mask, import_GoldStandard_array, calculate_AUC_per_rank, compute_calibration_curve, bin_curve_by_metric, extend_bins_to_full_grid, bin_median_table_by_f1, merge_binned_metrics, build_cross_cell_type_threshold_table, import_peak_bed_bins, gold_standard_run_bins, peak_max_predictions, peak_recall_at_thresholds from maxatac.utilities.plot import plot_threshold_calibration_stats from sklearn.metrics import precision_recall_curve from sklearn import metrics @@ -14,12 +14,17 @@ import logging -def extract_pred_gs_bw(bigwig_file, training_data_dict, chrom_name, chrom_length, bin_count): +def extract_pred_gs_bw(bigwig_file, training_data_dict, chrom_name, chrom_length, bin_count, + peaks_bed=None, blacklist_mask=None): """ - Bin one cell type's prediction bigwig and its binary gold standard on one chromosome. + Bin one cell type's prediction bigwig and its binary gold standard on one chromosome, and + reduce the prediction to one max value per unique ChIP-seq peak (for Peak_Recall). - :return: (predictions, gold_standard, tot_gs_bins) with predictions and gold_standard - both of length bin_count and aligned bin-for-bin. + Peaks come from peaks_bed (unique BED intervals) when given, else from runs of consecutive + gold-standard bins. Blacklisted bins are ignored; fully blacklisted peaks are dropped. + + :return: (predictions, gold_standard, tot_gs_bins, peak_max, peak_source) with predictions + and gold_standard both of length bin_count and aligned bin-for-bin. """ start = time.time() bw_name = os.path.basename(bigwig_file) @@ -29,10 +34,19 @@ def extract_pred_gs_bw(bigwig_file, training_data_dict, chrom_name, chrom_length tot_gs_bins = int(np.count_nonzero(gold_standard)) + if peaks_bed: + peak_idx, bin_idx = import_peak_bed_bins(peaks_bed, chrom_name, chrom_length, bin_count) + peak_source = os.path.basename(peaks_bed) + else: + peak_idx, bin_idx = gold_standard_run_bins(gold_standard) + peak_source = "gold_standard_runs" + peak_max = peak_max_predictions(predictions, peak_idx, bin_idx, keep_mask=blacklist_mask) + logging.info(f"Binned {bw_name} vs {os.path.basename(training_data_dict[bigwig_file])} " - f"on {chrom_name} in {time.time() - start:.1f} s") + f"on {chrom_name} in {time.time() - start:.1f} s; " + f"{len(peak_max)} unique peaks from {peak_source}") - return predictions, gold_standard, tot_gs_bins + return predictions, gold_standard, tot_gs_bins, peak_max, peak_source def run_thresholding(args): """ @@ -55,6 +69,14 @@ def run_thresholding(args): training_data_dict = pd.Series(meta_DF["Binding_File"].values,index=meta_DF["Prediction"]).to_dict() + # Optional ChIP_peaks column (BED) defines the unique peaks for Peak_Recall; a missing + # column or empty cell falls back to runs of consecutive gold-standard bins. + if "ChIP_peaks" in meta_DF.columns: + peaks_dict = {pred: (bed if isinstance(bed, str) and bed.strip() else None) + for pred, bed in zip(meta_DF["Prediction"], meta_DF["ChIP_peaks"])} + else: + peaks_dict = {} + bin_count = int(int(chrom_length) / int(args.bin_size)) # need to floor the number blacklist_mask = import_blacklist_mask(args.blacklist_bw, chrom_name, chrom_length, bin_count) @@ -65,16 +87,21 @@ def run_thresholding(args): with Pool(int(multiprocessing.cpu_count())) as pool: output = pool.starmap( extract_pred_gs_bw, - [(bigwig, training_data_dict, chrom_name, chrom_length, bin_count) for bigwig in lst_of_bws] + [(bigwig, training_data_dict, chrom_name, chrom_length, bin_count, + peaks_dict.get(bigwig), blacklist_mask) for bigwig in lst_of_bws] ) # Stack each cell type's Prediction/GoldStandard as a pair of columns DF = pd.DataFrame([]) total_gs_bins = [] - for predictions, gold_standard, gs_bins in output: + peak_maxes = [] + peak_sources = [] + for predictions, gold_standard, gs_bins, peak_max, peak_source in output: df = pd.DataFrame({'Prediction': predictions, 'GoldStandard': gold_standard}) DF = pd.concat([DF, df], axis=1, ignore_index=True) total_gs_bins.append(gs_bins) + peak_maxes.append(peak_max) + peak_sources.append(peak_source) num_cell_types = len(output) @@ -103,7 +130,8 @@ def run_thresholding(args): raw_cell_type_curves = [] for i in range(num_cell_types): ct_curve = compute_calibration_curve( - DF[2 * i + 1][blacklist_mask], DF[2 * i][blacklist_mask], total_gs_bins[i], rand_bins + DF[2 * i + 1][blacklist_mask], DF[2 * i][blacklist_mask], total_gs_bins[i], rand_bins, + peak_max=peak_maxes[i] ) raw_cell_type_curves.append(ct_curve) @@ -115,33 +143,49 @@ def run_thresholding(args): cross_celltype_filename = os.path.join(output_dir, args.prefix + "_cross_celltype.tsv") cross_celltype_table.to_csv(cross_celltype_filename, sep="\t", header=True, index=False) + # Per-cell-type % of unique ChIP-seq peaks recovered at its own max-F1 threshold and at + # the cross-cell-type max-F1 threshold + cross_f1 = cross_celltype_table[cross_celltype_table['Metric'] == 'F1'] + cross_best_threshold = cross_f1.loc[cross_f1['F1'].idxmax(), 'Threshold'] + peak_recovery_rows = [] + for i, ct_curve in enumerate(raw_cell_type_curves): + own_best = ct_curve.loc[ct_curve['F1'].idxmax()] + peak_recovery_rows.append({ + 'Prediction': os.path.basename(lst_of_bws[i]), + 'Peak_Source': peak_sources[i], + 'N_Peaks': len(peak_maxes[i]), + 'MaxF1_Threshold': own_best['Threshold'], + 'MaxF1': own_best['F1'], + 'Peak_Recall_at_MaxF1': own_best['Peak_Recall'], + 'CrossCellType_MaxF1_Threshold': cross_best_threshold, + 'Peak_Recall_at_CrossCellType_MaxF1': peak_recall_at_thresholds(peak_maxes[i], [cross_best_threshold])[0], + }) + pd.DataFrame(peak_recovery_rows).to_csv(os.path.join(output_dir, args.prefix + "_peak_recovery.tsv"), + sep="\t", header=True, index=False) + logging.info("Plotting the validation statistics v. threshold values") # Plot each cell type's own binned+extended curve rather than resampling it at the # median thresholds, so one cell type's gaps cannot distort another's line. cell_type_curves = [] for i, ct_curve in enumerate(raw_cell_type_curves): - random_precision_i = total_gs_bins[i] / rand_bins precision_curve = extend_bins_to_full_grid(bin_curve_by_metric(ct_curve, 'Precision')) recall_curve = extend_bins_to_full_grid(bin_curve_by_metric(ct_curve, 'Recall')) + peak_recall_curve = extend_bins_to_full_grid(bin_curve_by_metric(ct_curve, 'Peak_Recall')) # Save this cell type's own binned threshold table (same schema as cross_celltype.tsv) - sample_table = merge_binned_metrics([precision_curve, recall_curve, bin_median_table_by_f1([recall_curve])]) + sample_table = merge_binned_metrics([precision_curve, recall_curve, bin_median_table_by_f1([recall_curve]), + peak_recall_curve]) sample_name = os.path.splitext(os.path.basename(lst_of_bws[i]))[0] sample_table.to_csv(os.path.join(output_dir, sample_name + ".tsv"), sep="\t", header=True, index=False) # F1 is not monotonic in Threshold, so re-binning it by value zigzags; the # Recall-binned curve already carries a Threshold-monotonic F1 column, reuse it. - curves_by_metric = {'Precision': precision_curve, 'Recall': recall_curve, 'F1': recall_curve.copy()} - for curve in curves_by_metric.values(): - curve['log2FC'] = np.log2(curve['Precision'] / random_precision_i) + curves_by_metric = {'Precision': precision_curve, 'Recall': recall_curve, 'F1': recall_curve.copy(), + 'Peak_Recall': peak_recall_curve} cell_type_curves.append({'name': os.path.basename(lst_of_bws[i]), 'curves': curves_by_metric}) - # log2FC is needed for the plot only; not written to cross_celltype.tsv - random_precision = np.mean(total_gs_bins) / rand_bins - median_curve_for_plot = cross_celltype_table.copy() - median_curve_for_plot['log2FC'] = np.log2(median_curve_for_plot['Precision'] / random_precision) - - plot_threshold_calibration_stats(median_curve_for_plot, cell_type_curves, cross_celltype_filename, args.prefix) + plot_threshold_calibration_stats(cross_celltype_table, cell_type_curves, cross_celltype_filename, args.prefix, + chrom_name=chrom_name) diff --git a/maxatac/utilities/parser.py b/maxatac/utilities/parser.py index bb238ae..d881c30 100644 --- a/maxatac/utilities/parser.py +++ b/maxatac/utilities/parser.py @@ -398,9 +398,10 @@ def get_parser(): dest="cutoff_type", default="F1", type=str, - choices=["Precision", "Recall", "F1"], + choices=["Precision", "Recall", "F1", "Peak_Recall"], help="Metric whose calibration grid is used to pick the peak calling \ - threshold. Default: F1" + threshold. Peak_Recall is the fraction of unique ChIP-seq peaks \ + recovered. Default: F1" ) predict_parser.add_argument("-cv", "-cutoff_value", "--cutoff_value", @@ -1057,9 +1058,10 @@ def get_parser(): dest="cutoff_type", default="F1", type=str, - choices=["Precision", "Recall", "F1"], + choices=["Precision", "Recall", "F1", "Peak_Recall"], help="Metric whose calibration grid is used to pick the peak calling \ - threshold. Default: F1" + threshold. Peak_Recall is the fraction of unique ChIP-seq peaks \ + recovered. Default: F1" ) peaks_parser.add_argument("-cutoff_value", "--cutoff_value", @@ -1383,7 +1385,9 @@ def get_parser(): required=True, help="Tab-separated meta file with one row per cell type and columns 'Prediction' " "(prediction bigWig, quantitative or binary) and 'Binding_File' (binary gold " - "standard bigWig)." + "standard bigWig). Optional column 'ChIP_peaks' (ChIP-seq peak BED) defines the " + "unique peaks for the Peak_Recall (% of peaks recovered) metric; without it, " + "runs of consecutive gold-standard bins are used." ) return general_parser diff --git a/maxatac/utilities/peak_tools.py b/maxatac/utilities/peak_tools.py index 74ca786..0d8a31c 100644 --- a/maxatac/utilities/peak_tools.py +++ b/maxatac/utilities/peak_tools.py @@ -61,7 +61,7 @@ def call_peaks_per_chromosome(bigwig_path, chrom_name, threshold, bin_size=200): return pd.DataFrame(BIN_list, columns=["chr", "start", "end", "score"]) -CUTOFF_TYPES = ("Precision", "Recall", "F1") +CUTOFF_TYPES = ("Precision", "Recall", "F1", "Peak_Recall") def get_threshold(cutoff_file, cutoff_type, cutoff_val): @@ -70,9 +70,10 @@ def get_threshold(cutoff_file, cutoff_type, cutoff_val): Args: cutoff_file (str): Threshold calibration table written by `maxatac threshold` (`_cross_celltype.tsv` or a per-sample `.tsv`), with columns - Metric/Bin/Precision/Recall/Threshold/F1. + Metric/Bin/Precision/Recall/Threshold/F1 (+ Peak_Recall). cutoff_type (str): Which metric's bin grid to look the threshold up on. - One of Precision, Recall, F1. + One of Precision, Recall, F1, Peak_Recall (fraction of unique ChIP-seq peaks + recovered). cutoff_val (float): Target value on that metric's grid. Optional for F1, where omitting it selects the threshold with the highest F1. @@ -94,7 +95,9 @@ def get_threshold(cutoff_file, cutoff_type, cutoff_val): rows = df[df["Metric"] == cutoff_type] if rows.empty: - raise ValueError(f"{cutoff_file} has no {cutoff_type} rows to calibrate a threshold against.") + hint = (" Tables written before Peak_Recall was added lack these rows; regenerate it with " + "`maxatac threshold`.") if cutoff_type == "Peak_Recall" else "" + raise ValueError(f"{cutoff_file} has no {cutoff_type} rows to calibrate a threshold against.{hint}") if cutoff_type == "F1" and cutoff_val is None: selected = rows.loc[rows["F1"].idxmax()] @@ -114,9 +117,12 @@ def get_threshold(cutoff_file, cutoff_type, cutoff_val): selected = reachable.iloc[0] + achieved_peak_recall = (f"\n Achieved Peak_Recall: {selected['Peak_Recall']}" + if "Peak_Recall" in selected.index else "") logging.info(f"Threshold calibrated on {cutoff_type} bin {selected['Bin']}: {selected['Threshold']}" + f"\n Achieved Precision: {selected['Precision']}" + f"\n Achieved Recall: {selected['Recall']}" + - f"\n Achieved F1: {selected['F1']}") + f"\n Achieved F1: {selected['F1']}" + + achieved_peak_recall) return float(selected["Threshold"]) diff --git a/maxatac/utilities/plot.py b/maxatac/utilities/plot.py index bbe67b9..f6220ae 100644 --- a/maxatac/utilities/plot.py +++ b/maxatac/utilities/plot.py @@ -259,26 +259,32 @@ def export_prc(precision, recall, file_location, title="Precision Recall Curve", def plot_threshold_calibration_stats(median_curve, cell_type_curves, file_location, prefix, - suffix="_validationPerformance_vs_thresholdCalibration", ext=".png", style="ggplot"): + suffix="_validationPerformance_vs_thresholdCalibration", ext=".png", style="ggplot", + chrom_name="chr2"): """ - Multi-panel plot of Precision, log2(FC), Recall, and F1 vs. Threshold. Each cell type - is drawn in color from its own per-metric curve; the median-across-cell-type curve - is drawn in black on the Precision/Recall/F1 panels. + Multi-panel plot of Precision, Recall, F1 and, when present, Peak_Recall (% of unique + ChIP-seq peaks recovered) vs. Threshold. Each cell type is drawn in color from its own + per-metric curve; the median-across-cell-type curve is drawn in black on every panel. - median_curve: DataFrame with Metric/Precision/Recall/Threshold/log2FC/F1 columns. + median_curve: DataFrame with Metric/Precision/Recall/Threshold/F1 (+ Peak_Recall) columns. cell_type_curves: list of {'name': str, 'curves': {'Precision': DataFrame, - 'Recall': DataFrame, 'F1': DataFrame}}. + 'Recall': DataFrame, 'F1': DataFrame (, 'Peak_Recall': DataFrame)}}. """ plt.style.use(style) + has_peak_recall = (median_curve["Metric"] == "Peak_Recall").any() and \ + all("Peak_Recall" in ct["curves"] for ct in cell_type_curves) fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(15, 12)) # (axis, column, label, median_curve Metric for the black line; None = no black line) panels = [ (axs[0, 0], "Precision", "Precision", "Precision"), - (axs[0, 1], "log2FC", "log2(FC)", None), - (axs[1, 0], "Recall", "Recall", "Recall"), - (axs[1, 1], "F1", "F1 Score", "F1"), + (axs[0, 1], "Recall", "Recall", "Recall"), + (axs[1, 0], "F1", "F1 Score", "F1"), ] + if has_peak_recall: + panels.append((axs[1, 1], "Peak_Recall", "Fraction of Unique Peaks Recovered", "Peak_Recall")) + else: + axs[1, 1].axis("off") n_curves = max(len(cell_type_curves), 1) colors = plt.cm.rainbow(np.linspace(0, 1, n_curves)) @@ -298,7 +304,7 @@ def plot_threshold_calibration_stats(median_curve, cell_type_curves, file_locati if metric_filter is not None: panel_median = median_curve[median_curve["Metric"] == metric_filter].sort_values("Threshold") ax.plot(panel_median["Threshold"], panel_median[col], c="black", lw=3, label="Median") - ax.set_title(f"chr2 Validation {label} v. Thresholds", size="medium") + ax.set_title(f"{chrom_name} Validation {label} v. Thresholds", size="medium") ax.set_xlabel("Threshold", size="medium") ax.set_xlim([0.0, max_threshold]) ax.set_ylabel(f"Validation {label}", size="medium") @@ -307,7 +313,7 @@ def plot_threshold_calibration_stats(median_curve, cell_type_curves, file_locati handles, labels = axs[0, 0].get_legend_handles_labels() fig.legend(handles, labels, loc="lower center", ncol=min(len(labels), 6), fontsize=9, bbox_to_anchor=(0.5, -0.02)) - fig.suptitle(prefix + " chr2 Validation Performance v. Threshold Calibration") + fig.suptitle(f"{prefix} {chrom_name} Validation Performance v. Threshold Calibration") fig.savefig(replace_extension(file_location, prefix + '_' + suffix + ext), bbox_inches="tight", dpi=320) diff --git a/maxatac/utilities/threshold_tools.py b/maxatac/utilities/threshold_tools.py index 0b20a10..fdbfb1e 100644 --- a/maxatac/utilities/threshold_tools.py +++ b/maxatac/utilities/threshold_tools.py @@ -19,6 +19,107 @@ def f1_from_precision_recall(precision, recall): out=np.zeros_like(denominator), where=denominator > 0) +PEAK_RECALL = 'Peak_Recall' + + +def curve_value_columns(df): + """ + Value columns carried through binning/medians: always Precision/Recall/Threshold/F1, + plus Peak_Recall when the curve was built with per-peak predictions. + """ + columns = ['Precision', 'Recall', 'Threshold', 'F1'] + if PEAK_RECALL in df.columns: + columns.append(PEAK_RECALL) + return columns + + +def _intervals_to_peak_bin_pairs(start_bins, end_bins): + """ + Expand half-open bin intervals [start, end) into flat (peak_idx, bin_idx) pairs. + Pairs rather than a label array, because overlapping peaks can share a bin. + """ + start_bins = np.asarray(start_bins, dtype=np.int64) + lengths = np.asarray(end_bins, dtype=np.int64) - start_bins + + peak_idx = np.repeat(np.arange(len(lengths)), lengths) + offsets = np.arange(lengths.sum()) - np.repeat(np.cumsum(lengths) - lengths, lengths) + bin_idx = np.repeat(start_bins, lengths) + offsets + + return peak_idx, bin_idx + + +def import_peak_bed_bins(peaks_bed, chrom_name, chrom_length, bin_count): + """ + Map the unique (chr, start, end) intervals of a ChIP-seq peak BED on chrom_name onto the + bin grid used by get_bigwig_stats (nBins=bin_count over [0, chrom_length), so each bin is + chrom_length / bin_count bp wide). Peaks falling entirely past the last bin are dropped. + + :return: (peak_idx, bin_idx) pairs, one per bin a peak touches + """ + bed = pd.read_csv(peaks_bed, sep="\t", header=None, usecols=[0, 1, 2], + names=['chr', 'start', 'end'], dtype={'chr': str}, comment='#') + # Coercing drops track/browser header lines + bed['start'] = pd.to_numeric(bed['start'], errors='coerce') + bed['end'] = pd.to_numeric(bed['end'], errors='coerce') + bed = bed.dropna() + bed = bed[bed['chr'] == chrom_name].drop_duplicates(subset=['chr', 'start', 'end']) + + start = bed['start'].to_numpy(dtype=np.int64) + end = bed['end'].to_numpy(dtype=np.int64) + + start_bins = start * bin_count // chrom_length + end_bins = np.minimum(-(-end * bin_count // chrom_length), bin_count) + + keep = end_bins > start_bins + return _intervals_to_peak_bin_pairs(start_bins[keep], end_bins[keep]) + + +def gold_standard_run_bins(gold_standard): + """ + Fallback peak definition when no ChIP-seq peak BED is given: each run of consecutive + gold-standard bins is one peak (peaks closer than one bin apart merge). + + :return: (peak_idx, bin_idx) pairs, one per gold-standard bin + """ + gs = np.asarray(gold_standard, dtype=bool).astype(np.int8) + edges = np.diff(np.concatenate(([0], gs, [0]))) + + return _intervals_to_peak_bin_pairs(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1)) + + +def peak_max_predictions(predictions, peak_idx, bin_idx, keep_mask=None): + """ + Max prediction per peak over its kept (e.g. non-blacklisted) bins. Peaks with no kept + bin are dropped, so they do not count toward the Peak_Recall denominator. + """ + predictions = np.asarray(predictions, dtype=float) + if keep_mask is not None: + keep = np.asarray(keep_mask, dtype=bool)[bin_idx] + peak_idx, bin_idx = peak_idx[keep], bin_idx[keep] + + if len(peak_idx) == 0: + return np.array([], dtype=float) + + peak_max = np.full(int(peak_idx.max()) + 1, -np.inf) + np.maximum.at(peak_max, peak_idx, predictions[bin_idx]) + + return peak_max[np.isfinite(peak_max)] + + +def peak_recall_at_thresholds(peak_max, thresholds): + """ + Fraction of peaks recovered at each threshold T: a peak counts when any of its bins has + prediction >= T (the same >= rule sklearn uses for bin-level Recall). + """ + thresholds = np.asarray(thresholds, dtype=float) + n_peaks = len(peak_max) + if n_peaks == 0: + return np.zeros_like(thresholds) + + sorted_max = np.sort(peak_max) + return (n_peaks - np.searchsorted(sorted_max, thresholds, side='left')) / n_peaks + + def import_blacklist_mask(bigwig_path, chromosome, chromosome_length, bin_count): """ Import the chromosome signal from a blacklist bigwig file and convert to a numpy array to use to mask out @@ -63,10 +164,12 @@ def calculate_AUC_per_rank(PR_CURVE_DF, threshold): return metrics.auc(y=tmp_df["Precision"], x=tmp_df["Recall"]) -def compute_calibration_curve(goldstandard, prediction, gs_bins=None, rand_bins=None): +def compute_calibration_curve(goldstandard, prediction, gs_bins=None, rand_bins=None, peak_max=None): """ Build a monotonic Precision/Recall/Threshold calibration curve (plus F1) for one - goldstandard/prediction pair. log2FC is added only when gs_bins and rand_bins are given. + goldstandard/prediction pair. log2FC is added only when gs_bins and rand_bins are given; + Peak_Recall (fraction of unique ChIP-seq peaks recovered) only when peak_max, the + per-peak max prediction from peak_max_predictions(), is given. """ precision, recall, thresholds = precision_recall_curve(goldstandard, prediction) @@ -77,6 +180,11 @@ def compute_calibration_curve(goldstandard, prediction, gs_bins=None, rand_bins= # sentinel row (P=1, R=0) with the last real threshold. threshold_col = np.append(thresholds, thresholds[-1]) curve_df = pd.DataFrame({'Precision': P, 'Recall': R, "Threshold": threshold_col}) + if peak_max is not None: + peak_recall = peak_recall_at_thresholds(peak_max, threshold_col) + # The sentinel row stands for "above every threshold" (Recall=0); match it + peak_recall[-1] = 0.0 + curve_df[PEAK_RECALL] = peak_recall # Duplicate the last row rather than forcing Threshold=1 (quant predictions can exceed 1) new_row = curve_df.tail(n=1) curve_df = pd.concat([curve_df, new_row], ignore_index=True) @@ -104,7 +212,7 @@ def bin_curve_by_metric(curve_df, metric): binned = binned.rename(columns={'_bin': 'Bin'}) binned['Metric'] = metric - return binned[['Metric', 'Bin', 'Precision', 'Recall', 'Threshold', 'F1']].reset_index(drop=True) + return binned[['Metric', 'Bin'] + curve_value_columns(binned)].reset_index(drop=True) def extend_bins_to_full_grid(binned_df, full_bins=None): @@ -120,17 +228,17 @@ def extend_bins_to_full_grid(binned_df, full_bins=None): binned_df = binned_df.drop_duplicates(subset='Bin').sort_values('Bin').reset_index(drop=True) grid = pd.DataFrame({'Bin': np.sort(np.unique(full_bins))}) + value_columns = curve_value_columns(binned_df) + extended = grid.merge(binned_df, on='Bin', how='left') # Row position equals Bin position on the evenly spaced grid, so linear is exact - extended[['Precision', 'Recall', 'Threshold', 'F1']] = extended[ - ['Precision', 'Recall', 'Threshold', 'F1'] - ].interpolate(method='linear', limit_direction='both') + extended[value_columns] = extended[value_columns].interpolate(method='linear', limit_direction='both') extended['Metric'] = extended['Metric'].ffill().bfill() # Recompute F1 from interpolated P/R for internal consistency extended['F1'] = f1_from_precision_recall(extended['Precision'], extended['Recall']) - return extended[['Metric', 'Bin', 'Precision', 'Recall', 'Threshold', 'F1']] + return extended[['Metric', 'Bin'] + value_columns] def median_bins_across_samples(binned_tables, full_bins=None): @@ -143,7 +251,7 @@ def median_bins_across_samples(binned_tables, full_bins=None): extended_tables = [extend_bins_to_full_grid(t, full_bins) for t in binned_tables] merged = pd.concat(extended_tables, ignore_index=True) - combined = merged.groupby('Bin', as_index=False)[['Precision', 'Recall', 'Threshold', 'F1']].median() + combined = merged.groupby('Bin', as_index=False)[curve_value_columns(merged)].median() combined.insert(0, 'Metric', metric) return combined.sort_values('Bin').reset_index(drop=True) @@ -172,16 +280,17 @@ def bin_median_table_by_f1(median_tables): binned = pooled.loc[pooled.groupby('Bin')['F1'].idxmax()].copy() binned['Metric'] = 'F1' - return binned[['Metric', 'Bin', 'Precision', 'Recall', 'Threshold', 'F1']].sort_values('Bin').reset_index(drop=True) + return binned[['Metric', 'Bin'] + curve_value_columns(binned)].sort_values('Bin').reset_index(drop=True) def merge_binned_metrics(median_tables): """ - Concatenate the Precision/Recall/F1 tables, ordered by Metric then Bin. No - deduplication across metrics: F1 rows legitimately coincide with Precision/Recall rows. + Concatenate the Precision/Recall/F1 (+ Peak_Recall) tables, ordered by Metric then Bin. + No deduplication across metrics: F1 rows legitimately coincide with Precision/Recall rows. """ merged = pd.concat(median_tables, ignore_index=True) - merged['Metric'] = pd.Categorical(merged['Metric'], categories=['Precision', 'Recall', 'F1'], ordered=True) + merged['Metric'] = pd.Categorical(merged['Metric'], categories=['Precision', 'Recall', 'F1', PEAK_RECALL], + ordered=True) merged = merged.sort_values(['Metric', 'Bin']).reset_index(drop=True) merged['Metric'] = merged['Metric'].astype(str) @@ -192,7 +301,8 @@ def build_cross_cell_type_threshold_table(curves): """ Given one calibration curve per cell type: bin each by Precision and Recall, take the median across cell types per bin, recompute F1, derive the F1 grid from the Recall - table, and merge the three metrics' tables. + table, and merge the metrics' tables. When every curve carries Peak_Recall, it gets its + own grid too (binned and median-aggregated exactly like Recall). """ precision_tables = [bin_curve_by_metric(curve, 'Precision') for curve in curves] recall_tables = [bin_curve_by_metric(curve, 'Recall') for curve in curves] @@ -202,7 +312,12 @@ def build_cross_cell_type_threshold_table(curves): f1_binned = bin_median_table_by_f1([recall_median]) - return merge_binned_metrics([precision_median, recall_median, f1_binned]) + tables = [precision_median, recall_median, f1_binned] + if all(PEAK_RECALL in curve.columns for curve in curves): + peak_recall_tables = [bin_curve_by_metric(curve, PEAK_RECALL) for curve in curves] + tables.append(recompute_f1(median_bins_across_samples(peak_recall_tables))) + + return merge_binned_metrics(tables) def sample_curve_at_thresholds(curve_df, threshold_values): From 2c57ebe333c304bb826f842508c1fb432f089454 Mon Sep 17 00:00:00 2001 From: XC Date: Sun, 11 Oct 2026 11:59:08 -0400 Subject: [PATCH 38/40] q-maxATAC v2 preview (improved documentation, main branch changes merged, code review issues mostly addressed, add unique peak % recovered, update 3) --- maxatac/analyses/threshold.py | 6 +++--- maxatac/analyses/variants.py | 5 +++-- maxatac/utilities/parser.py | 23 ++++++++++++----------- 3 files changed, 18 insertions(+), 16 deletions(-) diff --git a/maxatac/analyses/threshold.py b/maxatac/analyses/threshold.py index 245fc5a..73f9269 100644 --- a/maxatac/analyses/threshold.py +++ b/maxatac/analyses/threshold.py @@ -108,9 +108,9 @@ def run_thresholding(args): # Create a bedtools object that is a windowed genome BED_df_bedtool = pybedtools.BedTool().window_maker(g=args.chrom_sizes, w=args.bin_size) - # Create a blacklist object form the blacklist bed - # TODO: I do not think we need to get the blacklist bed location like this since it is a part of the args now. - blacklist_bed_location = ".".join([args.blacklist_bw.split(".")[0],'bed']) + # Create a blacklist object form the blacklist bed: --blacklist_bed if given, otherwise the .bed next to --blacklist_bw. + # splitext only strips the final extension, so dots elsewhere in the path are kept. + blacklist_bed_location = args.blacklist_bed or os.path.splitext(args.blacklist_bw)[0] + ".bed" blacklist_bedtool = pybedtools.BedTool(blacklist_bed_location) # Remove the blacklisted regions from the windowed genome object diff --git a/maxatac/analyses/variants.py b/maxatac/analyses/variants.py index e1e0a50..cea2e26 100644 --- a/maxatac/analyses/variants.py +++ b/maxatac/analyses/variants.py @@ -14,7 +14,7 @@ def run_variants(args): Args: args ([type]): input_bigwig, sequence, models, chromosomes, variant_start_pos, nucleotide, overhang, output, name """ - output_directory = get_dir(args.output) + output_directory = get_dir(args.output_dir) output_bw = os.path.join(output_directory, args.name + ".bw") output_bg = os.path.join(output_directory, args.name + ".bg") output_windows = os.path.join(output_directory, args.name + "_windows.bed") @@ -42,7 +42,8 @@ def run_variants(args): bed_df = create_prediction_regions(chromosomes=args.chromosomes, chrom_sizes=args.chrom_sizes, blacklist=args.blacklist, - step_size=args.step_size + peaks=None, + windows=None ) regions_pool = pybedtools.BedTool.from_dataframe(bed_df) diff --git a/maxatac/utilities/parser.py b/maxatac/utilities/parser.py index d881c30..79bb7aa 100644 --- a/maxatac/utilities/parser.py +++ b/maxatac/utilities/parser.py @@ -106,7 +106,8 @@ def get_parser(): type=str, default="hg38", required=False, - help="The reference genome build to use." + help="The reference genome build to use. Can be given before or after the subcommand. " + "Default: hg38" ) ############################################# @@ -201,7 +202,7 @@ def get_parser(): average_parser.add_argument("--genome", dest="genome", type=str, - default="hg38", + default=argparse.SUPPRESS, required=False, help="The reference genome build to which the input file was aligned." ) @@ -281,7 +282,7 @@ def get_parser(): predict_parser.add_argument("--genome", dest="genome", type=str, - default="hg38", + default=argparse.SUPPRESS, required=False, help="The reference genome build to which the input file was aligned." ) @@ -483,7 +484,7 @@ def get_parser(): train_parser.add_argument("--genome", dest="genome", type=str, - default="hg38", + default=argparse.SUPPRESS, required=False, help="The reference genome build to which the input file was aligned." ) @@ -747,7 +748,7 @@ def get_parser(): normalize_parser.add_argument("--genome", dest="genome", type=str, - default="hg38", + default=argparse.SUPPRESS, required=False, help="The reference genome build to use." ) @@ -949,7 +950,7 @@ def get_parser(): benchmark_parser.add_argument("--genome", dest="genome", type=str, - default="hg38", + default=argparse.SUPPRESS, required=False, help="The reference genome build to which the input file was aligned." ) @@ -1139,7 +1140,7 @@ def get_parser(): variants_parser.add_argument("--genome", dest="genome", type=str, - default="hg38", + default=argparse.SUPPRESS, required=False, help="The reference genome build to which the input file was aligned." ) @@ -1272,7 +1273,7 @@ def get_parser(): prepare_parser.add_argument("--genome", dest="genome", type=str, - default="hg38", + default=argparse.SUPPRESS, required=False, help="The reference genome build to which the input file was aligned." ) @@ -1361,7 +1362,7 @@ def get_parser(): threshold_parser.add_argument("--genome", dest="genome", type=str, - default="hg38", + default=argparse.SUPPRESS, required=False, help="The reference genome build to which the input BAM file was aligned." ) @@ -1372,11 +1373,11 @@ def get_parser(): help="The blacklisted regions to exclude in bigwig format." ) - # TODO: inherited from upstream main but unused; run_thresholding derives the BED path from --blacklist_bw threshold_parser.add_argument("--blacklist_bed", dest="blacklist_bed", type=str, - help="The blacklisted regions to exclude in bigwig format." + help="The blacklisted regions to exclude in BED format. Default: the .bed file " + "next to --blacklist_bw." ) threshold_parser.add_argument("--meta_file", From 044e22a0a07845c2922391e0b1da9367e4ff543e Mon Sep 17 00:00:00 2001 From: XC Date: Sun, 11 Oct 2026 12:14:16 -0400 Subject: [PATCH 39/40] q-maxATAC v2 preview (improved documentation, main branch changes merged, code review issues mostly addressed, add unique peak % recovered, update 4 - maxatac data) --- Dockerfile | 2 +- INSTALL.md | 16 +-- README.md | 5 +- docs/readme/data.md | 24 +++- maxatac/analyses/data.py | 196 +++++++++++++++++++++++++----- maxatac/utilities/constants.py | 7 ++ maxatac/utilities/parser.py | 20 ++- maxatac/utilities/system_tools.py | 5 +- 8 files changed, 227 insertions(+), 48 deletions(-) diff --git a/Dockerfile b/Dockerfile index 410625f..aafbe02 100644 --- a/Dockerfile +++ b/Dockerfile @@ -63,7 +63,7 @@ RUN apt-get update && \ rm -rf ./* &&\ pip install maxatac==0.0.3 &&\ mkdir -p /opt/maxatac && cd /opt/maxatac &&\ - git clone https://github.com/MiraldiLab/maxATAC_data.git && mv maxATAC_data data &&\ + git clone --depth 1 https://github.com/MiraldiLab/quant-maxATAC_data.git data &&\ cd ./data/hg38 && wget https://hgdownload.cse.ucsc.edu/goldenpath/hg38/bigZips/hg38.2bit &&\ strip /usr/local/bin/*; true diff --git a/INSTALL.md b/INSTALL.md index 652ba92..7997e6e 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -5,21 +5,23 @@ below with the PyPI package name/version once quant-maxATAC is published. The do ## Install Instructions -### 1. To install maxATAC begin by downloading the data reopository located on github: maxATAC_data +The reference data and models are installed with `maxatac data` once quant-maxATAC is installed (step 4). To install them by hand instead, follow steps 1-3. - `git clone https://github.com/MiraldiLab/maxATAC_data.git` +### 1. Download the data repository located on github: [quant-maxATAC_data](https://github.com/MiraldiLab/quant-maxATAC_data) -### 2. To ensure that the data is located in a central location copy maxATAC_data to local location: +This replaces the maxATAC v1 [maxATAC_data](https://github.com/MiraldiLab/maxATAC_data) repository, whose binary models quant-maxATAC does not use. If you have an existing `~/opt/maxatac/data`, move it out of the way first. + +### 2. Clone it into the location quant-maxATAC looks in by default: ```bash -mkdir -p /opt/maxatac/data/ -cp -r ./maxATAC_data /opt/maxatac/ +mkdir -p ~/opt/maxatac +git clone --depth 1 https://github.com/MiraldiLab/quant-maxATAC_data.git ~/opt/maxatac/data ``` -### 3. Then Download hg38.2bit file from UCSC in a location of your choice +### 3. Then download the hg38.2bit file from UCSC next to the hg38 reference files ```bash -wget https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/hg38.2bit +wget https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/hg38.2bit -O ~/opt/maxatac/data/hg38/hg38.2bit ``` ### 4. Installing maxATAC diff --git a/README.md b/README.md index db0014d..8e82d0e 100644 --- a/README.md +++ b/README.md @@ -73,10 +73,9 @@ In order to run the distributed TF models, the following files are required and * TF specific threshold calibration tables (`_cross_celltype.tsv`, generated by [`maxatac threshold`](./docs/readme/threshold.md)) * Bash scripts for preparing data -The `maxatac data` function downloads the data repository and reference data into your `~/opt/` directory under `~/opt/maxatac`. Only the hg38 reference genome has been extensively tested. +The `maxatac data` function downloads the [quant-maxATAC_data](https://github.com/MiraldiLab/quant-maxATAC_data) repository and reference data into your `~/opt/` directory under `~/opt/maxatac`. Only the hg38 reference genome has been extensively tested. - +If `~/opt/maxatac/data` already exists, for example from a maxATAC v1 install, `maxatac data` asks before overwriting it, because the maxATAC v1 (binary) models in it will be replaced. If you are still interested in using the v1 models with quant-maxATAC, let us know on the [issue tracker](https://github.com/MiraldiLab/quant-maxATAC/issues). See [Data](./docs/readme/data.md) for details. #### Using custom reference data diff --git a/docs/readme/data.md b/docs/readme/data.md index 1e13a60..62d0f78 100644 --- a/docs/readme/data.md +++ b/docs/readme/data.md @@ -2,19 +2,27 @@ The `data` function downloads the reference data and models that the other functions look for by default under `~/opt/maxatac/data`: -* the [maxATAC_data](https://github.com/MiraldiLab/maxATAC_data) repository (blacklists, chromosome sizes, TF models with their `*_cross_celltype.tsv` threshold calibration tables, and the `prepare` shell scripts), cloned into `~/opt/maxatac/data` +* the [quant-maxATAC_data](https://github.com/MiraldiLab/quant-maxATAC_data) repository (blacklists, chromosome sizes, quant-maxATAC TF models with their `*_cross_celltype.tsv` threshold calibration tables, and the `prepare` shell scripts), cloned into `~/opt/maxatac/data` * the UCSC `.2bit` genome sequence for each requested genome, downloaded into `~/opt/maxatac/data//` - - `git` and `wget` must be on your PATH. +## Overwriting existing data and maxATAC v1 models + +quant-maxATAC uses its own data repository instead of the maxATAC v1 [maxATAC_data](https://github.com/MiraldiLab/maxATAC_data) repository. If `~/opt/maxatac/data` already exists, `maxatac data` lists what is installed there (the source repository and how many models look like v1 binary models) and asks for confirmation before replacing it. The whole directory is replaced, **including any maxATAC v1 models**. Answer anything other than `y` to leave it untouched. + +* The new data is cloned into a temporary directory first; the old directory is only removed once the clone has succeeded. +* `.2bit` files already present are kept, so they are not downloaded again. +* Without a terminal to answer the prompt (e.g. in a script or Docker build), `maxatac data` stops with an error unless `--yes` is given. + +If you are still interested in using the maxATAC v1 models with quant-maxATAC, let us know on the [issue tracker](https://github.com/MiraldiLab/quant-maxATAC/issues). + ## Example ```bash maxatac data maxatac data --genome hg38 hg19 +maxatac data --yes ``` ## Optional Arguments @@ -27,6 +35,14 @@ One or more genome builds to download the `.2bit` sequence for, or `all` for `hg Base directory to install into; data is placed in `/maxatac/data`. Default: `~/opt` +### `--data_repo` + +Git repository to install the reference data and models from, e.g. a fork or mirror of quant-maxATAC_data. Default: `https://github.com/MiraldiLab/quant-maxATAC_data.git` + +### `-y`, `--yes` + +Overwrite an existing data directory, including any maxATAC v1 models, without asking for confirmation. + ### `--loglevel` Logging level (`fatal`, `error`, `warning`, `info`, `debug`). Default: `info`. diff --git a/maxatac/analyses/data.py b/maxatac/analyses/data.py index f410db5..12e9f3b 100644 --- a/maxatac/analyses/data.py +++ b/maxatac/analyses/data.py @@ -1,52 +1,192 @@ +import glob import shutil import os +import sys +import stat import logging +import subprocess from maxatac.utilities.system_tools import get_dir, check_data_packages_installed - +from maxatac.utilities.constants import V1_MODELS_WISHLIST_URL + + +def remove_tree(path): + """Delete a directory tree, including read-only files such as git objects on Windows + + Args: + path (str): Directory to delete + """ + def make_writable_and_retry(func, failed_path, _): + os.chmod(failed_path, stat.S_IWRITE) + func(failed_path) + + if sys.version_info >= (3, 12): + shutil.rmtree(path, onexc=make_writable_and_retry) + else: + shutil.rmtree(path, onerror=make_writable_and_retry) + + +def describe_existing_data(data_dir): + """Summarize an existing maxATAC data directory so the user knows what will be overwritten + + Args: + data_dir (str): Path to the installed data directory. Default: ~/opt/maxatac/data + + Returns: + str: A short human readable description + """ + lines = [f"Existing maxATAC data found in: {data_dir}"] + + if os.path.isdir(os.path.join(data_dir, ".git")): + source = subprocess.run(["git", "remote", "get-url", "origin"], cwd=data_dir, + capture_output=True, text=True).stdout.strip() + + if source: + lines.append(f" Installed from: {source}") + + model_files = glob.glob(os.path.join(data_dir, "models", "*", "*.h5")) + + if model_files: + n_tfs = len({os.path.dirname(model_file) for model_file in model_files}) + + # quant-maxATAC model files carry "quant" in their name; anything else is most likely a v1 (binary) model + n_v1 = len([model_file for model_file in model_files if "quant" not in os.path.basename(model_file).lower()]) + + lines.append(f" Models: {len(model_files)} .h5 files for {n_tfs} TFs" + + (f", {n_v1} of which look like maxATAC v1 (binary) models" if n_v1 else "")) + + return "\n".join(lines) + + +def confirm_overwrite(data_dir, assume_yes): + """Ask the user to confirm that an existing data directory, including any v1 models, will be replaced + + Args: + data_dir (str): Path to the installed data directory + assume_yes (bool): Skip the prompt (--yes) + + Returns: + bool: True if the data directory may be overwritten + """ + logging.warning(describe_existing_data(data_dir)) + + if assume_yes: + logging.info("--yes was set: overwriting without asking") + return True + + if not sys.stdin.isatty(): + raise RuntimeError(f"{data_dir} already exists and would be overwritten, but there is no terminal to " + "confirm this. Re-run with --yes to overwrite it.") + + try: + answer = input(f"\n{data_dir} will be overwritten, including any maxATAC v1 models it contains.\n" + f"quant-maxATAC does not use the v1 models; to ask for v1 support, see {V1_MODELS_WISHLIST_URL}\n" + "Continue? [y/N] ") + + except EOFError: + # No answer could be read (e.g. stdin is a null device on Windows): treat it as "no" + logging.error("No answer received. Re-run with --yes to overwrite without asking.") + return False + + return answer.strip().lower() in ("y", "yes") + + def run_data(args): - """Download maxATAC reference data + """Download maxATAC reference data and the quant-maxATAC models + + Workflow overview + + 1) If a data directory already exists, ask the user to confirm it will be overwritten (v1 models included) + 2) Clone the data repository into a temporary directory, so a failed clone leaves the old data in place + 3) Replace the old data directory with the new clone, keeping any downloaded .2bit files + 4) Download the UCSC .2bit genome sequence for each requested genome Args: - args (Namespace): Arguments list for the reference genome and the log level. - """ + args (Namespace): Arguments list for the reference genome, output directory, data repository, --yes and the + log level. + """ check_data_packages_installed() ############### Parameters ############### # Path to the directory where the project data should be installed. Default: ~/opt base_dir = get_dir(args.output) - + # Path to the maxATAC directory in the install directory. Default: ~/opt/maxatac maxatac_dir = get_dir(os.path.join(base_dir, "maxatac")) - - # Path the repo directory and the final directory. Default: ~/opt/maxatac/maxATAC_data - maxatac_repo_dir = os.path.join(maxatac_dir, "maxATAC_data") - - # Path final directory (it is renamed for simplicity). Default: ~/opt/maxatac/data - maxatac_final_dir = os.path.join(maxatac_dir, "data") - # Command to clone the data repo - clone = "git clone --depth 1 https://github.com/MiraldiLab/maxATAC_data.git" + # Final data directory. Default: ~/opt/maxatac/data + maxatac_final_dir = os.path.join(maxatac_dir, "data") - os.chdir(maxatac_dir) # Change to the directory where the repo should be cloned - - os.system(clone) # Cloning + # Temporary clone directory, swapped in for the final directory once the clone succeeded + maxatac_tmp_dir = os.path.join(maxatac_dir, ".maxatac_data.tmp") - dest = shutil.move(maxatac_repo_dir, maxatac_final_dir) # Rename the git directory to data + # The old data directory is renamed here before the new one is moved in, and deleted last + maxatac_old_dir = os.path.join(maxatac_dir, ".maxatac_data.old") # Set all genomes if selected - if args.genome == ['all']: - args.genome = ["hg38", "hg19", "mm10"] + genomes = ["hg38", "hg19", "mm10"] if args.genome == ['all'] else args.genome + + ############### Body ############### + if os.path.isdir(maxatac_final_dir) and os.listdir(maxatac_final_dir): + if not confirm_overwrite(maxatac_final_dir, args.yes): + logging.info("Aborted: nothing was changed.") + return + + # Clear temporary directories left behind by an interrupted run + for leftover_dir in (maxatac_tmp_dir, maxatac_old_dir): + if os.path.exists(leftover_dir): + remove_tree(leftover_dir) + + logging.info(f"Cloning {args.data_repo} \n" + + f"Final data will be placed in: {maxatac_final_dir}") + + try: + subprocess.run(["git", "clone", "--depth", "1", args.data_repo, maxatac_tmp_dir], check=True) + + except subprocess.CalledProcessError: + if os.path.exists(maxatac_tmp_dir): + remove_tree(maxatac_tmp_dir) + raise + + if os.path.isdir(maxatac_final_dir): + # The .2bit files are not part of the repository and are large: carry them over instead of re-downloading + for twobit in glob.glob(os.path.join(maxatac_final_dir, "*", "*.2bit")): + new_genome_dir = os.path.join(maxatac_tmp_dir, os.path.basename(os.path.dirname(twobit))) + + if os.path.isdir(new_genome_dir) and not os.path.exists(os.path.join(new_genome_dir, os.path.basename(twobit))): + shutil.move(twobit, new_genome_dir) + + # Swap by renaming, so the data directory is never left half deleted + shutil.move(maxatac_final_dir, maxatac_old_dir) + + shutil.move(maxatac_tmp_dir, maxatac_final_dir) + + if os.path.exists(maxatac_old_dir): + remove_tree(maxatac_old_dir) + + commit = subprocess.run(["git", "rev-parse", "HEAD"], cwd=maxatac_final_dir, + capture_output=True, text=True).stdout.strip() + + logging.info(f"Installed {args.data_repo} at commit {commit}") + + for genome in genomes: + genome_dir = os.path.join(maxatac_final_dir, genome) + + if not os.path.isdir(genome_dir): + logging.warning(f"{args.data_repo} has no reference data for {genome}; skipping the {genome}.2bit download") + continue + + if os.path.exists(os.path.join(genome_dir, f"{genome}.2bit")): + logging.info(f"{genome}.2bit is already present in {genome_dir}") + continue - for genome in args.genome: - os.chdir(os.path.join(maxatac_final_dir, genome)) # change to the final data directory - wget_2bit = f"wget --no-check-certificate https://hgdownload.cse.ucsc.edu/goldenpath/{genome}/bigZips/{genome}.2bit -O {genome}.2bit" + logging.info(f"Downloading {genome}.2bit into {genome_dir}") - ############### Body ############### - logging.info(f"Downloading data for: {genome} \n" + - f"Data will be installed: {args.output} \n" + - f"Temporarily downlading data to: {maxatac_repo_dir} \n" + - f"Final data will be placed in: {maxatac_final_dir}") + # Download under a temporary name so an interrupted download is not mistaken for a finished one + subprocess.run(["wget", "--no-check-certificate", + f"https://hgdownload.cse.ucsc.edu/goldenpath/{genome}/bigZips/{genome}.2bit", + "-O", f"{genome}.2bit.part"], + cwd=genome_dir, check=True) - os.system(wget_2bit) # Wget 2bit + os.replace(os.path.join(genome_dir, f"{genome}.2bit.part"), os.path.join(genome_dir, f"{genome}.2bit")) logging.info("Finished!") diff --git a/maxatac/utilities/constants.py b/maxatac/utilities/constants.py index 7a27291..d5f334d 100644 --- a/maxatac/utilities/constants.py +++ b/maxatac/utilities/constants.py @@ -22,6 +22,13 @@ # build maxatac data path maxatac_data_path = os.path.join(os.path.expanduser('~'), "opt", "maxatac", "data") +# Reference data + quant-maxATAC models installed by `maxatac data`. It replaces MiraldiLab/maxATAC_data, +# which holds the binary maxATAC v1 models. +MAXATAC_DATA_REPO = "https://github.com/MiraldiLab/quant-maxATAC_data.git" + +# Where users can ask for the maxATAC v1 (binary) models to be supported again +V1_MODELS_WISHLIST_URL = "https://github.com/MiraldiLab/quant-maxATAC/issues" + # build processing script path names prepare_atac_script_dir = os.path.join(maxatac_data_path, "scripts", "ATAC", "ATAC_bowtie2_pipeline.sh") # bulk processing script diff --git a/maxatac/utilities/parser.py b/maxatac/utilities/parser.py index 79bb7aa..a91d135 100644 --- a/maxatac/utilities/parser.py +++ b/maxatac/utilities/parser.py @@ -48,7 +48,8 @@ BINARY_LOSS, QUANT_LOSS, QUANT_LOSSES, - QUANT_TARGET_SCALE_FACTOR + QUANT_TARGET_SCALE_FACTOR, + MAXATAC_DATA_REPO ) @@ -139,6 +140,23 @@ def get_parser(): help="Output results directory." ) + data_parser.add_argument("--data_repo", + dest="data_repo", + type=str, + default=MAXATAC_DATA_REPO, + required=False, + help="Git repository to install the reference data and models from. " + "Default: " + MAXATAC_DATA_REPO + ) + + data_parser.add_argument("-y", "--yes", + dest="yes", + action="store_true", + default=False, + help="Overwrite an existing data directory, including any maxATAC v1 models, " + "without asking for confirmation." + ) + data_parser.add_argument("--loglevel", dest="loglevel", type=str, diff --git a/maxatac/utilities/system_tools.py b/maxatac/utilities/system_tools.py index 642160b..d313ce8 100644 --- a/maxatac/utilities/system_tools.py +++ b/maxatac/utilities/system_tools.py @@ -4,7 +4,7 @@ import sys import subprocess from os import path, getcwd, makedirs, error, walk, environ -from maxatac.utilities.constants import CPP_LOG_LEVEL +from maxatac.utilities.constants import CPP_LOG_LEVEL, maxatac_data_path from re import match from multiprocessing import cpu_count @@ -207,9 +207,6 @@ def update_reference_genome_paths(args): """ logging.info(f"Generating Paths for genome build: {args.genome} \n") - # build maxatac data path - maxatac_data_path = os.path.join(os.path.expanduser('~'), "opt", "maxatac", "data") - # build genome specific paths blacklist_path = os.path.join(maxatac_data_path, f"{args.genome}/{args.genome}_maxatac_blacklist.bed") # maxATAC extended blacklist as bed From 7a951e208aa3a6837414759d40d35086f35c57d8 Mon Sep 17 00:00:00 2001 From: XC Date: Thu, 12 Nov 2026 10:51:59 -0500 Subject: [PATCH 40/40] q-maxATAC v2 preview - update 5 --- .dockerignore | 16 + .gitattributes | 1 + .github/workflows/ci.yml | 80 +++ .github/workflows/e2e.yml | 143 +++++ .github/workflows/release.yml | 187 ++++++ .gitignore | 4 + Dockerfile | 128 ++-- INSTALL.md | 2 + docs/readme/data.md | 8 + docs/readme/threshold.md | 17 +- maxatac/analyses/average.py | 4 +- maxatac/analyses/benchmark.py | 10 +- maxatac/analyses/data.py | 95 ++- maxatac/utilities/benchmarking_tools.py | 144 ++++- maxatac/utilities/genome_tools.py | 55 +- maxatac/utilities/parser.py | 52 +- maxatac/utilities/peak_tools.py | 15 +- maxatac/utilities/plot.py | 5 +- maxatac/utilities/system_tools.py | 10 +- maxatac/utilities/threshold_tools.py | 38 +- maxatac/utilities/training_tools.py | 6 +- setup.py | 46 +- tests/e2e/baseline.json | 13 + tests/e2e/check_outputs.py | 245 ++++++++ tests/e2e/run_e2e.sh | 103 +++ tests/run_tests.sh | 54 -- tests/test.sh | 52 -- tests/test_average.py | 22 + tests/test_average/test_average.py | 85 --- tests/test_benchmark.py | 329 ++++++++++ tests/test_data.py | 41 -- tests/test_helpers.py | 60 -- tests/test_normalize/test_normalize.py | 41 -- tests/test_parser.py | 792 ------------------------ tests/test_predict/test_predict.py | 33 - tests/test_prepare/test_prepare.py | 117 ---- tests/test_requirements.txt | 4 - tests/test_threshold.py | 77 +++ tests/test_tools.py | 20 - 39 files changed, 1702 insertions(+), 1452 deletions(-) create mode 100644 .dockerignore create mode 100644 .gitattributes create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/e2e.yml create mode 100644 .github/workflows/release.yml create mode 100644 tests/e2e/baseline.json create mode 100644 tests/e2e/check_outputs.py create mode 100644 tests/e2e/run_e2e.sh delete mode 100755 tests/run_tests.sh delete mode 100644 tests/test.sh create mode 100644 tests/test_average.py delete mode 100644 tests/test_average/test_average.py delete mode 100644 tests/test_data.py delete mode 100644 tests/test_helpers.py delete mode 100644 tests/test_normalize/test_normalize.py delete mode 100644 tests/test_parser.py delete mode 100644 tests/test_predict/test_predict.py delete mode 100644 tests/test_prepare/test_prepare.py delete mode 100644 tests/test_requirements.txt create mode 100644 tests/test_threshold.py delete mode 100644 tests/test_tools.py diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..af90966 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +# Only the package source goes into the image (see Dockerfile) +.git +.github +.idea +**/__pycache__ +**/*.pyc +*.egg-info +build +dist +docs +tests +packaging +test_data +e2e_out +maxatac/git_version +.Rhistory diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfdb8b7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.sh text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b2d8e4b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,80 @@ +name: CI + +# Fast checks on every push and pull request: install, CLI smoke test, lint for errors, unit tests. +# The data -> predict -> benchmark run lives in e2e.yml. + +on: + push: + # Branches only: release tags run this through release.yml + branches: ["**"] + pull_request: + workflow_dispatch: + workflow_call: + +permissions: + contents: read + +concurrency: + # github.workflow is the caller's name when called from release.yml, so a release never cancels a branch run + group: ${{ github.workflow }}-ci-${{ github.ref }} + cancel-in-progress: true + +env: + TF_CPP_MIN_LOG_LEVEL: "2" + CUDA_VISIBLE_DEVICES: "" + +jobs: + test: + name: Unit tests (Python ${{ matrix.python-version }}) + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + # setup.py pins tensorflow>=2.14,<2.16, which has wheels for Python 3.9-3.11 + python-version: ["3.10", "3.11"] + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + cache: pip + cache-dependency-path: setup.py + + - name: Install system dependencies + # pybedtools calls the bedtools binary + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends bedtools + + - name: Install ushuffle + # The PyPI release of ushuffle (a quant-maxATAC dependency) does not build; install it from source first. + # --no-build-isolation needs the build tools already installed. If the build fails, retry with Cython < 3. + run: | + # setuptools 82 removed pkg_resources, which older dependencies (e.g. TF 2.15-era tensorboard) still import + python -m pip install --upgrade pip "setuptools<82" wheel + pip install --no-build-isolation git+https://github.com/guma44/ushuffle.git || { + echo "::warning::ushuffle build failed; retrying with Cython < 3" + pip install "cython<3" + pip install --no-build-isolation git+https://github.com/guma44/ushuffle.git + } + python -c "from ushuffle import shuffle; print(shuffle(b'ACGTACGTAC', 2))" + + - name: Install quant-maxATAC + run: | + pip install -e . pytest flake8 + + - name: CLI smoke test + run: | + maxatac -h + for command in data predict benchmark threshold train; do + maxatac "$command" -h > /dev/null + done + + - name: Lint (errors only) + # Syntax errors and undefined names; style is not enforced + run: flake8 maxatac tests --count --select=E9,F63,F7,F82 --show-source --statistics + + - name: Unit tests + # data -> predict -> benchmark on real data is covered by e2e.yml + run: pytest -v tests --ignore=tests/e2e diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml new file mode 100644 index 0000000..b826527 --- /dev/null +++ b/.github/workflows/e2e.yml @@ -0,0 +1,143 @@ +name: End-to-end + +# The user path on real data: `maxatac data` -> `maxatac predict` -> `maxatac benchmark` +# inputs: https://github.com/XiaotingChen/quant-maxATAC_test_data (Git LFS) +# models: https://github.com/MiraldiLab/quant-maxATAC_data (installed by `maxatac data`) +# The steps themselves are in tests/e2e/run_e2e.sh so they can be run outside GitHub too. + +on: + push: + branches: [main, "quant*"] + pull_request: + workflow_dispatch: + inputs: + data_version: + description: "Data repository tag or branch (`maxatac data --data_version`); empty = match the code version" + required: false + default: "" + workflow_call: + # release.yml passes the release tag, so a release is tested with the data of the same tag + inputs: + data_version: + type: string + required: false + default: "" + schedule: + # Weekly, to catch changes in the data repositories and in unpinned dependencies + - cron: "0 6 * * 1" + +permissions: + contents: read + +concurrency: + # github.workflow is the caller's name when called from release.yml, so a release never cancels a branch run + group: ${{ github.workflow }}-e2e-${{ github.ref }} + cancel-in-progress: true + +env: + TEST_DATA_REPO: XiaotingChen/quant-maxATAC_test_data + DATA_VERSION: ${{ inputs.data_version }} + TF_CPP_MIN_LOG_LEVEL: "2" + CUDA_VISIBLE_DEVICES: "" + +jobs: + e2e: + name: data -> predict -> benchmark (GM12878 CTCF, chr1 slice) + runs-on: ubuntu-latest + timeout-minutes: 60 + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + cache: pip + cache-dependency-path: setup.py + + - name: Install system dependencies + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends bedtools wget + + - name: Install ushuffle + # The PyPI release of ushuffle (a quant-maxATAC dependency) does not build; install it from source first. + # --no-build-isolation needs the build tools already installed. If the build fails, retry with Cython < 3. + run: | + # setuptools 82 removed pkg_resources, which older dependencies (e.g. TF 2.15-era tensorboard) still import + python -m pip install --upgrade pip "setuptools<82" wheel + pip install --no-build-isolation git+https://github.com/guma44/ushuffle.git || { + echo "::warning::ushuffle build failed; retrying with Cython < 3" + pip install "cython<3" + pip install --no-build-isolation git+https://github.com/guma44/ushuffle.git + } + python -c "from ushuffle import shuffle; print(shuffle(b'ACGTACGTAC', 2))" + + - name: Install quant-maxATAC + run: | + pip install -e . + + # ---- Test inputs: Git LFS files, cached per commit of the test data repository so each + # commit is downloaded once (LFS bandwidth is metered on the repository owner's account) + - name: Resolve test data commit + id: test-data + run: echo "sha=$(git ls-remote "https://github.com/${TEST_DATA_REPO}.git" HEAD | cut -f1)" >> "$GITHUB_OUTPUT" + + - name: Restore test data + id: test-data-cache + uses: actions/cache/restore@v4 + with: + path: test_data/data + key: test-data-${{ steps.test-data.outputs.sha }} + + - name: Download test data + if: steps.test-data-cache.outputs.cache-hit != 'true' + uses: actions/checkout@v4 + with: + repository: ${{ env.TEST_DATA_REPO }} + ref: ${{ steps.test-data.outputs.sha }} + path: test_data + lfs: true + + - name: Save test data + if: steps.test-data-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@v4 + with: + path: test_data/data + key: test-data-${{ steps.test-data.outputs.sha }} + + # ---- hg38.2bit (~800 MB from UCSC). Restored into the data directory before `maxatac data`, + # which carries an existing .2bit over into the fresh clone instead of downloading it again + - name: Restore hg38.2bit + id: twobit-cache + uses: actions/cache/restore@v4 + with: + path: ~/opt/maxatac/data/hg38/hg38.2bit + key: hg38-2bit-v1 + + - name: Run data -> predict -> benchmark + run: bash tests/e2e/run_e2e.sh + env: + TEST_DATA: test_data/data + OUT: e2e_out + + - name: Check for a downloaded hg38.2bit + id: twobit + if: always() && steps.twobit-cache.outputs.cache-hit != 'true' + # hashFiles() only sees the workspace, so test for the file directly + run: | + if [ -s ~/opt/maxatac/data/hg38/hg38.2bit ]; then echo "present=true" >> "$GITHUB_OUTPUT"; fi + + - name: Save hg38.2bit + if: always() && steps.twobit.outputs.present == 'true' + uses: actions/cache/save@v4 + with: + path: ~/opt/maxatac/data/hg38/hg38.2bit + key: hg38-2bit-v1 + + - name: Upload outputs + if: always() + uses: actions/upload-artifact@v4 + with: + name: e2e-outputs + path: e2e_out + retention-days: 14 + if-no-files-found: ignore diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..13bae27 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,187 @@ +name: Release + +# Push a version tag to release, e.g. +# git tag -a v2.0.0b2 -m "q-maxATAC v2 preview 2" && git push xc v2.0.0b2 +# +# 1. Runs CI and the end-to-end test on the tagged commit, the latter with the data repository tag of the same +# name (`maxatac data --data_version `): tag MiraldiLab/quant-maxATAC_data first, or the release fails +# 2. Builds the sdist and wheel and checks their version matches the tag +# 3. Once CI and the end-to-end test pass, builds the Docker image from the tagged commit, checks the version +# inside it and pushes it to ghcr.io//quant-maxatac: (and :latest for final releases) +# 4. Creates a GitHub Release with the packages, the e2e metrics and the image in the notes and the benchmark +# files attached. a/b/rc tags (v2.0.0b2, v2.0.0rc1) are marked as pre-releases +# +# The first image pushed to a repository owner's GHCR is private: make it public once in the package settings. +# +# Tags must be PEP 440 versions with a leading "v": v2.0.0, v2.0.0b1, v2.0.0rc1. Never move or reuse a tag. + +on: + push: + tags: ["v*"] + +permissions: + contents: read + +jobs: + ci: + uses: ./.github/workflows/ci.yml + + e2e: + uses: ./.github/workflows/e2e.yml + with: + data_version: ${{ github.ref_name }} + + build: + name: Build packages + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + # Full history and tags: setup.py reads the version from the tag on this commit + fetch-depth: 0 + + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Build sdist and wheel + run: | + python -m pip install --upgrade pip build twine + python -m build + twine check dist/* + + - name: Check the version matches the tag + # Catches tags that are not PEP 440 versions (e.g. v2.0.0-preview.1 would be built as 2.0.0rc1) + run: | + version="${GITHUB_REF_NAME#v}" + ls dist + if [ ! -f "dist/maxatac-${version}.tar.gz" ]; then + echo "::error::Built packages do not have version ${version} from tag ${GITHUB_REF_NAME}" + exit 1 + fi + + - uses: actions/upload-artifact@v4 + with: + name: dist + path: dist + retention-days: 14 + + image: + name: Docker image + # Only publish an image of code that passed the checks + needs: [ci, e2e] + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + outputs: + image: ${{ steps.name.outputs.image }} + steps: + - uses: actions/checkout@v4 + + - name: Image name and version + id: name + # GHCR names must be lowercase; the owner follows the repository, so this works unchanged upstream + run: | + version="${GITHUB_REF_NAME#v}" + echo "version=${version}" >> "$GITHUB_OUTPUT" + echo "repo=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/quant-maxatac" >> "$GITHUB_OUTPUT" + echo "image=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/quant-maxatac:${version}" >> "$GITHUB_OUTPUT" + + - uses: docker/setup-buildx-action@v3 + + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ github.token }} + + - name: Build + uses: docker/build-push-action@v6 + with: + context: . + # The image has no .git: the version comes from the tag of the commit it is built from + build-args: | + MAXATAC_VERSION=${{ steps.name.outputs.version }} + SOURCE_URL=${{ github.server_url }}/${{ github.repository }} + load: true + tags: ${{ steps.name.outputs.image }} + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Test the image + env: + IMAGE: ${{ steps.name.outputs.image }} + VERSION: ${{ steps.name.outputs.version }} + run: | + docker run --rm "${IMAGE}" maxatac -h > /dev/null + installed=$(docker run --rm "${IMAGE}" python -c "from importlib import metadata; print(metadata.version('maxatac'))") + if [ "${installed}" != "${VERSION}" ]; then + echo "::error::The image has maxatac ${installed}, expected ${VERSION}" + exit 1 + fi + docker run --rm "${IMAGE}" python -c "from ushuffle import shuffle; shuffle(b'ACGTACGTAC', 2)" + docker images "${IMAGE}" + + - name: Push + env: + IMAGE: ${{ steps.name.outputs.image }} + REPO: ${{ steps.name.outputs.repo }} + run: | + docker push "${IMAGE}" + # :latest only moves to final releases, never to a/b/rc pre-releases + if [[ ! "${GITHUB_REF_NAME}" =~ (a|b|rc)[0-9]+$ ]]; then + docker tag "${IMAGE}" "${REPO}:latest" + docker push "${REPO}:latest" + fi + + release: + name: GitHub Release + needs: [ci, e2e, build, image] + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist + + - uses: actions/download-artifact@v4 + with: + name: e2e-outputs + path: e2e_out + + - name: Write release notes + env: + IMAGE: ${{ needs.image.outputs.image }} + run: | + { + echo "quant-maxATAC ${GITHUB_REF_NAME}, tested with [quant-maxATAC_data ${GITHUB_REF_NAME}](https://github.com/MiraldiLab/quant-maxATAC_data/tree/${GITHUB_REF_NAME})." + echo + echo "Install: \`pip install https://github.com/${GITHUB_REPOSITORY}/releases/download/${GITHUB_REF_NAME}/$(cd dist && ls *.whl)\`, then \`maxatac data\` installs the matching models." + echo + echo "Docker: \`docker pull ${IMAGE}\` (no data inside: mount ~/opt/maxatac, see the [Dockerfile](https://github.com/${GITHUB_REPOSITORY}/blob/${GITHUB_REF_NAME}/Dockerfile))." + echo + cat e2e_out/metrics.md + } > notes.md + cat notes.md + + - name: Create the release + env: + GH_TOKEN: ${{ github.token }} + run: | + shopt -s nullglob + prerelease="" + if [[ "${GITHUB_REF_NAME}" =~ (a|b|rc)[0-9]+$ ]]; then prerelease="--prerelease"; fi + + gh release create "${GITHUB_REF_NAME}" \ + --repo "${GITHUB_REPOSITORY}" \ + --title "quant-maxATAC ${GITHUB_REF_NAME}" \ + --notes-file notes.md \ + --generate-notes \ + ${prerelease} \ + dist/* \ + e2e_out/metrics.json \ + e2e_out/benchmark/*.tsv \ + e2e_out/benchmark/*.png diff --git a/.gitignore b/.gitignore index 8f90e03..7cf290e 100644 --- a/.gitignore +++ b/.gitignore @@ -115,3 +115,7 @@ snakemake/dag.svg # Readme Swp file *.INSTALL.md.swp + +# End-to-end test (tests/e2e/run_e2e.sh) +test_data/ +e2e_out/ diff --git a/Dockerfile b/Dockerfile index aafbe02..0219bf8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,70 +1,88 @@ ################################################################# -# Dockerfile +# quant-maxATAC (CPU) # -# Software: maxATAC -# Software Version: v0.0.3 -# Description: python based suite for transcription factor binding prediction -# Website: https://github.com/MiraldiLab/maxATAC -# Website2: https://github.com/MiraldiLab/maxATAC_data -# Provides: Transcription Factor Binding Prediction -# Base Image: biowardrobe2/samtools:v1.4/bedtools/ucsc-bedgraphtobigwig/pigz -# Build Cmd: docker build --rm -t miraldi/maxatac:v0.0.3 -f Dockerfile . -# Pull Cmd: docker pull miraldi/maxatac:v0.0.3 -# Run Cmd: docker run --rm -ti miraldi/maxatac:v0.0.3 +# Build: docker build -t quant-maxatac --build-arg MAXATAC_VERSION=2.0.0b2 . +# MAXATAC_VERSION is the release without its "v" (the git tag is not copied into the image). It decides +# which data tag `maxatac data` installs; without it the image is a development version and installs the +# latest data. +# +# The image holds no reference data or models (the hg38.2bit alone is ~800 MB). Keep them on the host under +# ~/opt/maxatac and mount that directory; `maxatac data` fills it once and later runs reuse it: +# +# docker run --rm --user "$(id -u):$(id -g)" -v ~/opt/maxatac:/home/maxatac/opt/maxatac \ +# quant-maxatac maxatac data +# docker run --rm --user "$(id -u):$(id -g)" -v ~/opt/maxatac:/home/maxatac/opt/maxatac -v "$PWD":/work \ +# quant-maxatac maxatac predict --tf_name CTCF --signal sample.bw --prefix sample_CTCF +# +# Singularity/Apptainer mounts your home directory by default, so ~/opt/maxatac/data on the host is used as is: +# apptainer exec docker:// maxatac predict ... ################################################################# +ARG PYTHON_VERSION=3.11 -# Dockerfile, Image, Container +########## Build stage: compile the Python packages into a virtualenv ########## +FROM python:${PYTHON_VERSION}-slim-bookworm AS build -FROM python:3.9 +# Compilers and headers for packages without wheels (ushuffle, py2bit, ...) +RUN apt-get update && \ + apt-get install -y --no-install-recommends build-essential git zlib1g-dev libbz2-dev liblzma-dev \ + libcurl4-openssl-dev && \ + rm -rf /var/lib/apt/lists/* -################## BEGIN INSTALLATION ###################### +RUN python -m venv /opt/venv +ENV PATH=/opt/venv/bin:$PATH -WORKDIR /tmp +# setuptools 82 removed pkg_resources, which older dependencies (e.g. TF 2.15-era tensorboard) still import +RUN pip install --no-cache-dir --upgrade pip "setuptools<82" wheel -ENV VERSION_BEDTOOLS 2.26.0 -ENV URL_BEDTOOLS "https://github.com/arq5x/bedtools2/releases/download/v${VERSION_BEDTOOLS}/bedtools-${VERSION_BEDTOOLS}.tar.gz" +# The PyPI release of ushuffle does not build: install it from source first, as in .github/workflows/ci.yml. +# --no-build-isolation needs the build tools above. If the build fails, retry with Cython < 3 +ARG USHUFFLE_SOURCE=git+https://github.com/guma44/ushuffle.git@b54df34f60246ff236ec58bbccb40af3cea608ed +RUN (pip install --no-cache-dir --no-build-isolation "${USHUFFLE_SOURCE}" || \ + (pip install --no-cache-dir "cython<3" && pip install --no-cache-dir --no-build-isolation "${USHUFFLE_SOURCE}")) && \ + python -c "from ushuffle import shuffle; shuffle(b'ACGTACGTAC', 2)" -ENV VERSION_HTSLIB 1.12 -ENV URL_HTSLIB "https://github.com/samtools/htslib/releases/download/${VERSION_HTSLIB}/htslib-${VERSION_HTSLIB}.tar.bz2" +COPY . /src -ENV VERSION_SAMTOOLS 1.12 -ENV URL_SAMTOOLS "https://github.com/samtools/samtools/releases/download/${VERSION_SAMTOOLS}/samtools-${VERSION_SAMTOOLS}.tar.bz2" +# Without .git, setup.py reads the version from maxatac/git_version +ARG MAXATAC_VERSION="" +RUN if [ -n "${MAXATAC_VERSION}" ]; then printf "%s" "${MAXATAC_VERSION#v}" > /src/maxatac/git_version; fi && \ + pip install --no-cache-dir /src -ENV URL_UCSC "http://hgdownload.soe.ucsc.edu/admin/exe/userApps.src.tgz" +########## Runtime stage ########## +FROM python:${PYTHON_VERSION}-slim-bookworm +ARG MAXATAC_VERSION="" +# GHCR links the image to this repository (release.yml passes the repository that built it) +ARG SOURCE_URL=https://github.com/MiraldiLab/quant-maxATAC +LABEL org.opencontainers.image.title="quant-maxATAC" \ + org.opencontainers.image.description="Deep neural networks predicting quantitative TF ChIP-seq signal from ATAC-seq signal and DNA sequence" \ + org.opencontainers.image.source="${SOURCE_URL}" \ + org.opencontainers.image.version="${MAXATAC_VERSION}" \ + org.opencontainers.image.licenses="Apache-2.0" +# git, wget: `maxatac data`. samtools, bedtools, pigz, bedGraphToBigWig: `maxatac prepare`; bedtools also for +# pybedtools in predict/benchmark +ARG BEDGRAPHTOBIGWIG_URL=https://hgdownload.soe.ucsc.edu/admin/exe/linux.x86_64/bedGraphToBigWig RUN apt-get update && \ - apt-get install -y gcc-10-base libgcc-10-dev libxml2-dev libcurl4-openssl-dev libssl-dev pandoc libgtextutils-dev libmariadb-dev-compat libmariadb-dev libpng-dev uuid-dev libncurses5-dev libbz2-dev liblzma-dev pigz rsync && \ -### Install htslib - wget -q -O - $URL_HTSLIB | tar -jxv && \ - cd htslib-${VERSION_HTSLIB} && \ - ./configure --prefix=/usr/local/ && \ - make -j 4 && \ - make install && \ - cd .. && \ -### Install samtools - wget -q -O - $URL_SAMTOOLS | tar -jxv && \ - cd samtools-${VERSION_SAMTOOLS} && \ - ./configure --prefix=/usr/local/ && \ - make -j 4 && \ - make install && \ - cd .. && \ -### Install bedtools - wget -q -O - $URL_BEDTOOLS | tar -zxv && \ - cd bedtools2 && \ - make -j 4 && \ - cd .. && \ - cp ./bedtools2/bin/bedtools /usr/local/bin/ && \ -### Install UCSC User Apps - wget -q -O - $URL_UCSC | tar -zxv --strip-components=2 && \ - make -j 2 && \ - cp ./bin/* /usr/local/bin/ &&\ - rm -rf ./* &&\ - pip install maxatac==0.0.3 &&\ - mkdir -p /opt/maxatac && cd /opt/maxatac &&\ - git clone --depth 1 https://github.com/MiraldiLab/quant-maxATAC_data.git data &&\ - cd ./data/hg38 && wget https://hgdownload.cse.ucsc.edu/goldenpath/hg38/bigZips/hg38.2bit &&\ - strip /usr/local/bin/*; true - -CMD ["maxatac"] + apt-get install -y --no-install-recommends bedtools samtools pigz git wget ca-certificates && \ + rm -rf /var/lib/apt/lists/* && \ + wget -q -O /usr/local/bin/bedGraphToBigWig "${BEDGRAPHTOBIGWIG_URL}" && \ + chmod +x /usr/local/bin/bedGraphToBigWig && \ + (bedGraphToBigWig 2>&1 || true) | grep -q "usage" + +COPY --from=build /opt/venv /opt/venv + +# A fixed HOME, so the data directory (~/opt/maxatac/data) is the same for any --user. World-writable because +# --user runs as an arbitrary uid +ENV PATH=/opt/venv/bin:$PATH \ + HOME=/home/maxatac \ + MPLCONFIGDIR=/tmp/matplotlib \ + TF_CPP_MIN_LOG_LEVEL=2 +RUN mkdir -p /home/maxatac/opt/maxatac /work && chmod -R 777 /home/maxatac /work + +WORKDIR /work + +RUN maxatac -h > /dev/null + +CMD ["maxatac", "-h"] diff --git a/INSTALL.md b/INSTALL.md index 7997e6e..a26a0cb 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -18,6 +18,8 @@ mkdir -p ~/opt/maxatac git clone --depth 1 https://github.com/MiraldiLab/quant-maxATAC_data.git ~/opt/maxatac/data ``` +To match a quant-maxATAC release, clone the data tag of the same name, e.g. `git clone --depth 1 --branch v2.0.0b1 ...`. `maxatac data` does this for you. + ### 3. Then download the hg38.2bit file from UCSC next to the hg38 reference files ```bash diff --git a/docs/readme/data.md b/docs/readme/data.md index 62d0f78..0e44cd8 100644 --- a/docs/readme/data.md +++ b/docs/readme/data.md @@ -23,6 +23,8 @@ If you are still interested in using the maxATAC v1 models with quant-maxATAC, l maxatac data maxatac data --genome hg38 hg19 maxatac data --yes +maxatac data --data_version v2.0.0b1 +maxatac data --data_version latest ``` ## Optional Arguments @@ -39,6 +41,12 @@ Base directory to install into; data is placed in `/maxatac/data`. Defau Git repository to install the reference data and models from, e.g. a fork or mirror of quant-maxATAC_data. Default: `https://github.com/MiraldiLab/quant-maxATAC_data.git` +### `--data_version` + +Tag or branch of the data repository to install, e.g. `v2.0.0b1`, or `latest` for the newest commit on its default branch. Default: the data tag matching the installed quant-maxATAC version (`maxatac --version`), so code and models from the same release are used together. Development installs (versions ending in `.dev0`) and versions without a matching tag install the latest data, with a warning. + +Releases are tagged with the same name in both repositories, following [PEP 440](https://peps.python.org/pep-0440/): `v2.0.0b1`, `v2.0.0b2`, … for previews, `v2.0.0rc1` for release candidates and `v2.0.0` for the release. + ### `-y`, `--yes` Overwrite an existing data directory, including any maxATAC v1 models, without asking for confirmation. diff --git a/docs/readme/threshold.md b/docs/readme/threshold.md index f382d64..b28679f 100644 --- a/docs/readme/threshold.md +++ b/docs/readme/threshold.md @@ -9,11 +9,18 @@ Because quantitative models output predicted ChIP-seq signal rather than probabi For every cell type listed in the meta file: 1. The prediction bigwig and the binary gold standard bigwig are binned at `--bin_size` (max per bin) on the single held-out chromosome given by `--chromosomes`, excluding blacklisted bins. -2. A precision-recall curve is computed from the binned prediction scores against the binned gold standard, giving precision, recall, F1 and log2(precision / random precision) for every threshold. -3. Alongside the bin-level Recall, a peak-level **Peak_Recall** is computed per threshold: the fraction of unique ChIP-seq peaks with at least one non-blacklisted bin whose prediction is ≥ the threshold. Peaks are the unique intervals of the optional `ChIP_peaks` BED, or runs of consecutive gold-standard bins when it is not given. Fully blacklisted peaks are not counted. -4. The curve is re-binned on a 0.01 grid of Precision, Recall, F1 and Peak_Recall values so that each metric value maps to the threshold that achieves it. +2. A precision-recall curve is computed from the binned prediction scores against the binned gold standard: for every threshold, the precision, recall, F1 and log2(precision / random precision) **actually achieved at that threshold**. +3. Only thresholds worth using are kept. A threshold is dropped when a lower threshold reaches the same or a higher precision, because that lower threshold also has at least the recall (and Peak_Recall). On the kept rows, precision rises and recall falls as the threshold increases, and every row is a real threshold with the metrics it achieves: no value is carried over from another threshold. The final point of a precision-recall curve (Precision = 1, Recall = 0) belongs to no threshold and is not included, so a precision of 1 only appears if some threshold really reaches it. +4. Alongside the bin-level Recall, a peak-level **Peak_Recall** is computed per kept threshold: the fraction of unique ChIP-seq peaks with at least one non-blacklisted bin whose prediction is ≥ the threshold. Peaks are the unique intervals of the optional `ChIP_peaks` BED, or runs of consecutive gold-standard bins when it is not given. Fully blacklisted peaks are not counted. +5. The curve is re-binned on a 0.01 grid of Precision, Recall and Peak_Recall values, keeping the highest-F1 row in each bin. -The per-metric grids are then combined across cell types by taking the median threshold per grid bin (only thresholds are aggregated, never raw signal), producing the cross-cell-type table. `predict`/`peaks` look up the lowest grid bin that still meets the requested `--cutoff_value` (or the max-F1 bin when `--cutoff_type F1` is used without a value). +The per-cell-type grids are then combined into the cross-cell-type table: + +* Each cell type's grid is first extended to every bin from 0.00 to 1.00, so all cell types cover the same bins. Bins between two values the curve reaches are linearly interpolated. Bins beyond the curve's range repeat its nearest real row, so their `Precision`/`Recall` columns show what the cell type actually reaches, not the bin value. +* Per bin, the median `Precision`, `Recall`, `Threshold` and `Peak_Recall` across cell types is taken (only these per-threshold values are aggregated, never raw signal), and F1 is recomputed from the median precision and recall. A row therefore describes a typical cell type, not one particular cell type. +* The F1 grid is built from the Recall table by re-binning its rows on F1. + +`predict`/`peaks` look up a threshold by the **achieved** value of the requested metric, not by the bin label: among the rows of `--cutoff_type` whose achieved `Precision`, `Recall`, `F1` or `Peak_Recall` is ≥ `--cutoff_value`, they use the one closest to the request (ties go to the higher F1). If no row reaches the value, they stop with an error naming the highest value the table reaches. With `--cutoff_type F1` and no `--cutoff_value`, the max-F1 row is used. ## Meta file @@ -37,7 +44,7 @@ maxatac threshold --prefix CTCF --meta_file CTCF_threshold_meta.tsv --chromosome | Filename | Description | |-----------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------| -| `_cross_celltype.tsv` | The calibration table used by `predict`/`peaks`. Columns: `Metric` (`Precision`, `Recall`, `F1` or `Peak_Recall`), `Bin` (metric value on the 0.01 grid), `Precision`, `Recall`, `Threshold`, `F1`, `Peak_Recall` (fraction of unique ChIP-seq peaks recovered at that threshold) | +| `_cross_celltype.tsv` | The calibration table used by `predict`/`peaks`. Columns: `Metric` (`Precision`, `Recall`, `F1` or `Peak_Recall`), `Bin` (position on the 0.01 grid of that metric), `Precision`, `Recall`, `Threshold`, `F1`, `Peak_Recall` (fraction of unique ChIP-seq peaks recovered at that threshold). The `Precision`/`Recall`/`F1`/`Peak_Recall` columns are the values achieved at `Threshold`; past the range a curve reaches they can be lower than `Bin` | | `.tsv` | The same table for each individual cell type in the meta file | | `_peak_recovery.tsv` | Per cell type: peak source, number of unique peaks, and `Peak_Recall` at that cell type's own max-F1 threshold and at the cross-cell-type max-F1 threshold | | `*_validationPerformance_vs_thresholdCalibration.png` | Precision, recall, F1 and fraction of unique peaks recovered vs. threshold for every cell type, with the cross-cell-type median in black | diff --git a/maxatac/analyses/average.py b/maxatac/analyses/average.py index 49d8ec1..036350a 100644 --- a/maxatac/analyses/average.py +++ b/maxatac/analyses/average.py @@ -24,7 +24,7 @@ def run_averaging(args): 4) Loop through each entry in the chromosome sizes dictionary and calculate the average across all inputs 5) Write the bigwig file - :param args: bigwig_files, output_dir, name, chromosomes, chromosome_sizes, max_zooms + :param args: bigwig_files, output_dir, name, chromosomes, chrom_sizes, max_zooms :return: A bigwig file """ @@ -50,7 +50,7 @@ def run_averaging(args): # Build a dictionary of chromosomes sizes using the chromosomes and chromosome sizes files provided # The function will filter the dictionary based on the input list - chromosome_sizes_dictionary = build_chrom_sizes_dict(args.chromosomes, args.chromosome_sizes) + chromosome_sizes_dictionary = build_chrom_sizes_dict(args.chromosomes, args.chrom_sizes) # Open the bigwig file for writing with pyBigWig.open(output_bigwig_filename, "w") as output_bw: diff --git a/maxatac/analyses/benchmark.py b/maxatac/analyses/benchmark.py index 894b886..dde7736 100644 --- a/maxatac/analyses/benchmark.py +++ b/maxatac/analyses/benchmark.py @@ -38,7 +38,7 @@ def run_benchmarking(args): logging.info( "Benchmarking" + - "\n Prediction file: " + args.prediction + + "\n Prediction file: " + str(args.prediction) + "\n Alternative prediction file: " + str(args.alternative_prediction) + "\n Prediction combine operation: " + args.prediction_combine_operation + "\n Gold standard file: " + args.gold_standard + @@ -71,9 +71,10 @@ def run_benchmarking(args): else: for chromosome in args.chromosomes: logging.info("Benchmarking " + chromosome) - # Build the results filename + # Build the results filename; --random writes only the random baselines to their own file + results_suffix = "bp_random_UCPeR.tsv" if args.random else "bp_PRC.tsv" results_filename = os.path.join(output_dir, - args.prefix + "_" + chromosome + "_" + str(args.bin_size) + "bp_PRC.tsv") + args.prefix + "_" + chromosome + "_" + str(args.bin_size) + results_suffix) ChromosomeAUPRC(args.prediction, args.gold_standard, @@ -88,7 +89,8 @@ def run_benchmarking(args): plot=args.plot, peak_based=args.peak_based, alternative_prediction_bw=args.alternative_prediction, - prediction_combine_operation=args.prediction_combine_operation + prediction_combine_operation=args.prediction_combine_operation, + random_only=args.random ) # Measure End Time of Training diff --git a/maxatac/analyses/data.py b/maxatac/analyses/data.py index 12e9f3b..b37e460 100644 --- a/maxatac/analyses/data.py +++ b/maxatac/analyses/data.py @@ -4,10 +4,70 @@ import sys import stat import logging +import re import subprocess -from maxatac.utilities.system_tools import get_dir, check_data_packages_installed +from maxatac.utilities.system_tools import get_dir, check_data_packages_installed, get_version from maxatac.utilities.constants import V1_MODELS_WISHLIST_URL +# Release and pre-release versions (2.0.0, 2.0.0b1, 2.0.0rc1, 2.0.0.post1) have a data repository tag of the +# same name; development versions (2.0.0.dev0, local versions such as 2.0.0+g1234abc) do not +RELEASE_VERSION = re.compile(r"\d+(\.\d+)*((a|b|rc)\d+)?(\.post\d+)?") + + +def remote_ref_exists(data_repo, ref): + """Check whether a git repository has a tag or branch with this name + + Args: + data_repo (str): Git repository URL or path + ref (str): Tag or branch name + + Returns: + bool: True if the tag or branch exists + """ + result = subprocess.run(["git", "ls-remote", "--tags", "--heads", data_repo, ref], + capture_output=True, text=True, check=True) + + return any(line.split("\t")[1] in (f"refs/tags/{ref}", f"refs/heads/{ref}") + for line in result.stdout.splitlines()) + + +def resolve_data_version(data_repo, data_version): + """Pick the data repository tag or branch to install + + Args: + data_repo (str): Git repository URL or path + data_version (str): --data_version: a tag or branch, "latest", or None for the tag matching this + quant-maxATAC version + + Returns: + str: Tag or branch to clone, or None to clone the latest commit on the default branch + """ + if data_version == "latest": + return None + + if data_version: + if not remote_ref_exists(data_repo, data_version): + raise ValueError(f"{data_repo} has no tag or branch named {data_version}. " + "Use --data_version latest for the newest data.") + + return data_version + + version = get_version() + + if not RELEASE_VERSION.fullmatch(version): + logging.warning(f"quant-maxATAC {version} is a development version: installing the latest data from " + f"{data_repo}. Use --data_version to install a specific release.") + return None + + tag = f"v{version}" + + if not remote_ref_exists(data_repo, tag): + logging.warning(f"{data_repo} has no {tag} tag matching quant-maxATAC {version}: installing the latest " + "data instead. Use --data_version to install a specific release.") + return None + + return tag + def remove_tree(path): """Delete a directory tree, including read-only files such as git objects on Windows @@ -48,8 +108,9 @@ def describe_existing_data(data_dir): if model_files: n_tfs = len({os.path.dirname(model_file) for model_file in model_files}) - # quant-maxATAC model files carry "quant" in their name; anything else is most likely a v1 (binary) model - n_v1 = len([model_file for model_file in model_files if "quant" not in os.path.basename(model_file).lower()]) + # quant-maxATAC ships a _cross_celltype.tsv calibration table next to each model; v1 (binary) models do not + n_v1 = len([model_file for model_file in model_files + if not glob.glob(os.path.join(os.path.dirname(model_file), "*_cross_celltype.tsv"))]) lines.append(f" Models: {len(model_files)} .h5 files for {n_tfs} TFs" + (f", {n_v1} of which look like maxATAC v1 (binary) models" if n_v1 else "")) @@ -95,14 +156,16 @@ def run_data(args): Workflow overview - 1) If a data directory already exists, ask the user to confirm it will be overwritten (v1 models included) - 2) Clone the data repository into a temporary directory, so a failed clone leaves the old data in place - 3) Replace the old data directory with the new clone, keeping any downloaded .2bit files - 4) Download the UCSC .2bit genome sequence for each requested genome + 1) Pick the data version: --data_version, or the data repository tag matching this quant-maxATAC version + 2) If a data directory already exists, ask the user to confirm it will be overwritten (v1 models included) + 3) Clone that version of the data repository into a temporary directory, so a failed clone leaves the old + data in place + 4) Replace the old data directory with the new clone, keeping any downloaded .2bit files + 5) Download the UCSC .2bit genome sequence for each requested genome Args: - args (Namespace): Arguments list for the reference genome, output directory, data repository, --yes and the - log level. + args (Namespace): Arguments list for the reference genome, output directory, data repository, data version, + --yes and the log level. """ check_data_packages_installed() @@ -126,6 +189,10 @@ def run_data(args): genomes = ["hg38", "hg19", "mm10"] if args.genome == ['all'] else args.genome ############### Body ############### + # Resolve the version first, so a bad --data_version fails before anything is asked or changed + data_ref = resolve_data_version(args.data_repo, args.data_version) + data_label = data_ref or "latest" + if os.path.isdir(maxatac_final_dir) and os.listdir(maxatac_final_dir): if not confirm_overwrite(maxatac_final_dir, args.yes): logging.info("Aborted: nothing was changed.") @@ -136,11 +203,15 @@ def run_data(args): if os.path.exists(leftover_dir): remove_tree(leftover_dir) - logging.info(f"Cloning {args.data_repo} \n" + + logging.info(f"Cloning {args.data_repo} ({data_label}) \n" + f"Final data will be placed in: {maxatac_final_dir}") + branch = ["--branch", data_ref] if data_ref else [] + try: - subprocess.run(["git", "clone", "--depth", "1", args.data_repo, maxatac_tmp_dir], check=True) + # advice.detachedHead=false: cloning a tag is expected, not worth git's detached HEAD notice + subprocess.run(["git", "-c", "advice.detachedHead=false", "clone", "--depth", "1", *branch, + args.data_repo, maxatac_tmp_dir], check=True) except subprocess.CalledProcessError: if os.path.exists(maxatac_tmp_dir): @@ -166,7 +237,7 @@ def run_data(args): commit = subprocess.run(["git", "rev-parse", "HEAD"], cwd=maxatac_final_dir, capture_output=True, text=True).stdout.strip() - logging.info(f"Installed {args.data_repo} at commit {commit}") + logging.info(f"Installed {args.data_repo} {data_label} at commit {commit}") for genome in genomes: genome_dir = os.path.join(maxatac_final_dir, genome) diff --git a/maxatac/utilities/benchmarking_tools.py b/maxatac/utilities/benchmarking_tools.py index 3e2f4b1..523281f 100644 --- a/maxatac/utilities/benchmarking_tools.py +++ b/maxatac/utilities/benchmarking_tools.py @@ -6,7 +6,7 @@ from maxatac.utilities.genome_tools import load_bigwig, chromosome_blacklist_mask, chromosome_whitelist_mask, import_prediction_array_fn, import_quant_goldstandard_array_fn from sklearn import metrics from sklearn.metrics import precision_recall_curve, r2_score, mean_absolute_error -from scipy import stats +from scipy import stats, special from scipy.stats import pearsonr, spearmanr from maxatac.utilities.system_tools import remove_tags import pybedtools @@ -100,6 +100,10 @@ def __init__(self, self.quant_gs_null = quant_gs_null # change to quant_null_model self.prediction_combine_operation = prediction_combine_operation + if prediction_combine_operation == "rank_max": + raise ValueError("prediction_combine_operation rank_max is for the precision-recall benchmark only; " + "R2, Pearson and Spearman need prediction values, not percentile ranks") + # This has been modified self.blacklist_mask = chromosome_blacklist_mask(blacklist_bw, self.chromosome, @@ -441,6 +445,73 @@ def precision_recall_curve_peak_based(y_member, y_score): # return precision, recall, thresholds +def random_ucper_curve(y_member, n_points=2000): + """ + Expected precision vs unique-peak recall curve of a random ranking, built the same way as + precision_recall_curve_peak_based. + + Unlike bin-level AUPRC the random curve is not flat. A peak counts once however many of its bins + are called, so precision starts at positive bins / bins (P/N) and falls to M/(M+Q) as peaks + saturate (M peaks, Q negative bins). + + After k randomly ranked bins (drawn without replacement), a peak of s bins is hit with probability + 1 - C(N-s, k)/C(N, k), so E[TP_k] = sum over peaks of that, and E[FP_k] = k*Q/N. + + :param y_member: member array from peak_gs_array_to_member_array (peak ids > 0, negative bins < 0) + :param n_points: number of k values, geometrically spaced from 1 to N + :return: DataFrame with 'Precision' and 'Recall' columns in increasing recall, None when there are no peaks + """ + y_member = np.asarray(y_member) + n_bins = len(y_member) + n_negative = np.count_nonzero(y_member < 0) + + _, peak_sizes = np.unique(y_member[y_member > 0], return_counts=True) + n_peaks = len(peak_sizes) + if n_peaks == 0: + return None + + # Peaks of the same size share the same hit probability + sizes, size_counts = np.unique(peak_sizes, return_counts=True) + + k = np.unique(np.geomspace(1, n_bins, n_points).astype(int)).astype(float) + + # log C(N-s, k) - log C(N, k); a peak is certainly hit once k > N - s + remaining = n_bins - sizes[:, None] - k[None, :] + log_miss = (special.gammaln(n_bins - sizes[:, None] + 1) - special.gammaln(np.maximum(remaining, 0) + 1) + - special.gammaln(n_bins + 1) + special.gammaln(n_bins - k[None, :] + 1)) + miss = np.where(remaining >= 0, np.exp(log_miss), 0.0) + + expected_tp = (size_counts[:, None] * (1 - miss)).sum(axis=0) + expected_fp = k * n_negative / n_bins + + return pd.DataFrame({'Precision': expected_tp / (expected_tp + expected_fp), + 'Recall': expected_tp / n_peaks}) + +def random_aup_ucper(y_member, n_points=2000): + """ + Expected AUP-UCPeR of a random ranking: the area under random_ucper_curve. + + :return: random AUP-UCPeR, NaN when there are no peaks + """ + curve = random_ucper_curve(y_member, n_points) + if curve is None: + return np.nan + + return metrics.auc(x=curve['Recall'], y=curve['Precision']) + +def random_precision_at_ucper(y_member, percent_recall, n_points=2000): + """ + Expected precision of a random ranking at a given unique-peak recall, read off random_ucper_curve + with the same interpolation as Precision_for_Recall. + + :return: random precision at percent_recall, NaN when there are no peaks + """ + curve = random_ucper_curve(y_member, n_points) + if curve is None: + return np.nan + + return Precision_for_Recall(curve, percent_recall) + class ChromosomeAUPRC(object): """ Benchmark maxATAC binary predictions against a gold standard using AUPRC. @@ -466,7 +537,8 @@ def __init__(self, plot=False, peak_based=False, alternative_prediction_bw=None, - prediction_combine_operation="mean" + prediction_combine_operation="mean", + random_only=False ): """ :param prediction_bw: Path to bigwig file containing maxATAC predictions @@ -475,11 +547,16 @@ def __init__(self, :param chromosome: Chromosome to benchmark :param bin_size: Resolution to bin the results to :param agg_function: Method to use to aggregate multiple signals in the same bin + :param random_only: With peak_based, only write the random AUP-UCPeR and P@10%UCPeR; the prediction is not read """ + if random_only and not peak_based: + raise ValueError("random_only requires peak_based") + self.results_location = results_location - self.prediction_stream = load_bigwig(prediction_bw) - self.alternative_prediction_stream = load_bigwig(alternative_prediction_bw) if alternative_prediction_bw else None + if not random_only: + self.prediction_stream = load_bigwig(prediction_bw) + self.alternative_prediction_stream = load_bigwig(alternative_prediction_bw) if alternative_prediction_bw else None self.goldstandard_stream = load_bigwig(goldstandard_bw) self.chromosome = chromosome @@ -507,6 +584,12 @@ def __init__(self, ) self.peak_based=peak_based + + if random_only: + self.__import_goldstandard_array__() + self.__random_UCPeR__() + return + self.__import_prediction_array__(round_prediction=round_predictions) self.__import_goldstandard_array__() self.__AUPRC__() @@ -515,6 +598,19 @@ def __init__(self, logging.info("Plotting AUPRC Curves") self.__plot() + def __random_UCPeR__(self): + """ + Write only the random baselines of the peak-based benchmark: Random AUP-UCPeR and Random P@10%UCPeR. + Both depend on the gold standard, bin size and mask alone, so no prediction is needed. + """ + logging.info("Calculate random AUP-UCPeR and P@10%UCPeR for " + self.chromosome) + + member_array = peak_gs_array_to_member_array(self.goldstandard_array[self.blacklist_mask]) + + pd.DataFrame({'Random_AUPRC': [random_aup_ucper(member_array)], + 'Random_Precision_at_10_Percent_Recall': [random_precision_at_ucper(member_array, 0.1)]} + ).to_csv(self.results_location, sep='\t', index=False) + def __import_prediction_array__(self, round_prediction=6): """ Import the chromosome signal from the predictions bigwig file and convert to a numpy array. @@ -535,8 +631,10 @@ def __import_prediction_array__(self, round_prediction=6): combine_operation=self.prediction_combine_operation) # Under "sum" the bin value is a base-pair total; divide by bin_size to stay on the - # same per-base scale as max/mean. - if self.agg_function == "sum": + # same per-base scale as max/mean. rank_max is already a percentile, and dividing it would let + # the rounding below merge neighbouring ranks into ties + if self.agg_function == "sum" and not (self.alternative_prediction_stream is not None + and self.prediction_combine_operation == "rank_max"): self.prediction_array = self.prediction_array / self.bin_size self.prediction_array = np.round(self.prediction_array, round_prediction) @@ -571,7 +669,7 @@ def __import_goldstandard_array__(self): self.goldstandard_array = self.goldstandard_array > 0 self.random_precision = np.count_nonzero(self.goldstandard_array[self.blacklist_mask]) / \ - np.size(self.prediction_array[self.blacklist_mask]) + np.count_nonzero(self.blacklist_mask) def __get_true_positives__(self, threshold): """ @@ -646,8 +744,9 @@ def __AUPRC__(self): ) else: # generate member array from gs + member_array = peak_gs_array_to_member_array(self.goldstandard_array[self.blacklist_mask]) self.precision, self.recall, self.thresholds = precision_recall_curve_peak_based( - peak_gs_array_to_member_array(self.goldstandard_array[self.blacklist_mask]), + member_array, self.prediction_array[self.blacklist_mask] ) logging.info("Making DataFrame from results") @@ -668,23 +767,38 @@ def __AUPRC__(self): self.PR_CURVE_DF["AUPRC"] = self.AUPRC if self.peak_based==False: - # Calculate the total gold standard bins + # Count gold standard bins with the same mask as the PR curve (blacklist removed, whitelist applied). + # Counting them chromosome wide while dividing by the evaluated bins inflates the random baseline, + # above 1 with a small whitelist logging.info("Calculate Total GoldStandard Bins") - self.PR_CURVE_DF["Total_GoldStandard_Bins"] = len(np.argwhere(self.goldstandard_array == True)) + self.PR_CURVE_DF["Total_GoldStandard_Bins"] = np.count_nonzero(self.goldstandard_array[self.blacklist_mask]) - # Find the number of non-blacklisted bins in chr of interest - rand_bins = len(np.argwhere(self.blacklist_mask == True)) - - # Random Precision - self.PR_CURVE_DF['Random_AUPRC'] = self.PR_CURVE_DF['Total_GoldStandard_Bins'] / rand_bins + # Random Precision: gold standard bins / evaluated bins, i.e. self.random_precision + self.PR_CURVE_DF['Random_AUPRC'] = self.random_precision # Log2FC self.PR_CURVE_DF['log2FC_AUPRC_Random_AUPRC'] = np.log2(self.PR_CURVE_DF["AUPRC"] / self.PR_CURVE_DF["Random_AUPRC"]) + else: + # Peaks and bins counted with the same mask as the AUP-UCPeR curve + self.PR_CURVE_DF["Total_GoldStandard_Bins"] = np.count_nonzero(member_array > 0) + self.PR_CURVE_DF["Total_GoldStandard_Peaks"] = len(np.unique(member_array[member_array > 0])) + + # Random AUP-UCPeR: area under the expected random curve, not the flat bin-level ratio + self.PR_CURVE_DF['Random_AUPRC'] = random_aup_ucper(member_array) + + self.PR_CURVE_DF['log2FC_AUPRC_Random_AUPRC'] = np.log2(self.PR_CURVE_DF["AUPRC"] / self.PR_CURVE_DF["Random_AUPRC"]) # Precision at 10% Recall self.PR_CURVE_DF['Precision_at_10_Percent_Recall']=Precision_for_Recall(self.PR_CURVE_DF, 0.1) + if self.peak_based: + # Random P@10%UCPeR: the expected random curve read at 10% unique-peak recall + self.PR_CURVE_DF['Random_Precision_at_10_Percent_Recall'] = random_precision_at_ucper(member_array, 0.1) + + self.PR_CURVE_DF['log2FC_Precision_at_10_Percent_Recall_Random'] = np.log2( + self.PR_CURVE_DF['Precision_at_10_Percent_Recall'] / self.PR_CURVE_DF['Random_Precision_at_10_Percent_Recall']) + logging.info("Write results for " + self.chromosome) # Write the AUPRC stats to a dataframe diff --git a/maxatac/utilities/genome_tools.py b/maxatac/utilities/genome_tools.py index 114711d..84eeac5 100644 --- a/maxatac/utilities/genome_tools.py +++ b/maxatac/utilities/genome_tools.py @@ -1,5 +1,7 @@ +import logging import pandas as pd import numpy as np +from scipy.stats import rankdata import pyBigWig import py2bit import random @@ -214,13 +216,51 @@ def import_bigwig_stats_array(bigwig_stream, chromosome, chromosome_length, agg_ dtype=float) +def _pct_rank(array): + """ + Percentile rank of each bin across the whole array: rankdata(method="min") / number of bins. + NaN (missing) bins are set to 0 first, and every zero-valued bin gets percentile 0, so the + many zero bins of a sparse track cannot outrank low but nonzero bins of the other track. + """ + array = np.nan_to_num(np.asarray(array, dtype=float)) + if array.size == 0: + return array + + percentile = rankdata(array, method="min") / array.size + percentile[array == 0] = 0.0 + + return percentile + + +def _log_max_source(primary_array, alternative_array, combine_operation): + """ + Sanity check for a max combine: how often each track supplies the max. Near 0% or 100% means + the ensemble is effectively just one of the two inputs. + """ + n_bins = primary_array.size + if n_bins == 0: + return + + primary_wins = np.count_nonzero(primary_array > alternative_array) / n_bins + alternative_wins = np.count_nonzero(alternative_array > primary_array) / n_bins + + logging.info("%s combine: primary supplies the max in %.2f%% of bins, alternative in %.2f%%, tied in %.2f%%", + combine_operation, 100 * primary_wins, 100 * alternative_wins, + 100 * (1 - primary_wins - alternative_wins)) + + def combine_prediction_arrays(primary_array, alternative_array=None, combine_operation="mean"): """ Combine two prediction arrays element-wise. - Whenever both arrays contain values for the same bin, combine them using either the + mean / max: whenever both arrays contain values for the same bin, combine them using either the element-wise mean or max. If only one array has a value for a bin, use the available value. If neither has a value, return 0 for that position. + + rank_max: convert each array to percentile ranks across all of its bins (_pct_rank), then take the + element-wise max. Missing bins get percentile 0, so the other track's value is used, which is the + same missing-value rule as max. Rank before any masking: the result does not depend on the + blacklist or whitelist. """ primary_array = np.array(primary_array, dtype=float) if alternative_array is None: @@ -231,8 +271,15 @@ def combine_prediction_arrays(primary_array, alternative_array=None, combine_ope if primary_array.shape != alternative_array.shape: raise ValueError("Prediction arrays must have the same shape to be combined.") - if combine_operation not in {"mean", "max"}: - raise ValueError("combine_operation must be either 'mean' or 'max'.") + if combine_operation not in {"mean", "max", "rank_max"}: + raise ValueError("combine_operation must be one of 'mean', 'max' or 'rank_max'.") + + if combine_operation == "rank_max": + primary_percentile = _pct_rank(primary_array) + alternative_percentile = _pct_rank(alternative_array) + _log_max_source(primary_percentile, alternative_percentile, combine_operation) + + return np.maximum(primary_percentile, alternative_percentile) primary_available = ~np.isnan(primary_array) alternative_available = ~np.isnan(alternative_array) @@ -246,6 +293,8 @@ def combine_prediction_arrays(primary_array, alternative_array=None, combine_ope combined[both_available] = (primary_array[both_available] + alternative_array[both_available]) / 2.0 else: combined[both_available] = np.maximum(primary_array[both_available], alternative_array[both_available]) + _log_max_source(np.nan_to_num(primary_array, nan=-np.inf), np.nan_to_num(alternative_array, nan=-np.inf), + combine_operation) return np.nan_to_num(combined) diff --git a/maxatac/utilities/parser.py b/maxatac/utilities/parser.py index a91d135..0f8153f 100644 --- a/maxatac/utilities/parser.py +++ b/maxatac/utilities/parser.py @@ -149,6 +149,17 @@ def get_parser(): "Default: " + MAXATAC_DATA_REPO ) + data_parser.add_argument("--data_version", + dest="data_version", + type=str, + default=None, + required=False, + help="Tag or branch of the data repository to install (e.g. v2.0.0b1), or 'latest' " + "for the newest commit on its default branch. Default: the tag matching this " + "quant-maxATAC version (" + get_version() + "); development versions and " + "versions without a matching tag install the latest data." + ) + data_parser.add_argument("-y", "--yes", dest="yes", action="store_true", @@ -203,10 +214,11 @@ def get_parser(): # Add optional arguments to the parser + # dest must be chrom_sizes: update_reference_genome_paths fills that attribute from --genome when unset average_parser.add_argument("-cs", "--chrom_sizes", "--chromosome_sizes", - dest="chromosome_sizes", + dest="chrom_sizes", type=str, - help="Input chromosome sizes file" + help="Input chromosome sizes file. Default: the chromosome sizes of --genome" ) average_parser.add_argument("-c", "--chroms", "--chromosomes", @@ -856,7 +868,8 @@ def get_parser(): # Add arguments to the parser # Add arguments to the parser - benchmark_prediction_filetype = benchmark_parser.add_mutually_exclusive_group(required=True) + # Required unless --random (checked in parse_arguments): the random baselines do not read the prediction + benchmark_prediction_filetype = benchmark_parser.add_mutually_exclusive_group(required=False) benchmark_prediction_filetype.add_argument("-bed", "--bed", dest="prediction", @@ -880,9 +893,12 @@ def get_parser(): benchmark_parser.add_argument("--prediction_combine_operation", dest="prediction_combine_operation", type=str, - choices=["mean", "max"], + choices=["mean", "max", "rank_max"], default="mean", - help="How to combine bins from the primary and alternative prediction bigWig files when both provide a value. Default: mean" + help="How to combine bins from the primary and alternative prediction bigWig files. " + "mean / max combine raw values where both provide one. rank_max converts each " + "track to per-chromosome percentile ranks (zero and missing bins get 0) and " + "takes the max; precision-recall benchmark only, not with --quant. Default: mean" ) benchmark_parser.add_argument("--quant_gold_standard", @@ -918,6 +934,16 @@ def get_parser(): "Binary benchmark only." ) + benchmark_parser.add_argument("--random", + dest="random", + action='store_true', + default=False, + help="With --peak_based, compute only the random baselines, Random AUP-UCPeR and " + "Random P@10%%UCPeR, from the gold standard, bin size and blacklist/whitelist. " + "The prediction is not read, so --bw/--bed is optional. Writes " + "__bp_random_UCPeR.tsv instead of the PRC file." + ) + benchmark_parser.add_argument("--quant", dest="quant", action='store_true', @@ -1405,7 +1431,7 @@ def get_parser(): help="Tab-separated meta file with one row per cell type and columns 'Prediction' " "(prediction bigWig, quantitative or binary) and 'Binding_File' (binary gold " "standard bigWig). Optional column 'ChIP_peaks' (ChIP-seq peak BED) defines the " - "unique peaks for the Peak_Recall (% of peaks recovered) metric; without it, " + "unique peaks for the Peak_Recall (%% of peaks recovered) metric; without it, " "runs of consecutive gold-standard bins are used." ) @@ -1467,6 +1493,20 @@ def parse_arguments(argsl, cwd_abs_path=None): parser.error("threshold calibrates on exactly one chromosome; got --chromosomes " + " ".join(args.chromosomes)) + if args.func == run_benchmarking: + if args.random and not args.peak_based: + parser.error("--random requires --peak_based") + + if args.quant and args.prediction_combine_operation == "rank_max": + parser.error("--prediction_combine_operation rank_max is for the precision-recall benchmark; " + "it cannot be combined with --quant") + + if args.random and args.quant: + parser.error("--random is for the peak-based binary benchmark; it cannot be combined with --quant") + + if not args.random and not args.prediction: + parser.error("one of the arguments -bed/--bed --bw/--bigwig/-bw is required") + if args.func == run_benchmarking and args.quant: missing = [flag for flag, value in (("--quant_gold_standard", args.quant_gold_standard), ("--quant_gs_null", args.quant_gs_null)) if not value] diff --git a/maxatac/utilities/peak_tools.py b/maxatac/utilities/peak_tools.py index 0d8a31c..e74342e 100644 --- a/maxatac/utilities/peak_tools.py +++ b/maxatac/utilities/peak_tools.py @@ -74,8 +74,9 @@ def get_threshold(cutoff_file, cutoff_type, cutoff_val): cutoff_type (str): Which metric's bin grid to look the threshold up on. One of Precision, Recall, F1, Peak_Recall (fraction of unique ChIP-seq peaks recovered). - cutoff_val (float): Target value on that metric's grid. Optional for F1, where - omitting it selects the threshold with the highest F1. + cutoff_val (float): Target value of that metric. The row used must achieve it in its + metric column (not only in its Bin label). Optional for F1, where omitting it + selects the threshold with the highest F1. Returns: float: The threshold to apply to prediction scores. @@ -106,16 +107,18 @@ def get_threshold(cutoff_file, cutoff_type, cutoff_val): if cutoff_val is None: raise ValueError(f"A cutoff value is required for cutoff type {cutoff_type}.") - # Ceiling on the bin grid: the lowest bin that still meets the requested value. - reachable = rows[rows["Bin"] >= cutoff_val].sort_values("Bin") + # The achieved value must meet the request: grid bins past a curve's range hold its + # nearest real row, so the Bin label alone can promise a value no threshold reaches. + reachable = rows[rows[cutoff_type] >= cutoff_val] if reachable.empty: raise ValueError( f"{cutoff_file} does not reach {cutoff_type} {cutoff_val}; " - f"its highest {cutoff_type} bin is {rows['Bin'].max()}." + f"the highest {cutoff_type} it reaches is {rows[cutoff_type].max():.3f}." ) - selected = reachable.iloc[0] + # Closest to the request; ties go to the higher F1 + selected = reachable.sort_values([cutoff_type, "F1"], ascending=[True, False]).iloc[0] achieved_peak_recall = (f"\n Achieved Peak_Recall: {selected['Peak_Recall']}" if "Peak_Recall" in selected.index else "") diff --git a/maxatac/utilities/plot.py b/maxatac/utilities/plot.py index f6220ae..ab73f09 100644 --- a/maxatac/utilities/plot.py +++ b/maxatac/utilities/plot.py @@ -302,7 +302,10 @@ def plot_threshold_calibration_stats(median_curve, cell_type_curves, file_locati ct_curve = ct["curves"][metric_key] ax.plot(ct_curve["Threshold"], ct_curve[col], c=color, lw=1.2, alpha=0.85, label=ct["name"]) if metric_filter is not None: - panel_median = median_curve[median_curve["Metric"] == metric_filter].sort_values("Threshold") + # Bins past some cell types' range can share a median Threshold; break ties on Bin in + # the metric's own direction (Precision rises, Recall/Peak_Recall fall with threshold) + panel_median = median_curve[median_curve["Metric"] == metric_filter].sort_values( + ["Threshold", "Bin"], ascending=[True, metric_filter == "Precision"], kind="mergesort") ax.plot(panel_median["Threshold"], panel_median[col], c="black", lw=3, label="Median") ax.set_title(f"{chrom_name} Validation {label} v. Thresholds", size="medium") ax.set_xlabel("Threshold", size="medium") diff --git a/maxatac/utilities/system_tools.py b/maxatac/utilities/system_tools.py index d313ce8..6dea4af 100644 --- a/maxatac/utilities/system_tools.py +++ b/maxatac/utilities/system_tools.py @@ -1,5 +1,5 @@ import logging -import pkg_resources +from importlib import metadata import os import sys import subprocess @@ -58,8 +58,12 @@ def get_rootname(l): def get_version(): - pkg = pkg_resources.require("maxatac") - return pkg[0].version if pkg else "unknown version" + # importlib.metadata: pkg_resources was removed from recent setuptools releases + try: + return metadata.version("maxatac") + + except metadata.PackageNotFoundError: + return "unknown version" def remove_tags(l, tags): diff --git a/maxatac/utilities/threshold_tools.py b/maxatac/utilities/threshold_tools.py index fdbfb1e..86331df 100644 --- a/maxatac/utilities/threshold_tools.py +++ b/maxatac/utilities/threshold_tools.py @@ -166,28 +166,32 @@ def calculate_AUC_per_rank(PR_CURVE_DF, threshold): def compute_calibration_curve(goldstandard, prediction, gs_bins=None, rand_bins=None, peak_max=None): """ - Build a monotonic Precision/Recall/Threshold calibration curve (plus F1) for one - goldstandard/prediction pair. log2FC is added only when gs_bins and rand_bins are given; - Peak_Recall (fraction of unique ChIP-seq peaks recovered) only when peak_max, the - per-peak max prediction from peak_max_predictions(), is given. + Build a Precision/Recall/Threshold calibration curve (plus F1) for one goldstandard/prediction + pair. Every row is a real threshold with the metrics it actually achieves. log2FC is added only + when gs_bins and rand_bins are given; Peak_Recall (fraction of unique ChIP-seq peaks recovered) + only when peak_max, the per-peak max prediction from peak_max_predictions(), is given. + + Only thresholds on the precision-recall frontier are kept: a threshold is dropped when a lower + threshold reaches the same or a higher precision, since that one also has at least the recall + (and Peak_Recall). The kept rows are monotonic in threshold without changing any value. + sklearn's terminal (Precision=1, Recall=0) point has no threshold and is dropped. """ precision, recall, thresholds = precision_recall_curve(goldstandard, prediction) - P = np.maximum.accumulate(np.array(precision)) - R = np.minimum.accumulate(np.array(recall)) + # precision/recall have one more entry than thresholds: the terminal sentinel + precision = np.asarray(precision[:-1]) + recall = np.asarray(recall[:-1]) + + # Thresholds ascend: keep a point only if it beats the precision of every lower threshold + best_below = np.concatenate(([-np.inf], np.maximum.accumulate(precision)[:-1])) + keep = precision > best_below + + curve_df = pd.DataFrame({'Precision': precision[keep], + 'Recall': recall[keep], + 'Threshold': np.asarray(thresholds)[keep]}) - # sklearn returns one fewer threshold than precision/recall; label the terminal - # sentinel row (P=1, R=0) with the last real threshold. - threshold_col = np.append(thresholds, thresholds[-1]) - curve_df = pd.DataFrame({'Precision': P, 'Recall': R, "Threshold": threshold_col}) if peak_max is not None: - peak_recall = peak_recall_at_thresholds(peak_max, threshold_col) - # The sentinel row stands for "above every threshold" (Recall=0); match it - peak_recall[-1] = 0.0 - curve_df[PEAK_RECALL] = peak_recall - # Duplicate the last row rather than forcing Threshold=1 (quant predictions can exceed 1) - new_row = curve_df.tail(n=1) - curve_df = pd.concat([curve_df, new_row], ignore_index=True) + curve_df[PEAK_RECALL] = peak_recall_at_thresholds(peak_max, curve_df['Threshold']) if gs_bins is not None and rand_bins is not None: random_precision = gs_bins / rand_bins diff --git a/maxatac/utilities/training_tools.py b/maxatac/utilities/training_tools.py index 9dba423..b24b6fd 100644 --- a/maxatac/utilities/training_tools.py +++ b/maxatac/utilities/training_tools.py @@ -13,7 +13,7 @@ from maxatac.architectures.dcnn import get_dilated_cnn from maxatac.utilities.constants import BP_RESOLUTION, BATCH_SIZE, CHR_POOL_SIZE, INPUT_LENGTH, INPUT_CHANNELS, \ - BP_ORDER, TRAIN_SCALE_SIGNAL, BINARY_TARGET_MIN_PEAK_FRACTION + BP_ORDER, BINARY_TARGET_MIN_PEAK_FRACTION from maxatac.utilities.genome_tools import load_bigwig, load_2bit, get_one_hot_encoded, build_chrom_sizes_dict from maxatac.utilities.system_tools import get_dir, remove_tags, replace_extension @@ -38,7 +38,7 @@ def __init__(self, meta_path, weights, dense=False, - target_scale_factor=TRAIN_SCALE_SIGNAL, + target_scale_factor=1, output_activation="sigmoid", quant=False, interpret=False, @@ -95,7 +95,7 @@ def __init__(self, self.nn_model = self.__get_model() if interpret: - assert (interpret_cell_type is not None, "Set the interpretation cell type argument") + assert interpret_cell_type is not None, "Set the interpretation cell type argument" self.interpret_cell_type = interpret_cell_type self.__get_interpretation_attributes() diff --git a/setup.py b/setup.py index 216d699..8f4f6ac 100644 --- a/setup.py +++ b/setup.py @@ -1,46 +1,50 @@ #! /usr/bin/env python3 import os -import time import subprocess from setuptools import setup, find_packages GIT_VERSION_FILE = os.path.join("maxatac", "git_version") HERE = os.path.abspath(os.path.dirname(__file__)) +# Version of an untagged commit. A development version makes `maxatac data` install the latest data +DEV_VERSION = "2.0.0.dev0" -def get_git_tag(): - return subprocess.check_output(["git", "describe", "--contains"], text=True).split("^")[0].strip() - -def get_git_timestamp(): - gitinfo = subprocess.check_output( - ["git", "log", "--first-parent", "--max-count=1", "--format=format:%ct", "."], text=True).strip() - return time.strftime("%Y%m%d%H%M%S", time.gmtime(int(gitinfo))) +def git(*args): + return subprocess.check_output(["git", *args], cwd=HERE, text=True, stderr=subprocess.DEVNULL).strip() def get_version(): """ Tries to get package version with following order: - 0. default version - 1. from git_version file - when installing from pip, this is the only source to get version - 2. from tag - 3. from commit timestamp + 1. in a git checkout: the tag on the current commit without its leading "v" (v2.0.0b1 -> 2.0.0b1), + or DEV_VERSION if the commit is not tagged + 2. outside git (installing from an sdist): the git_version file written when the sdist was built + 3. DEV_VERSION + Tags must be PEP 440 versions: `maxatac data` installs the data repository tag of the same name. Updates/creates git_version file with the package version Returns package version """ - version = "1.9.2" # default version - try: - with open(GIT_VERSION_FILE, "r") as input_stream: # try to get version info from file - version = input_stream.read() - except Exception: - pass + version = DEV_VERSION try: - version = get_git_tag() # try to get version info from the closest tag + git("rev-parse", "--git-dir") + in_git = True except Exception: + in_git = False + + if in_git: + try: + tag = git("describe", "--tags", "--exact-match") + version = tag[1:] if tag.startswith("v") else tag + except Exception: + pass + + else: try: - version = "1.9.2" # try to get version info from commit date + with open(GIT_VERSION_FILE, "r") as input_stream: + version = input_stream.read().strip() or DEV_VERSION except Exception: pass @@ -54,7 +58,7 @@ def get_version(): def get_description(): README = os.path.join(HERE, "README.md") - with open(README, "r") as f: + with open(README, "r", encoding="utf-8") as f: return f.read() setup( diff --git a/tests/e2e/baseline.json b/tests/e2e/baseline.json new file mode 100644 index 0000000..5af24a1 --- /dev/null +++ b/tests/e2e/baseline.json @@ -0,0 +1,13 @@ +{ + "_comment": "Reference metrics for tests/e2e/run_e2e.sh (GM12878 CTCF, chr1:1,000,000-11,000,000). null = not seeded yet: copy the values from the metrics.json artifact of a green run. A run fails when a metric drops below baseline - tolerance.", + "metrics": { + "AUPRC": null, + "pearson": null, + "spearman": null + }, + "tolerance": { + "AUPRC": 0.02, + "pearson": 0.03, + "spearman": 0.03 + } +} diff --git a/tests/e2e/check_outputs.py b/tests/e2e/check_outputs.py new file mode 100644 index 0000000..10c5319 --- /dev/null +++ b/tests/e2e/check_outputs.py @@ -0,0 +1,245 @@ +#!/usr/bin/env python3 +"""Output checks for the end-to-end test (tests/e2e/run_e2e.sh) + +Subcommands: + data the reference files and the TF model installed by `maxatac data` are present + whitelist write a bigWig that is 1 over the ROI, used to restrict `maxatac benchmark` to it + prediction the prediction bigWig and peaks look sane over the ROI + report collect the metrics, compare them with the baseline and write a summary +""" +import argparse +import glob +import json +import os +import sys + +import numpy as np +import pandas as pd +import pyBigWig +from scipy import stats + +BIN_SIZE = 200 + + +def fail(message): + # ::error:: is shown as an annotation on GitHub Actions and is plain text elsewhere + print(f"::error::{message}") + sys.exit(1) + + +def read_roi(roi_path): + """Return (chrom, start, end) of the first interval in a BED file""" + with open(roi_path) as roi: + chrom, start, end = roi.readline().split("\t")[:3] + + return chrom, int(start), int(end) + + +def binned_stats(bigwig_path, chrom, start, end, agg="mean", bin_size=BIN_SIZE): + """Aggregate a bigWig into fixed bins over [start, end); bins without data are NaN""" + n_bins = (end - start) // bin_size + bigwig = pyBigWig.open(bigwig_path) + + try: + values = bigwig.stats(chrom, start, start + n_bins * bin_size, type=agg, nBins=n_bins) + + finally: + bigwig.close() + + return np.array(values, dtype=float) + + +def check_data(args): + genome_dir = os.path.join(args.data_dir, args.genome) + required = [os.path.join(genome_dir, f"{args.genome}.chrom.sizes"), + os.path.join(genome_dir, f"{args.genome}_maxatac_blacklist.bed"), + os.path.join(genome_dir, f"{args.genome}_maxatac_blacklist.bw"), + os.path.join(genome_dir, f"{args.genome}.2bit")] + + for path in required: + if not os.path.isfile(path) or os.path.getsize(path) == 0: + fail(f"`maxatac data` did not install {path}") + + model_dir = os.path.join(args.data_dir, "models", args.tf) + models = glob.glob(os.path.join(model_dir, f"{args.tf}*.h5")) + tables = glob.glob(os.path.join(model_dir, f"{args.tf}*_cross_celltype.tsv")) + + if not models: + fail(f"No {args.tf} model (*.h5) in {model_dir}") + + if not tables: + fail(f"No {args.tf} threshold calibration table (*_cross_celltype.tsv) in {model_dir}") + + print(f"Reference data OK: {genome_dir}") + print(f"Model: {models[0]}") + print(f"Calibration table: {tables[0]}") + + +def write_whitelist(args): + chrom, start, end = read_roi(args.roi) + chrom_sizes = pd.read_csv(args.chrom_sizes, sep="\t", header=None, index_col=0)[1] + + whitelist = pyBigWig.open(args.out, "w") + whitelist.addHeader([(chrom, int(chrom_sizes[chrom]))]) + whitelist.addEntries([chrom], [start], ends=[end], values=[1.0]) + whitelist.close() + + print(f"Wrote {args.out}: {chrom}:{start}-{end}") + + +def check_prediction(args): + if not os.path.isfile(args.prediction): + fail(f"`maxatac predict` did not write {args.prediction}") + + chrom, start, end = read_roi(args.roi) + + prediction = pyBigWig.open(args.prediction) + chroms = prediction.chroms() + prediction.close() + + if chrom not in chroms: + fail(f"{args.prediction} has no {chrom}; chromosomes: {list(chroms)}") + + values = binned_stats(args.prediction, chrom, start, end, agg="max") + covered = np.isfinite(values) + + # Blacklisted windows are not predicted, so full coverage is not expected + if covered.mean() < 0.5: + fail(f"Only {covered.mean():.1%} of the {BIN_SIZE} bp bins in the ROI have a prediction") + + covered_values = values[covered] + + if covered_values.min() < 0: + fail(f"Negative prediction scores (min {covered_values.min():.4g}); the quant models end in softplus") + + if np.std(covered_values) == 0: + fail(f"The prediction is constant ({covered_values[0]:.4g}) over the ROI") + + if not os.path.isfile(args.peaks) or os.path.getsize(args.peaks) == 0: + fail(f"`maxatac predict` called no peaks: {args.peaks} is missing or empty") + + peaks = pd.read_csv(args.peaks, sep="\t", header=None, usecols=[0, 1, 2]) + + print(f"Prediction OK: {covered.mean():.1%} of bins covered, " + f"score range {covered_values.min():.4g}-{covered_values.max():.4g}, {len(peaks)} peaks") + + +def report(args): + chrom, start, end = read_roi(args.roi) + + prc = pd.read_csv(args.prc, sep="\t") + metrics = {"AUPRC": float(prc["AUPRC"].iloc[0])} + + if "Random_AUPRC" in prc.columns: + metrics["Random_AUPRC"] = float(prc["Random_AUPRC"].iloc[0]) + + # Interim quantitative check until a null track for `maxatac benchmark --quant` is in the test data + prediction = binned_stats(args.prediction, chrom, start, end, agg="mean") + observed = binned_stats(args.quant_gold_standard, chrom, start, end, agg="mean") + blacklisted = binned_stats(args.blacklist_bw, chrom, start, end, agg="max") > 0 + + # Bins without gold standard signal are 0, not missing + observed = np.nan_to_num(observed, nan=0.0) + keep = np.isfinite(prediction) & ~blacklisted + + metrics["pearson"] = float(stats.pearsonr(prediction[keep], observed[keep])[0]) + metrics["spearman"] = float(stats.spearmanr(prediction[keep], observed[keep])[0]) + metrics["n_bins"] = int(keep.sum()) + + failures = [] + + if "Random_AUPRC" in metrics and metrics["AUPRC"] <= metrics["Random_AUPRC"]: + failures.append(f"AUPRC {metrics['AUPRC']:.4f} is not above random ({metrics['Random_AUPRC']:.4f})") + + if metrics["pearson"] <= 0: + failures.append(f"Pearson correlation with the quantitative gold standard is {metrics['pearson']:.4f}") + + with open(args.baseline) as baseline_file: + baseline = json.load(baseline_file) + + rows = [] + + for name, reference in baseline["metrics"].items(): + tolerance = baseline["tolerance"][name] + value = metrics[name] + + if reference is None: + status = "no baseline" + + elif value < reference - tolerance: + status = "REGRESSED" + failures.append(f"{name} {value:.4f} is below the baseline {reference:.4f} - {tolerance}") + + else: + status = "ok" + + rows.append(f"| {name} | {value:.4f} | {'-' if reference is None else f'{reference:.4f}'} | {status} |") + + with open(args.metrics_out, "w") as metrics_file: + json.dump(metrics, metrics_file, indent=2) + + summary = "\n".join([f"### quant-maxATAC e2e: GM12878 {chrom}:{start:,}-{end:,}", + "", + "| Metric | Value | Baseline | Status |", + "|---|---|---|---|", + *rows, + "", + f"Random AUPRC: {metrics.get('Random_AUPRC', float('nan')):.4f}; " + f"{metrics['n_bins']} {BIN_SIZE} bp bins outside the blacklist", + ""]) + + print(summary) + + # Also kept as a file: release.yml puts it in the GitHub Release notes + with open(os.path.splitext(args.metrics_out)[0] + ".md", "w") as summary_file: + summary_file.write(summary) + + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as step_summary: + step_summary.write(summary + "\n") + + for failure in failures: + print(f"::error::{failure}") + + if failures: + sys.exit(1) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + subparsers = parser.add_subparsers(dest="command", required=True) + + data = subparsers.add_parser("data") + data.add_argument("--data_dir", required=True) + data.add_argument("--genome", required=True) + data.add_argument("--tf", required=True) + data.set_defaults(func=check_data) + + whitelist = subparsers.add_parser("whitelist") + whitelist.add_argument("--roi", required=True) + whitelist.add_argument("--chrom_sizes", required=True) + whitelist.add_argument("--out", required=True) + whitelist.set_defaults(func=write_whitelist) + + prediction = subparsers.add_parser("prediction") + prediction.add_argument("--prediction", required=True) + prediction.add_argument("--peaks", required=True) + prediction.add_argument("--roi", required=True) + prediction.set_defaults(func=check_prediction) + + metrics = subparsers.add_parser("report") + metrics.add_argument("--prc", required=True) + metrics.add_argument("--prediction", required=True) + metrics.add_argument("--quant_gold_standard", required=True) + metrics.add_argument("--blacklist_bw", required=True) + metrics.add_argument("--roi", required=True) + metrics.add_argument("--baseline", required=True) + metrics.add_argument("--metrics_out", required=True) + metrics.set_defaults(func=report) + + args = parser.parse_args() + args.func(args) + + +if __name__ == "__main__": + main() diff --git a/tests/e2e/run_e2e.sh b/tests/e2e/run_e2e.sh new file mode 100644 index 0000000..923d83e --- /dev/null +++ b/tests/e2e/run_e2e.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# End-to-end test of the user path: maxatac data -> maxatac predict -> maxatac benchmark +# +# Predicts one TF on a slice of chr1 from the GM12878 test inputs in +# https://github.com/XiaotingChen/quant-maxATAC_test_data (Git LFS: clone with `git lfs` installed) +# and benchmarks the prediction against the ChIP-seq gold standard on the same slice. +# +# Used by .github/workflows/e2e.yml; runs the same way on a workstation or the cluster: +# TEST_DATA=/path/to/quant-maxATAC_test_data/data bash tests/e2e/run_e2e.sh +# +# Environment (all optional): +# TEST_DATA directory with the test inputs Default: test_data/data +# OUT output directory Default: e2e_out +# TF TF to predict (model from `maxatac data`) Default: CTCF +# ROI_START start of the chr1 slice Default: 1000000 +# ROI_END end of the chr1 slice Default: 11000000 +# DATA_VERSION data repository tag/branch for `maxatac data --data_version` Default: matches the code version +# SKIP_DATA 1 = reuse the installed data, skip `maxatac data` +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +TEST_DATA="${TEST_DATA:-test_data/data}" +OUT="${OUT:-e2e_out}" +TF="${TF:-CTCF}" +CHROM=chr1 +ROI_START="${ROI_START:-1000000}" +ROI_END="${ROI_END:-11000000}" +GENOME=hg38 +DATA_DIR="${HOME}/opt/maxatac/data" +PREFIX="GM12878_${TF}_e2e" + +ATAC_SIGNAL="${TEST_DATA}/GM12878_RP20M_minmax_percentile99_chr1.bw" +GOLD_STANDARD="${TEST_DATA}/GM12878__${TF}.bw" +QUANT_GOLD_STANDARD="${TEST_DATA}/GM12878__${TF}_quantLinearFC_chr1.bw" + +CHECK="python ${HERE}/check_outputs.py" + +mkdir -p "${OUT}" + +for input in "${ATAC_SIGNAL}" "${GOLD_STANDARD}" "${QUANT_GOLD_STANDARD}"; do + # An LFS pointer is ~130 bytes: catch a clone made without git-lfs early + if [ ! -s "${input}" ] || [ "$(wc -c < "${input}")" -lt 1024 ]; then + echo "::error::Missing test input or unresolved Git LFS pointer: ${input}" + exit 1 + fi +done + +echo "::group::maxatac data" +if [ "${SKIP_DATA:-0}" != "1" ]; then + maxatac data --genome "${GENOME}" --yes ${DATA_VERSION:+--data_version "${DATA_VERSION}"} +fi +${CHECK} data --data_dir "${DATA_DIR}" --genome "${GENOME}" --tf "${TF}" +echo "::endgroup::" + +echo "::group::Region of interest" +# Prediction is limited to one slice of chr1 so it runs on a CPU runner in minutes +printf "%s\t%s\t%s\n" "${CHROM}" "${ROI_START}" "${ROI_END}" > "${OUT}/roi.bed" +# chr1-only chrom sizes, so the sliding windows are not built genome wide +awk -v c="${CHROM}" '$1 == c' "${DATA_DIR}/${GENOME}/${GENOME}.chrom.sizes" > "${OUT}/${CHROM}.chrom.sizes" +# benchmark has no region option: restrict it to the ROI with a whitelist bigWig +${CHECK} whitelist --roi "${OUT}/roi.bed" --chrom_sizes "${OUT}/${CHROM}.chrom.sizes" --out "${OUT}/roi_whitelist.bw" +cat "${OUT}/roi.bed" +echo "::endgroup::" + +echo "::group::maxatac predict" +maxatac predict \ + --tf_name "${TF}" \ + --signal "${ATAC_SIGNAL}" \ + --chromosomes "${CHROM}" \ + --chrom_sizes "${OUT}/${CHROM}.chrom.sizes" \ + --roi "${OUT}/roi.bed" \ + --threads 1 \ + --batch_size 2000 \ + --prefix "${PREFIX}" \ + --output "${OUT}/predict" +${CHECK} prediction --prediction "${OUT}/predict/${PREFIX}.bw" --peaks "${OUT}/predict/${PREFIX}_peaks.bed" \ + --roi "${OUT}/roi.bed" +echo "::endgroup::" + +echo "::group::maxatac benchmark" +maxatac benchmark \ + --bw "${OUT}/predict/${PREFIX}.bw" \ + --gold_standard "${GOLD_STANDARD}" \ + --whitelist_bw "${OUT}/roi_whitelist.bw" \ + --chromosomes "${CHROM}" \ + --bin_size 200 \ + --agg max \ + --plot \ + --prefix "${PREFIX}" \ + --output_directory "${OUT}/benchmark" +echo "::endgroup::" + +echo "::group::Metrics" +${CHECK} report \ + --prc "${OUT}/benchmark/${PREFIX}_${CHROM}_200bp_PRC.tsv" \ + --prediction "${OUT}/predict/${PREFIX}.bw" \ + --quant_gold_standard "${QUANT_GOLD_STANDARD}" \ + --blacklist_bw "${DATA_DIR}/${GENOME}/${GENOME}_maxatac_blacklist.bw" \ + --roi "${OUT}/roi.bed" \ + --baseline "${HERE}/baseline.json" \ + --metrics_out "${OUT}/metrics.json" +echo "::endgroup::" diff --git a/tests/run_tests.sh b/tests/run_tests.sh deleted file mode 100755 index 3565614..0000000 --- a/tests/run_tests.sh +++ /dev/null @@ -1,54 +0,0 @@ -#!/bin/bash - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" - -#pip3 install -r $DIR/../test_requirements.txt -pip3 install -r $DIR/test_requirements.txt --use-feature=2020-resolver - -cd $DIR -mkdir -p temp -cd temp - -if [ ! -f "hg19.2bit" ] ; then - echo "Downloading hg19.2bit" - wget -q http://hgdownload.cse.ucsc.edu/goldenPath/hg19/bigZips/hg19.2bit -O hg19.2bit -fi - -if [ ! -f "predict_signal_cell_GM12878.bigwig" ] ; then - echo "Downloading predict_signal_cell_GM12878.bigwig" - wget -q https://guanfiles.dcmb.med.umich.edu/dnase_bigwig/GM12878.bigwig -O predict_signal_cell_GM12878.bigwig -fi - -if [ ! -f "train_signal_cell_A549.bigwig" ] ; then - echo "Downloading train_signal_cell_A549.bigwig" - wget -q https://guanfiles.dcmb.med.umich.edu/dnase_bigwig/A549.bigwig -O train_signal_cell_A549.bigwig -fi - -if [ ! -f "validate_signal_cell_HCT116.bigwig" ] ; then - echo "Downloading validate_signal_cell_HCT116.bigwig" - wget -q https://guanfiles.dcmb.med.umich.edu/dnase_bigwig/HCT116.bigwig -O validate_signal_cell_HCT116.bigwig -fi - -if [ ! -f "average.bigwig" ] ; then - echo "Downloading average.bigwig" - wget -q https://guanfiles.dcmb.med.umich.edu/dnase_bigwig/avg.bigwig -O average.bigwig -fi - -if [ ! -f "train_sites_cell_A549_tf_CTCF.bigwig" ] ; then - echo "Downloading train_sites_cell_A549_tf_CTCF.bigwig" - wget -q https://guanfiles.dcmb.med.umich.edu/chipseq_conservative_refine_bigwig/CTCF_A549.bigwig -O train_sites_cell_A549_tf_CTCF.bigwig -fi - -if [ ! -f "validate_sites_cell_HCT116_tf_CTCF.bigwig" ] ; then - echo "Downloading validate_sites_cell_HCT116_tf_CTCF.bigwig" - wget -q https://guanfiles.dcmb.med.umich.edu/test_chipseq_conservative_refine_bigwig/CTCF_HCT116.bigwig -O validate_sites_cell_HCT116_tf_CTCF.bigwig -fi - -if [ ! -f "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" ] ; then - echo "Downloading GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - wget -q https://ftp.ncbi.nlm.nih.gov/geo/series/GSE143nnn/GSE143104/suppl/GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed -fi - -cd .. - -pytest -v --cov=maxatac --forked . diff --git a/tests/test.sh b/tests/test.sh deleted file mode 100644 index 4c9703b..0000000 --- a/tests/test.sh +++ /dev/null @@ -1,52 +0,0 @@ -#!/bin/bash - -module load bedtools/2.30.0 -module load anaconda3 -source activate maxATAC_IS59 - - -mkdir -p /scratch/war9qi/data/aronow/Balaji_Iyer/Projects/Maxatac_IS59/Maxatac_Predictions/20211015_DCNN_ATAC_DELTA/ARNT1 -cd /scratch/war9qi/data/aronow/Balaji_Iyer/Projects/Maxatac_IS59/Maxatac_Predictions/20211015_DCNN_ATAC_DELTA/ARNT1 - -maxatac train \ ---rand_ratio .30 \ ---arch DCNN_V2 \ ---atac_delta \ ---loss_name clipped_cross_entropy \ ---output_activation 'softmax' \ ---sequence /data/miraldiLab/databank/maxatac/maxATAC_inputs/genome_inf/hg38.2bit \ ---meta_file /scratch/war9qi/ARNT_revcomp_99percentile_Binary_Train.tsv \ ---output /scratch/war9qi/data/aronow/Balaji_Iyer/Projects/Maxatac_IS59/Maxatac_Predictions/20211015_DCNN_ATAC_DELTA/ARNT1/training_results \ ---prefix ARNT_binary_archs \ ---batch_size 1000 \ ---val_batch_size 1000 \ ---batches 100 \ ---epochs 30 \ ---threads 8 \ ---shuffle_cell_type - - -declare -a best_model_path=$(cat /scratch/war9qi/data/aronow/Balaji_Iyer/Projects/Maxatac_IS59/Maxatac_Predictions/20211015_DCNN_ATAC_DELTA/ARNT1/training_results/*txt) -for best_model in ${best_model_path[@]}; do - maxatac predict \ - --models ${best_model} \ - --sequence /data/miraldiLab/databank/maxatac/maxATAC_inputs/genome_inf/hg38.2bit \ - --signal /data/miraldiLab/databank/maxatac/maxATAC_inputs/ATAC/hg38/normalization/GM12878__minmax_percentile99.bw \ - --chromosomes chr1 \ - --prefix ARNT_binary_revcomp99_RR30 \ - --output /scratch/war9qi/data/aronow/Balaji_Iyer/Projects/Maxatac_IS59/Maxatac_Predictions/20211015_DCNN_ATAC_DELTA/ARNT1/prediction_results \ - --step_size 256 -done - -declare -a bp_RES=(200) - -for item in ${bp_RES[@]}; do - maxatac benchmark \ - --prediction /scratch/war9qi/data/aronow/Balaji_Iyer/Projects/Maxatac_IS59/Maxatac_Predictions/20211015_DCNN_ATAC_DELTA/ARNT1/prediction_results/ARNT_binary_revcomp99_RR30.bw \ - --gold_standard /data/miraldiLab/databank/maxatac/maxatac_goldstandards/hg38/binary/GM12878__ARNT.bw \ - --prefix ARNT_binary_revcomp99_RR30_benchmark \ - --bin_size ${item} \ - --agg max \ - --chromosomes chr1 \ - --output /scratch/war9qi/data/aronow/Balaji_Iyer/Projects/Maxatac_IS59/Maxatac_Predictions/20211015_DCNN_ATAC_DELTA/ARNT1/benchmarking_results -done diff --git a/tests/test_average.py b/tests/test_average.py new file mode 100644 index 0000000..105fcb5 --- /dev/null +++ b/tests/test_average.py @@ -0,0 +1,22 @@ +import os + +import pytest + + +def test_average_defaults_chrom_sizes_to_the_genome_bundle(): + # parse_arguments also runs update_reference_genome_paths, which fills args.chrom_sizes from --genome + parser_module = pytest.importorskip("maxatac.utilities.parser") + from maxatac.utilities.constants import maxatac_data_path + + args = parser_module.parse_arguments(["average", "-i", "a.bw", "b.bw", "-n", "average_test"]) + + assert args.chrom_sizes == os.path.join(maxatac_data_path, "hg38/hg38.chrom.sizes") + + +def test_average_keeps_an_explicit_chrom_sizes_file(): + parser_module = pytest.importorskip("maxatac.utilities.parser") + + args = parser_module.parse_arguments(["average", "-i", "a.bw", "-n", "average_test", + "--chromosome_sizes", "custom.chrom.sizes"]) + + assert args.chrom_sizes == "custom.chrom.sizes" diff --git a/tests/test_average/test_average.py b/tests/test_average/test_average.py deleted file mode 100644 index 3c94626..0000000 --- a/tests/test_average/test_average.py +++ /dev/null @@ -1,85 +0,0 @@ -import os -import pytest -from maxatac.analyses.average import run_averaging -from maxatac.utilities.system_tools import Namespace -from maxatac.utilities.constants import ALL_CHRS -import subprocess - -DATA_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp")) - -input_file_paths = ["../data/average/SRX10474876_Tn5_slop20_blacklisted.bw", - "../data/average/SRX10474877_Tn5_slop20_blacklisted.bw"] - -expected_outputs = {"../data/average/IMR-90_single_chrom.bw": "6194b2bc8ddd1f8b9e277e21a79d9297", - "../data/average/IMR-90_multi_chrom.bw": "46775111a72df9fc54c8c9d153135272", - "../data/average/IMR-90_all_chrom.bw": "a7b2b7b1be22a046d49cff36ba46e8ea"} - -chrom_sizes_path = "~/opt/maxatac/data/hg38/hg38.chrom.sizes" - -def test_average_multi_chrom(): - """ - Test that maxatac average can produce a .bw that has been filtered for chr22 and chr3 - - """ - args_test_multi_chrom = Namespace(bigwig_files=input_file_paths, - output_dir=DATA_FOLDER, - name="average_multi_chrom_test", - chromosomes=["chr22", "chr3"], - chromosome_sizes=chrom_sizes_path - ) - - run_averaging(args_test_multi_chrom) - - output_file = os.path.join(DATA_FOLDER, "average_multi_chrom_test.bw") - - results = subprocess.run(f"md5sum {output_file}", shell=True, capture_output=True) - - md5sum = str(results.stdout.decode()).split(" ")[0] - - assert md5sum == expected_outputs["../data/average/IMR-90_multi_chrom.bw"] - - -def test_average_single_chrom(): - """ - Test that maxatac average can produce a .bw file that has only a single chromosome - - """ - args_test_single_chrom = Namespace(bigwig_files=input_file_paths, - output_dir=DATA_FOLDER, - name="average_single_chrom_test", - chromosomes=["chr22"], - chromosome_sizes=chrom_sizes_path - ) - - run_averaging(args_test_single_chrom) - - output_file = os.path.join(DATA_FOLDER, "average_single_chrom_test.bw") - - results = subprocess.run(f"md5sum {output_file}", shell=True, capture_output=True) - - md5sum = str(results.stdout.decode()).split(" ")[0] - - assert md5sum == expected_outputs["../data/average/IMR-90_single_chrom.bw"] - - -def test_average_all_chrom(): - """ - Test that maxatac average can produce a .bw file that uses all chromosome - - """ - args_test_all_chrom = Namespace(bigwig_files=input_file_paths, - output_dir=DATA_FOLDER, - name="average_all_chrom_test", - chromosomes=ALL_CHRS, - chromosome_sizes=chrom_sizes_path - ) - - run_averaging(args_test_all_chrom) - - output_file = os.path.join(DATA_FOLDER, "average_all_chrom_test.bw") - - results = subprocess.run(f"md5sum {output_file}", shell=True, capture_output=True) - - md5sum = str(results.stdout.decode()).split(" ")[0] - - assert md5sum == expected_outputs["../data/average/IMR-90_all_chrom.bw"] diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py index 2704b66..87b8001 100644 --- a/tests/test_benchmark.py +++ b/tests/test_benchmark.py @@ -71,3 +71,332 @@ def test_precision_for_recall_collapses_duplicate_recall_to_max_precision(): assert Precision_for_Recall(curve, 0.10) == pytest.approx(0.9) assert Precision_for_Recall(curve, 0.15) == pytest.approx(0.7) + + +class _StubGoldStandard: + """pyBigWig stand-in returning fixed per-bin stats""" + + def __init__(self, bins): + self.bins = bins + + def stats(self, chromosome, start, end, type, nBins, exact): + return list(self.bins) + + +def test_random_auprc_counts_gold_standard_bins_inside_the_evaluated_mask(tmp_path): + import pandas as pd + from maxatac.utilities.benchmarking_tools import ChromosomeAUPRC + + # 200 bins, the first 100 bound. The mask (blacklist and whitelist combined) keeps 10 bins, 2 of them bound + gold_standard = np.zeros(200) + gold_standard[:100] = 1 + mask = np.zeros(200, dtype=bool) + mask[98:108] = True + + # Bypass __init__ (bigwig I/O) and run the gold standard import and AUPRC steps on in-memory arrays + auprc = ChromosomeAUPRC.__new__(ChromosomeAUPRC) + auprc.chromosome = "chr1" + auprc.chromosome_length = 200 * 200 + auprc.bin_count = 200 + auprc.bin_size = 200 + auprc.agg_function = "max" + auprc.agg_threshold = 0.5 + auprc.peak_based = False + auprc.blacklist_mask = mask + auprc.goldstandard_stream = _StubGoldStandard(gold_standard) + auprc.prediction_array = np.linspace(1, 0, 200) + auprc.results_location = str(tmp_path / "chr1_PRC.tsv") + + auprc.__import_goldstandard_array__() + auprc.__AUPRC__() + + results = pd.read_csv(auprc.results_location, sep="\t") + + # Before the fix: 100 chromosome-wide positives / 10 evaluated bins = 10 + assert results["Total_GoldStandard_Bins"].iloc[0] == 2 + assert results["Random_AUPRC"].iloc[0] == pytest.approx(0.2) + assert results["Random_AUPRC"].iloc[0] == pytest.approx(auprc.random_precision) + + +def _peak_gold_standard(peak_sizes, gap, rng): + """Boolean bins: peaks of the given sizes separated by random negative gaps of at least 1 bin""" + bins = [] + for size in peak_sizes: + bins += [False] * int(rng.integers(1, gap + 1)) + [True] * size + return np.array(bins + [False] * gap) + + +def test_random_aup_ucper_matches_mean_of_random_rankings(): + from maxatac.utilities.benchmarking_tools import (peak_gs_array_to_member_array, + precision_recall_curve_peak_based, + random_aup_ucper) + from sklearn import metrics + + # The analytic curve is the expected curve, so it is about 1/peaks below the mean of shuffled + # rankings (8% at 20 peaks). Use 500 peaks so that bias is well under the tolerance + rng = np.random.default_rng(0) + member = peak_gs_array_to_member_array(_peak_gold_standard([1, 2, 3, 5, 8] * 100, 30, rng)) + + simulated = [] + for _ in range(100): + precision, recall, _ = precision_recall_curve_peak_based(member, rng.random(len(member))) + simulated.append(metrics.auc(x=recall[:-1], y=precision[:-1])) + + assert random_aup_ucper(member) == pytest.approx(np.mean(simulated), rel=0.05) + + +def test_random_aup_ucper_is_flat_bin_level_baseline_for_single_bin_peaks(): + from maxatac.utilities.benchmarking_tools import peak_gs_array_to_member_array, random_aup_ucper + + gold_standard = _peak_gold_standard([1] * 25, 10, np.random.default_rng(1)) + member = peak_gs_array_to_member_array(gold_standard) + + # Flat at P/N; the curve starts at recall 1/N rather than 0, hence the small tolerance + assert random_aup_ucper(member) == pytest.approx(gold_standard.mean(), rel=0.01) + + +def test_random_aup_ucper_lies_between_end_and_start_precision(): + from maxatac.utilities.benchmarking_tools import peak_gs_array_to_member_array, random_aup_ucper + + gold_standard = _peak_gold_standard([4, 10, 20, 6] * 5, 40, np.random.default_rng(2)) + member = peak_gs_array_to_member_array(gold_standard) + n_peaks = len(np.unique(member[member > 0])) + n_negative = np.count_nonzero(member < 0) + + assert n_peaks / (n_peaks + n_negative) < random_aup_ucper(member) < gold_standard.mean() + + +def test_random_precision_at_ucper_matches_mean_of_random_rankings(): + from maxatac.utilities.benchmarking_tools import (Precision_for_Recall, + peak_gs_array_to_member_array, + precision_recall_curve_peak_based, + random_precision_at_ucper) + import pandas as pd + + rng = np.random.default_rng(3) + member = peak_gs_array_to_member_array(_peak_gold_standard([1, 2, 3, 5, 8] * 100, 30, rng)) + + simulated = [] + for _ in range(100): + precision, recall, _ = precision_recall_curve_peak_based(member, rng.random(len(member))) + curve = pd.DataFrame({"Precision": precision[:-1], "Recall": recall[:-1]}) + simulated.append(Precision_for_Recall(curve, 0.1)) + + assert random_precision_at_ucper(member, 0.1) == pytest.approx(np.mean(simulated), rel=0.03) + + +def test_peak_based_auprc_writes_random_baselines(tmp_path): + import pandas as pd + from maxatac.utilities.benchmarking_tools import (ChromosomeAUPRC, peak_gs_array_to_member_array, + random_aup_ucper, random_precision_at_ucper) + + gold_standard = _peak_gold_standard([1, 2, 3, 5, 8] * 20, 30, np.random.default_rng(4)).astype(float) + n_bins = len(gold_standard) + + auprc = ChromosomeAUPRC.__new__(ChromosomeAUPRC) + auprc.chromosome = "chr1" + auprc.chromosome_length = n_bins * 200 + auprc.bin_count = n_bins + auprc.bin_size = 200 + auprc.agg_function = "max" + auprc.agg_threshold = 0.5 + auprc.peak_based = True + auprc.blacklist_mask = np.ones(n_bins, dtype=bool) + auprc.goldstandard_stream = _StubGoldStandard(gold_standard) + auprc.prediction_array = np.random.default_rng(5).random(n_bins) + gold_standard + auprc.results_location = str(tmp_path / "chr1_PRC.tsv") + + auprc.__import_goldstandard_array__() + auprc.__AUPRC__() + + results = pd.read_csv(auprc.results_location, sep="\t").iloc[0] + member = peak_gs_array_to_member_array(gold_standard > 0) + + assert results["Total_GoldStandard_Peaks"] == 100 + assert results["Random_AUPRC"] == pytest.approx(random_aup_ucper(member)) + assert results["Random_Precision_at_10_Percent_Recall"] == pytest.approx(random_precision_at_ucper(member, 0.1)) + assert results["log2FC_Precision_at_10_Percent_Recall_Random"] == pytest.approx( + np.log2(results["Precision_at_10_Percent_Recall"] / results["Random_Precision_at_10_Percent_Recall"])) + + +class _StubGoldStandardBigWig(_StubGoldStandard): + """pyBigWig stand-in with a chromosome size, for running ChromosomeAUPRC.__init__""" + + def chroms(self, chromosome): + return len(self.bins) * 200 + + +def test_random_only_writes_just_the_two_random_baselines_without_reading_the_prediction(tmp_path, monkeypatch): + import pandas as pd + from maxatac.utilities import benchmarking_tools + from maxatac.utilities.benchmarking_tools import (ChromosomeAUPRC, peak_gs_array_to_member_array, + random_aup_ucper, random_precision_at_ucper) + + gold_standard = _peak_gold_standard([1, 2, 3, 5, 8] * 20, 30, np.random.default_rng(6)).astype(float) + n_bins = len(gold_standard) + # Blacklist the first 50 bins: the baselines must use the masked gold standard only + mask = np.ones(n_bins, dtype=bool) + mask[:50] = False + + opened = [] + + def load_bigwig(path): + opened.append(path) + return _StubGoldStandardBigWig(gold_standard) + + monkeypatch.setattr(benchmarking_tools, "load_bigwig", load_bigwig) + monkeypatch.setattr(benchmarking_tools, "chromosome_blacklist_mask", lambda *args: mask) + + results_location = str(tmp_path / "test_chr1_200bp_random_UCPeR.tsv") + ChromosomeAUPRC(None, "gold_standard.bw", "blacklist.bw", None, "chr1", 200, "max", 0.5, + results_location, 9, peak_based=True, random_only=True) + + results = pd.read_csv(results_location, sep="\t") + member = peak_gs_array_to_member_array(gold_standard[mask] > 0) + + assert opened == ["gold_standard.bw"] + assert list(results.columns) == ["Random_AUPRC", "Random_Precision_at_10_Percent_Recall"] + assert len(results) == 1 + assert results["Random_AUPRC"].iloc[0] == pytest.approx(random_aup_ucper(member)) + assert results["Random_Precision_at_10_Percent_Recall"].iloc[0] == pytest.approx(random_precision_at_ucper(member, 0.1)) + + +def test_random_only_requires_peak_based(): + from maxatac.utilities.benchmarking_tools import ChromosomeAUPRC + + with pytest.raises(ValueError, match="peak_based"): + ChromosomeAUPRC(None, "gold_standard.bw", None, None, "chr1", 200, "max", 0.5, + "out.tsv", 9, peak_based=False, random_only=True) + + +def test_parse_benchmark_random_needs_no_prediction_but_needs_peak_based(): + parser_module = pytest.importorskip("maxatac.utilities.parser") + base = ["benchmark", "--gold_standard", "average.bigwig", "--name", "benchmark_test"] + + args = parser_module.parse_arguments(base + ["--peak_based", "--random"], DATA_FOLDER) + assert args.random and args.peak_based and args.prediction is None + + with pytest.raises(SystemExit): + parser_module.parse_arguments(base + ["--random"], DATA_FOLDER) + + with pytest.raises(SystemExit): + parser_module.parse_arguments(base + ["--peak_based"], DATA_FOLDER) + + +def test_pct_rank_gives_tied_bins_the_lowest_rank_and_zero_or_missing_bins_zero(): + from maxatac.utilities.genome_tools import _pct_rank + + # 6 bins: a zero, a NaN, a tie at 0.5, 0.2 and 0.9 + percentile = _pct_rank(np.array([0.0, np.nan, 0.5, 0.5, 0.2, 0.9])) + + # rankdata(min) over [0, 0, 0.5, 0.5, 0.2, 0.9] -> [1, 1, 4, 4, 3, 6], / 6; zero and NaN bins forced to 0 + np.testing.assert_allclose(percentile, np.array([0, 0, 4, 4, 3, 6]) / 6) + + +def test_rank_max_takes_the_max_percentile_and_falls_back_to_the_other_track(): + from maxatac.utilities.genome_tools import combine_prediction_arrays + + # Model scores are small, the average ChIP signal is large: a raw max would always pick the average + model = np.array([0.01, 0.02, 0.03, np.nan, 0.0, 0.04]) + average = np.array([10.0, 50.0, 0.0, 30.0, 20.0, 40.0]) + + combined = combine_prediction_arrays(model, average, combine_operation="rank_max") + + # model percentiles: [3, 4, 5, 0, 0, 6] / 6 (NaN and zero bins -> 0) + # average percentiles: [2, 6, 0, 4, 3, 5] / 6 (zero bin -> 0) + np.testing.assert_allclose(combined, np.array([3, 6, 5, 4, 3, 6]) / 6) + np.testing.assert_allclose(combine_prediction_arrays(model, average, combine_operation="max"), + np.array([10.0, 50.0, 0.03, 30.0, 20.0, 40.0])) + + +def test_rank_max_with_all_zero_or_missing_bins_scores_them_zero(): + from maxatac.utilities.genome_tools import combine_prediction_arrays + + combined = combine_prediction_arrays(np.array([np.nan, 0.0, 0.3]), np.array([0.0, np.nan, np.nan]), + combine_operation="rank_max") + + np.testing.assert_allclose(combined, np.array([0.0, 0.0, 1.0])) + + +def test_rank_max_logs_how_often_each_track_supplies_the_max(caplog): + import logging + from maxatac.utilities.genome_tools import combine_prediction_arrays + + with caplog.at_level(logging.INFO): + combine_prediction_arrays(np.array([0.01, 0.02, 0.03, np.nan, 0.0, 0.04]), + np.array([10.0, 50.0, 0.0, 30.0, 20.0, 40.0]), + combine_operation="rank_max") + + # From the percentiles above: model wins bins 1, 3, 6 and the average wins bins 2, 4, 5 + assert "primary supplies the max in 50.00% of bins, alternative in 50.00%, tied in 0.00%" in caplog.text + + +class _StubPredictionBigWig(_StubGoldStandardBigWig): + """pyBigWig stand-in for a prediction track; keeps NaN for missing bins like import_bigwig_stats_array expects""" + + +def test_chromosome_auprc_benchmarks_the_rank_max_ensemble(tmp_path, monkeypatch): + import pandas as pd + from maxatac.utilities import benchmarking_tools + from maxatac.utilities.benchmarking_tools import ChromosomeAUPRC + from maxatac.utilities.genome_tools import combine_prediction_arrays + + rng = np.random.default_rng(7) + gold_standard = _peak_gold_standard([1, 2, 3] * 30, 20, rng).astype(float) + n_bins = len(gold_standard) + + # Model: weak signal on peaks, missing on 5% of bins. Average ChIP: large values, zero on 40% of bins + model = rng.random(n_bins) * 0.1 + 0.05 * gold_standard + model[rng.random(n_bins) < 0.05] = np.nan + average = rng.random(n_bins) * 100 * (rng.random(n_bins) > 0.4) + + streams = {"model.bw": _StubPredictionBigWig(model), + "average.bw": _StubPredictionBigWig(average), + # --agg sum returns base-pair totals: 200 for a fully covered 200 bp bin + "gold_standard.bw": _StubGoldStandardBigWig(gold_standard * 200)} + monkeypatch.setattr(benchmarking_tools, "load_bigwig", lambda path: streams[path]) + # Blacklist bins 0-19, whitelist everything else but the last 10 bins + keep = np.ones(n_bins, dtype=bool) + keep[:20] = False + monkeypatch.setattr(benchmarking_tools, "chromosome_blacklist_mask", lambda *args: keep) + whitelist = np.ones(n_bins, dtype=bool) + whitelist[-10:] = False + monkeypatch.setattr(benchmarking_tools, "chromosome_whitelist_mask", lambda *args: whitelist) + + auprc = ChromosomeAUPRC("model.bw", "gold_standard.bw", "blacklist.bw", "whitelist.bw", "chr1", 200, "sum", 0.5, + str(tmp_path / "chr1_PRC.tsv"), 9, peak_based=True, + alternative_prediction_bw="average.bw", prediction_combine_operation="rank_max") + + # Combined on all bins before masking, and not divided by bin_size under --agg sum + expected = np.round(combine_prediction_arrays(model, average, combine_operation="rank_max"), 9) + np.testing.assert_allclose(auprc.prediction_array, expected) + assert auprc.prediction_array.max() <= 1.0 + + np.testing.assert_array_equal(auprc.blacklist_mask, keep & whitelist) + results = pd.read_csv(tmp_path / "chr1_PRC.tsv", sep="\t") + assert 0 < results["AUPRC"].iloc[0] <= 1 + + +def test_quant_benchmark_rejects_rank_max(monkeypatch): + from maxatac.utilities import benchmarking_tools + + stub = _StubGoldStandardBigWig(np.zeros(10)) + monkeypatch.setattr(benchmarking_tools, "load_bigwig", lambda path: stub) + + with pytest.raises(ValueError, match="rank_max"): + benchmarking_tools.calculate_R2_pearson_spearman("model.bw", "gs.bw", "quant_gs.bw", "chr1", 200, "mean", + "out.tsv", None, None, "null.bw", + alternative_prediction_bw="average.bw", + prediction_combine_operation="rank_max") + + +def test_parse_benchmark_rank_max_is_rejected_with_quant(): + parser_module = pytest.importorskip("maxatac.utilities.parser") + base = ["benchmark", "--bw", "model.bw", "--alternative_prediction", "average.bw", + "--gold_standard", "gs.bw", "--name", "benchmark_test", "--prediction_combine_operation", "rank_max"] + + assert parser_module.parse_arguments(base + ["--peak_based"], DATA_FOLDER).prediction_combine_operation == "rank_max" + + with pytest.raises(SystemExit): + parser_module.parse_arguments(base + ["--quant", "--quant_gold_standard", "q.bw", "--quant_gs_null", "n.bw"], + DATA_FOLDER) diff --git a/tests/test_data.py b/tests/test_data.py deleted file mode 100644 index 421cd8e..0000000 --- a/tests/test_data.py +++ /dev/null @@ -1,41 +0,0 @@ -import os -import re -import hashlib - -from maxatac.utilities.system_tools import get_files - -# Directory with all input files for testing. -# Subfolders are not allowed due to possible file name duplicates. -DATA_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp")) - - -CONTROL_MD5_SUMS = { - "hg19.2bit": "bcdbfbe9da62f19bee88b74dabef8cd3", - "train_signal_cell_A549.bigwig": "d41d8cd98f00b204e9800998ecf8427e", - "validate_signal_cell_HCT116.bigwig": "d41d8cd98f00b204e9800998ecf8427e", - "validate_sites_cell_HCT116_tf_CTCF.bigwig": "d41d8cd98f00b204e9800998ecf8427e", - "average.bigwig": "d41d8cd98f00b204e9800998ecf8427e", - "predict_signal_cell_GM12878.bigwig": "d41d8cd98f00b204e9800998ecf8427e", - "train_sites_cell_A549_tf_CTCF.bigwig": "d41d8cd98f00b204e9800998ecf8427e", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed": "63c2fda65d6810d4194e92c8ea8e394d" -} - - -def get_md5_sum(location, block_size=2**20): - md5_sum = hashlib.md5() - with open(location , "rb") as input_stream: - while True: - buf = input_stream.read(block_size) - if not buf: - break - md5_sum.update(buf) - return md5_sum.hexdigest() - - -def test_md5_sum(): - collected_md5_sums = {} - for filename, location in get_files(DATA_FOLDER).items(): - collected_md5_sums[filename] = get_md5_sum(location) - for filename, control_md5_sum in CONTROL_MD5_SUMS.items(): - assert filename in collected_md5_sums, "missing input file for tests" - assert collected_md5_sums[filename] == control_md5_sum, "change input file for tests" diff --git a/tests/test_helpers.py b/tests/test_helpers.py deleted file mode 100644 index de84de6..0000000 --- a/tests/test_helpers.py +++ /dev/null @@ -1,60 +0,0 @@ -import pytest -import os - -from maxatac.utilities.system_tools import get_files - - -DATA_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp")) - - -control_empty = [] - -control_all_files = [ - "hg19.2bit", - "train_signal_cell_A549.bigwig", - "validate_signal_cell_HCT116.bigwig", - "validate_sites_cell_HCT116_tf_CTCF.bigwig", - "average.bigwig", - "predict_signal_cell_GM12878.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" -] - -control_all_bigwigs = [ - "train_signal_cell_A549.bigwig", - "validate_signal_cell_HCT116.bigwig", - "validate_sites_cell_HCT116_tf_CTCF.bigwig", - "average.bigwig", - "predict_signal_cell_GM12878.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig" -] - -control_all_2bit = [ - "hg19.2bit" -] - -control_files_by_names = [ - "hg19.2bit", - "average.bigwig", - "predict_signal_cell_GM12878.bigwig", -] - -control_file_by_name = [ - "hg19.2bit" -] - - -@pytest.mark.parametrize( - "filename_pattern, control_filenames", - [ - (None, control_all_files), - (".*bigwig", control_all_bigwigs), - (".*2bit", control_all_2bit), - ("hg19.2bit|average.bigwig|predict_signal_cell_GM12878.bigwig", control_files_by_names), - ("hg19.2bit", control_file_by_name), - ("mm10", control_empty) - ] -) -def test_get_files(filename_pattern, control_filenames): - collected_filenames = get_files(DATA_FOLDER, filename_pattern).keys() - assert sorted(collected_filenames) == sorted(control_filenames) diff --git a/tests/test_normalize/test_normalize.py b/tests/test_normalize/test_normalize.py deleted file mode 100644 index a7e1f64..0000000 --- a/tests/test_normalize/test_normalize.py +++ /dev/null @@ -1,41 +0,0 @@ -import os -import pytest -from maxatac.analyses.normalize import run_normalization -from maxatac.utilities.system_tools import Namespace -import subprocess -from maxatac.utilities.constants import blacklist_bigwig_path, AUTOSOMAL_CHRS, chrom_sizes_path -DATA_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp")) - -input_file_paths = "../data/average/IMR-90_all_chrom.bw" - -expected_outputs = {"../data/normalize/IMR-90_minmax01_percentile99.bw": "413b925d425b039ff3ac46d84bd790c9", - "../data/normalize/IMR-90_minmax01_percentile99_genome_stats.txt": "cb54a14503617564674d1ba398a8e05e", - "../data/normalize/IMR-90_minmax01_percentile99_chromosome_min_max.txt": "19185afdd98c18ab03c891ed9f51f06c"} - -args_test_min_max = Namespace(signal=input_file_paths, - output_dir=DATA_FOLDER, - name="normalize_test", - max=False, - method="min-max", - max_percentile=99, - blacklist=blacklist_bigwig_path, - chromosomes=AUTOSOMAL_CHRS, - chrom_sizes=chrom_sizes_path, - clip=False) - - -def test_normalization(): - """ - Test that maxatac normalize can min-max normalize a bigwig file to the 99th percentile max - - """ - run_normalization(args_test_min_max) - - output_file = os.path.join(DATA_FOLDER, "normalize_test.bw") - - results = subprocess.run(f"md5sum {output_file}", shell=True, capture_output=True) - - md5sum = str(results.stdout.decode()).split(" ")[0] - - assert md5sum == expected_outputs["../data/normalize/IMR-90_minmax01_percentile99.bw"] - diff --git a/tests/test_parser.py b/tests/test_parser.py deleted file mode 100644 index 609b5d3..0000000 --- a/tests/test_parser.py +++ /dev/null @@ -1,792 +0,0 @@ -import pytest -import os - -from maxatac.utilities.system_tools import get_files -from maxatac.utilities.parser import parse_arguments - - -DATA_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp")) - - -# For not direct testing of assert_and_fix_args_for_training - -@pytest.mark.parametrize( - "args, control_args", - [ - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr2", "chr3", "chr10", "chr11", "chr8", "chr21", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr2", "chr8", "chr21", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr8": {"length": 146364022, "region": [0, 146364022]}, - "chr21": {"length": 48129895, "region": [0, 48129895]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]} - }, - "vchroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]}, - "chr21": {"length": 48129895, "region": [0, 48129895]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr2", "chr3", "chr10", "chr11", "chr8", "chr21", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr2", "chr8", "chr21", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr8": {"length": 146364022, "region": [0, 146364022]}, - "chr21": {"length": 48129895, "region": [0, 48129895]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]} - }, - "vchroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]}, - "chr21": {"length": 48129895, "region": [0, 48129895]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr2", "chr3", "chr10", "chr11", "chr8", "chr21", - "--tchroms", "chr10", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr8": {"length": 146364022, "region": [0, 146364022]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]} - }, - "vchroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr2", "chr3", "chr10", "chr11", "chr8", "chr21", - "--tchroms", "chr10", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr8": {"length": 146364022, "region": [0, 146364022]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]} - }, - "vchroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr2", "chr3", "chr10", "chr11", "chr8", "chr21", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]} - }, - "tchroms": {}, - "vchroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr2", "chr3", "chr10", "chr11", "chr8", "chr21", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]} - }, - "tchroms": {}, - "vchroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--tchroms", "chr10", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr8": {"length": 146364022, "region": [0, 146364022]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]} - }, - "vchroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--tchroms", "chr10", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr8": {"length": 146364022, "region": [0, 146364022]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]} - }, - "vchroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr8", "chr12", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]}, - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]} - }, - "vchroms": { - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr8", "chr12", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]}, - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]} - }, - "vchroms": { - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--vchroms", "chr8", "chr12", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]}, - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - }, - "tchroms": {}, - "vchroms": { - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--vchroms", "chr8", "chr12", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]}, - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - }, - "tchroms": {}, - "vchroms": { - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--filters", "average.bigwig", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr8", "chr12", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]}, - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]} - }, - "vchroms": { - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--filters", "average.bigwig", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr8", "chr12", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]}, - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]} - }, - "vchroms": { - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--filters", "train_sites_cell_A549_tf_CTCF.bigwig", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr8", "chr12", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]}, - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]} - }, - "vchroms": { - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--filters", "train_sites_cell_A549_tf_CTCF.bigwig", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr8", "chr12", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]}, - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]} - }, - "vchroms": { - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--filters", "train_sites_cell_A549_tf_CTCF.bigwig", - "--tchroms", "chr10", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]} - }, - "vchroms": {} - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--filters", "train_sites_cell_A549_tf_CTCF.bigwig", - "--tchroms", "chr10", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]} - }, - "vchroms": {} - } - ) - ] -) -def test_parse_chromosome_arguments_for_training(args, control_args): - args = parse_arguments(args, DATA_FOLDER) - assert args.chroms == control_args["chroms"] and args.tchroms == control_args["tchroms"] and args.vchroms == control_args["vchroms"] - - -# For not direct testing of assert_and_fix_args_for_training (should fail on assert) - -@pytest.mark.parametrize( - "args", - [ - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr8", "chr10", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ] - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr8", "chr10", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ] - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr20", "chr11", - "--vchroms", "chr8", "chr10", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ] - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr20", "chr11", - "--vchroms", "chr8", "chr10", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ] - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr8", - "--tchroms", "chr1", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ] - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr8", - "--tchroms", "chr1", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ] - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ] - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ] - ) - ] -) -def test_parse_chromosome_arguments_for_training_should_fail(args): - with pytest.raises(AssertionError): - args = parse_arguments(args, DATA_FOLDER) - - - - -# average.bigwig -# chr1 249250621 -# chr2 243199373 -# chr3 198022430 -# chr4 191154276 -# chr5 180915260 -# chr6 171115067 -# chr7 159138663 -# chr8 146364022 -# chr9 141213431 -# chr10 135534747 -# chr11 135006516 -# chr12 133851895 -# chr13 115169878 -# chr14 107349540 -# chr15 102531392 -# chr16 90354753) -# chr17 81195210 -# chr18 78077248 -# chr19 59128983 -# chr20 63025520 -# chr21 48129895 -# chr22 51304566 -# chrX 155270560 - - -# predict_signal_cell_GM12878.bigwig -# chr1 249250621 -# chr2 243199373 -# chr3 198022430 -# chr4 191154276 -# chr5 180915260 -# chr6 171115067 -# chr7 159138663 -# chr8 146364022 -# chr9 141213431 -# chr10 135534747) -# chr11 135006516 -# chr12 133851895 -# chr13 115169878 -# chr14 107349540 -# chr15 102531392 -# chr16 90354753 -# chr17 81195210 -# chr18 78077248 -# chr19 59128983 -# chr20 63025520 -# chr21 48129895 -# chr22 51304566 -# chrX 155270560 - - -# train_signal_cell_A549.bigwig -# chr1 249250621 -# chr2 243199373 -# chr3 198022430 -# chr4 191154276 -# chr5 180915260 -# chr6 171115067 -# chr7 159138663 -# chr8 146364022 -# chr9 141213431 -# chr10 135534747 -# chr11 135006516 -# chr12 133851895 -# chr13 115169878 -# chr14 107349540 -# chr15 102531392 -# chr16 90354753) -# chr17 81195210 -# chr18 78077248 -# chr19 59128983 -# chr20 63025520 -# chr21 48129895 -# chr22 51304566 -# chrX 155270560 - - -# train_sites_cell_A549_tf_CTCF.bigwig -# chr2 243199373 -# chr3 198022430 -# chr4 191154276 -# chr5 180915260 -# chr6 171115067) -# chr7 159138663 -# chr9 141213431 -# chr10 135534747 -# chr11 135006516 -# chr12 133851895 -# chr13 115169878 -# chr14 107349540 -# chr15 102531392 -# chr16 90354753 -# chr17 81195210 -# chr18 78077248 -# chr19 59128983 -# chr20 63025520 -# chr22 51304566 -# chrX 155270560 - - -# validate_signal_cell_HCT116.bigwig -# chr1 249250621 -# chr2 243199373 -# chr3 198022430 -# chr4 191154276 -# chr5 180915260 -# chr6 171115067 -# chr7 159138663 -# chr8 146364022 -# chr9 141213431 -# chr10 135534747 -# chr11 135006516 -# chr12 133851895 -# chr13 115169878 -# chr14 107349540 -# chr15 102531392 -# chr16 90354753) -# chr17 81195210 -# chr18 78077248 -# chr19 59128983 -# chr20 63025520 -# chr21 48129895 -# chr22 51304566 -# chrX 155270560 - - -# validate_sites_cell_HCT116_tf_CTCF.bigwig -# chr1 249250621 -# chr8 146364022 -# chr21 48129895 \ No newline at end of file diff --git a/tests/test_predict/test_predict.py b/tests/test_predict/test_predict.py deleted file mode 100644 index d400e5f..0000000 --- a/tests/test_predict/test_predict.py +++ /dev/null @@ -1,33 +0,0 @@ -import os -import pytest -import pandas as pd -from maxatac.utilities.prepare_tools import convert_fragments_to_tn5_bed -from maxatac.analyses.prepare import run_prepare -from maxatac.utilities.constants import chrom_sizes_path, AUTOSOMAL_CHRS, blacklist_bigwig_path, blacklist_path - -from maxatac.utilities.system_tools import Namespace -import subprocess - -DATA_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp")) - -# These are for the bulk data sets -input_bw_path = "/Users/caz3so/workspaces/miraldiLab/maxATAC/tests/data/prepare/bulk_atac_SRX2717911_sub01.bam" - -expected_outputs = {"GM12878_bulk_IS_slop20_RP20M.bw": "c49a30be1da68b73141ba02a2255a0f6", - "GM12878_bulk_IS_slop20_RP20M_minmax01.bw": "e0429a7fb990da36707a075343b97b3e", - "GM12878_bulk_IS_slop20_RP20M_minmax01_chromosome_min_max.txt": "36e5f37a4ec1aaea0fb55ed1c86e12ee", - "GM12878_bulk_IS_slop20_RP20M_minmax01_genome_stats.txt": "b366a2c759587d24440f25c6343caae6"} - -# These are for the scATAC-seq processing functions -input_file_path = "../data/prepare/scatac_fragments.tsv" -expected_file_path = "../data/prepare/scatac_CutSites.tsv" - - -def test_fragments_to_tn5_bed(): - """ - Test that fragments are converted to cut sites correctly - - """ - assert convert_fragments_to_tn5_bed(fragments_tsv=input_file_path, - chroms=["chr1"] - ).equals(expected_dataframe) \ No newline at end of file diff --git a/tests/test_prepare/test_prepare.py b/tests/test_prepare/test_prepare.py deleted file mode 100644 index 475077b..0000000 --- a/tests/test_prepare/test_prepare.py +++ /dev/null @@ -1,117 +0,0 @@ -import os -import pytest -import pandas as pd -from maxatac.utilities.prepare_tools import convert_fragments_to_tn5_bed -from maxatac.analyses.prepare import run_prepare -from maxatac.utilities.constants import chrom_sizes_path, AUTOSOMAL_CHRS, blacklist_bigwig_path, blacklist_path - -from maxatac.utilities.system_tools import Namespace -import subprocess - -DATA_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp")) - -# These are for the bulk data sets -input_bam_path = "/Users/caz3so/workspaces/miraldiLab/maxATAC/tests/data/prepare/bulk_atac_SRX2717911_sub01.bam" - -expected_bulk_outputs = {"GM12878_bulk_IS_slop20_RP20M.bw": "c49a30be1da68b73141ba02a2255a0f6", - "GM12878_bulk_IS_slop20_RP20M_minmax01.bw": "e0429a7fb990da36707a075343b97b3e", - "GM12878_bulk_IS_slop20_RP20M_minmax01_chromosome_min_max.txt": "36e5f37a4ec1aaea0fb55ed1c86e12ee", - "GM12878_bulk_IS_slop20_RP20M_minmax01_genome_stats.txt": "b366a2c759587d24440f25c6343caae6"} - -# These are for the scATAC-seq processing functions -input_file_path = "../data/prepare/scatac_fragments.tsv" -expected_file_path = "../data/prepare/scatac_CutSites.tsv" -expected_dataframe = pd.read_table(expected_file_path, sep="\t") - -# Full scATAC fragment file test -input_scatac_frags = "/Users/caz3so/workspaces/miraldiLab/maxATAC/tests/data/prepare/GM12878_fragments_subsample_1M.tsv" - -expected_scatac_outputs = {"GM12878_scatac_1M_IS_slop20_RP20M.bw": "5ad8c991d458e74f96024337652c93b3", - "GM12878_scatac_1M_IS_slop20_RP20M_minmax01.bw": "04b7edda09ec6303d80c121109bad90e", - "GM12878_scatac_1M_IS_slop20_RP20M_minmax01_chromosome_min_max.txt": "25863a4d1b83e7410dbaae0fa6090d59", - "GM12878_scatac_1M_IS_slop20_RP20M_minmax01_genome_stats.txt": "a7397bf4c5ef4dd4c79aaab35830ff4d"} - - -def test_fragments_to_tn5_bed(): - """ - Test that fragments are converted to cut sites correctly - - """ - assert convert_fragments_to_tn5_bed(fragments_tsv=input_file_path, - chroms=["chr1"]).equals(expected_dataframe) - - -def test_fragments_to_tn5_bed_wrong_chrom(): - """ - Test that fragments can be filtered by chromosome - - """ - assert (convert_fragments_to_tn5_bed(fragments_tsv=input_file_path, - chroms=["chr2"]).equals(expected_dataframe) == False) - - -def test_prepare_bulk(): - """ - Test that a bam file can be prepared for maxATAC - """ - # Args for bulk - args_bulk = Namespace(input=input_bam_path, - output_dir=DATA_FOLDER, - name="GM12878_bulk", - chromosomes=AUTOSOMAL_CHRS, - chrom_sizes=chrom_sizes_path, - slop=20, - rpm_factor=20000000, - blacklist_bed=blacklist_path, - blacklist=blacklist_bigwig_path, - threads=4, - skip_dedup=False, - clip=False, - max=False, - method="min-max", - max_percentile=99) - - run_prepare(args_bulk) - - for file, md5 in expected_bulk_outputs.items(): - output_file = os.path.join(DATA_FOLDER, file) - - results = subprocess.run(f"md5sum {output_file}", shell=True, capture_output=True) - - md5sum = str(results.stdout.decode()).split(" ")[0] - - assert md5sum == md5 - - -def test_prepare_scatac(): - """ - Test that a tsv file can be prepared for maxATAC - """ - # Args for scatac - args_scatac = Namespace(input=input_scatac_frags, - output_dir=DATA_FOLDER, - name="GM12878_scatac_1M", - chromosomes=AUTOSOMAL_CHRS, - chrom_sizes=chrom_sizes_path, - slop=20, - rpm_factor=20000000, - blacklist_bed=blacklist_path, - blacklist=blacklist_bigwig_path, - threads=4, - skip_dedup=False, - clip=False, - max=False, - method="min-max", - max_percentile=99 - ) - - run_prepare(args_scatac) - - for file, md5 in expected_scatac_outputs.items(): - output_file = os.path.join(DATA_FOLDER, file) - - results = subprocess.run(f"md5sum {output_file}", shell=True, capture_output=True) - - md5sum = str(results.stdout.decode()).split(" ")[0] - - assert md5sum == md5 diff --git a/tests/test_requirements.txt b/tests/test_requirements.txt deleted file mode 100644 index 5a59c47..0000000 --- a/tests/test_requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -pytest==6.2.5 -pytest-xdist==2.4.0 -pytest-cov==3.0.0 -coveralls==3.2.0 \ No newline at end of file diff --git a/tests/test_threshold.py b/tests/test_threshold.py new file mode 100644 index 0000000..974d909 --- /dev/null +++ b/tests/test_threshold.py @@ -0,0 +1,77 @@ +import numpy as np +import pandas as pd +import pytest + +from maxatac.utilities.peak_tools import get_threshold +from maxatac.utilities.threshold_tools import compute_calibration_curve, PEAK_RECALL + + +def _actual_metrics(goldstandard, prediction, threshold): + """Precision and recall at a threshold, with sklearn's >= rule""" + called = prediction >= threshold + true_positives = np.count_nonzero(called & goldstandard) + return true_positives / np.count_nonzero(called), true_positives / np.count_nonzero(goldstandard) + + +def test_calibration_curve_keeps_only_attained_thresholds(): + # Real precision: 0.667 at threshold 0.1, 0.5 at 0.2, 0 at 0.9 (the top-scoring bin is unbound). + # 0.2 and 0.9 are beaten by 0.1, and the (Precision=1, Recall=0) sentinel is not a threshold + curve = compute_calibration_curve(np.array([1, 1, 0]), np.array([0.1, 0.2, 0.9])) + + assert curve["Threshold"].tolist() == [0.1] + assert curve["Precision"].tolist() == pytest.approx([2 / 3]) + assert curve["Recall"].tolist() == pytest.approx([1.0]) + assert (curve["Precision"] < 1).all() + + +def test_calibration_curve_rows_are_real_and_monotonic(): + rng = np.random.default_rng(0) + goldstandard = rng.random(500) < 0.2 + prediction = np.round(goldstandard * 0.3 + rng.random(500), 3) + peak_max = rng.random(40) + + curve = compute_calibration_curve(goldstandard, prediction, peak_max=peak_max) + + # Every row is the precision/recall actually achieved at its own threshold + for row in curve.itertuples(): + precision, recall = _actual_metrics(goldstandard, prediction, row.Threshold) + assert row.Precision == pytest.approx(precision) + assert row.Recall == pytest.approx(recall) + + # Ascending threshold: precision strictly rises, recall and Peak_Recall never rise + curve = curve.sort_values("Threshold") + assert np.all(np.diff(curve["Precision"]) > 0) + assert np.all(np.diff(curve["Recall"]) <= 0) + assert np.all(np.diff(curve[PEAK_RECALL]) <= 0) + + +def _write_table(path, rows): + pd.DataFrame(rows, columns=["Metric", "Bin", "Precision", "Recall", "Threshold", "F1"]).to_csv( + path, sep="\t", index=False) + return str(path) + + +def test_get_threshold_requires_the_achieved_value(tmp_path): + # Grid extension: bins past the best precision (0.8) repeat its row, so Bin 1.0 holds Precision 0.8 + table = _write_table(tmp_path / "table.tsv", [ + ["Precision", 0.70, 0.70, 0.60, 0.5, 0.65], + ["Precision", 0.80, 0.80, 0.40, 0.7, 0.53], + ["Precision", 0.90, 0.80, 0.40, 0.7, 0.53], + ["Precision", 1.00, 0.80, 0.40, 0.7, 0.53], + ]) + + with pytest.raises(ValueError, match="highest Precision it reaches is 0.800"): + get_threshold(table, "Precision", 1.0) + + # Closest achieved value that meets the request + assert get_threshold(table, "Precision", 0.75) == pytest.approx(0.7) + assert get_threshold(table, "Precision", 0.65) == pytest.approx(0.5) + + +def test_get_threshold_breaks_ties_on_f1(tmp_path): + table = _write_table(tmp_path / "table.tsv", [ + ["Recall", 0.50, 0.60, 0.50, 0.9, 0.545], + ["Recall", 0.51, 0.70, 0.50, 0.8, 0.583], + ]) + + assert get_threshold(table, "Recall", 0.5) == pytest.approx(0.8) diff --git a/tests/test_tools.py b/tests/test_tools.py deleted file mode 100644 index 804281e..0000000 --- a/tests/test_tools.py +++ /dev/null @@ -1,20 +0,0 @@ -import pytest -import os -from maxatac.utilities.system_tools import get_files -from maxatac.utilities.constants import DATA_FOLDER - -control_all_2bit = [ - "hg19.2bit" -] - - -@pytest.mark.parametrize( - "filename_pattern, control_filenames", - [ - ("hg38.2bit", control_all_2bit), - ] -) - -def test_get_one_hot_encoded(filename_pattern, control_filenames): - collected_filenames = get_files(DATA_FOLDER, filename_pattern).keys() - assert sorted(collected_filenames) == sorted(control_filenames)