smftools 0.1.6__py3-none-any.whl → 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. smftools/__init__.py +34 -0
  2. smftools/_settings.py +20 -0
  3. smftools/_version.py +1 -0
  4. smftools/cli.py +184 -0
  5. smftools/config/__init__.py +1 -0
  6. smftools/config/conversion.yaml +33 -0
  7. smftools/config/deaminase.yaml +56 -0
  8. smftools/config/default.yaml +253 -0
  9. smftools/config/direct.yaml +17 -0
  10. smftools/config/experiment_config.py +1191 -0
  11. smftools/datasets/F1_hybrid_NKG2A_enhander_promoter_GpC_conversion_SMF.h5ad.gz +0 -0
  12. smftools/datasets/F1_sample_sheet.csv +5 -0
  13. smftools/datasets/__init__.py +9 -0
  14. smftools/datasets/dCas9_m6A_invitro_kinetics.h5ad.gz +0 -0
  15. smftools/datasets/datasets.py +28 -0
  16. smftools/hmm/HMM.py +1576 -0
  17. smftools/hmm/__init__.py +20 -0
  18. smftools/hmm/apply_hmm_batched.py +242 -0
  19. smftools/hmm/calculate_distances.py +18 -0
  20. smftools/hmm/call_hmm_peaks.py +106 -0
  21. smftools/hmm/display_hmm.py +18 -0
  22. smftools/hmm/hmm_readwrite.py +16 -0
  23. smftools/hmm/nucleosome_hmm_refinement.py +104 -0
  24. smftools/hmm/train_hmm.py +78 -0
  25. smftools/informatics/__init__.py +14 -0
  26. smftools/informatics/archived/bam_conversion.py +59 -0
  27. smftools/informatics/archived/bam_direct.py +63 -0
  28. smftools/informatics/archived/basecalls_to_adata.py +71 -0
  29. smftools/informatics/archived/conversion_smf.py +132 -0
  30. smftools/informatics/archived/deaminase_smf.py +132 -0
  31. smftools/informatics/archived/direct_smf.py +137 -0
  32. smftools/informatics/archived/print_bam_query_seq.py +29 -0
  33. smftools/informatics/basecall_pod5s.py +80 -0
  34. smftools/informatics/fast5_to_pod5.py +24 -0
  35. smftools/informatics/helpers/__init__.py +73 -0
  36. smftools/informatics/helpers/align_and_sort_BAM.py +86 -0
  37. smftools/informatics/helpers/aligned_BAM_to_bed.py +85 -0
  38. smftools/informatics/helpers/archived/informatics.py +260 -0
  39. smftools/informatics/helpers/archived/load_adata.py +516 -0
  40. smftools/informatics/helpers/bam_qc.py +66 -0
  41. smftools/informatics/helpers/bed_to_bigwig.py +39 -0
  42. smftools/informatics/helpers/binarize_converted_base_identities.py +172 -0
  43. smftools/informatics/helpers/canoncall.py +34 -0
  44. smftools/informatics/helpers/complement_base_list.py +21 -0
  45. smftools/informatics/helpers/concatenate_fastqs_to_bam.py +378 -0
  46. smftools/informatics/helpers/converted_BAM_to_adata.py +245 -0
  47. smftools/informatics/helpers/converted_BAM_to_adata_II.py +505 -0
  48. smftools/informatics/helpers/count_aligned_reads.py +43 -0
  49. smftools/informatics/helpers/demux_and_index_BAM.py +52 -0
  50. smftools/informatics/helpers/discover_input_files.py +100 -0
  51. smftools/informatics/helpers/extract_base_identities.py +70 -0
  52. smftools/informatics/helpers/extract_mods.py +83 -0
  53. smftools/informatics/helpers/extract_read_features_from_bam.py +33 -0
  54. smftools/informatics/helpers/extract_read_lengths_from_bed.py +25 -0
  55. smftools/informatics/helpers/extract_readnames_from_BAM.py +22 -0
  56. smftools/informatics/helpers/find_conversion_sites.py +51 -0
  57. smftools/informatics/helpers/generate_converted_FASTA.py +99 -0
  58. smftools/informatics/helpers/get_chromosome_lengths.py +32 -0
  59. smftools/informatics/helpers/get_native_references.py +28 -0
  60. smftools/informatics/helpers/index_fasta.py +12 -0
  61. smftools/informatics/helpers/make_dirs.py +21 -0
  62. smftools/informatics/helpers/make_modbed.py +27 -0
  63. smftools/informatics/helpers/modQC.py +27 -0
  64. smftools/informatics/helpers/modcall.py +36 -0
  65. smftools/informatics/helpers/modkit_extract_to_adata.py +887 -0
  66. smftools/informatics/helpers/ohe_batching.py +76 -0
  67. smftools/informatics/helpers/ohe_layers_decode.py +32 -0
  68. smftools/informatics/helpers/one_hot_decode.py +27 -0
  69. smftools/informatics/helpers/one_hot_encode.py +57 -0
  70. smftools/informatics/helpers/plot_bed_histograms.py +269 -0
  71. smftools/informatics/helpers/run_multiqc.py +28 -0
  72. smftools/informatics/helpers/separate_bam_by_bc.py +43 -0
  73. smftools/informatics/helpers/split_and_index_BAM.py +32 -0
  74. smftools/informatics/readwrite.py +106 -0
  75. smftools/informatics/subsample_fasta_from_bed.py +47 -0
  76. smftools/informatics/subsample_pod5.py +104 -0
  77. smftools/load_adata.py +1346 -0
  78. smftools/machine_learning/__init__.py +12 -0
  79. smftools/machine_learning/data/__init__.py +2 -0
  80. smftools/machine_learning/data/anndata_data_module.py +234 -0
  81. smftools/machine_learning/data/preprocessing.py +6 -0
  82. smftools/machine_learning/evaluation/__init__.py +2 -0
  83. smftools/machine_learning/evaluation/eval_utils.py +31 -0
  84. smftools/machine_learning/evaluation/evaluators.py +223 -0
  85. smftools/machine_learning/inference/__init__.py +3 -0
  86. smftools/machine_learning/inference/inference_utils.py +27 -0
  87. smftools/machine_learning/inference/lightning_inference.py +68 -0
  88. smftools/machine_learning/inference/sklearn_inference.py +55 -0
  89. smftools/machine_learning/inference/sliding_window_inference.py +114 -0
  90. smftools/machine_learning/models/__init__.py +9 -0
  91. smftools/machine_learning/models/base.py +295 -0
  92. smftools/machine_learning/models/cnn.py +138 -0
  93. smftools/machine_learning/models/lightning_base.py +345 -0
  94. smftools/machine_learning/models/mlp.py +26 -0
  95. smftools/machine_learning/models/positional.py +18 -0
  96. smftools/machine_learning/models/rnn.py +17 -0
  97. smftools/machine_learning/models/sklearn_models.py +273 -0
  98. smftools/machine_learning/models/transformer.py +303 -0
  99. smftools/machine_learning/models/wrappers.py +20 -0
  100. smftools/machine_learning/training/__init__.py +2 -0
  101. smftools/machine_learning/training/train_lightning_model.py +135 -0
  102. smftools/machine_learning/training/train_sklearn_model.py +114 -0
  103. smftools/machine_learning/utils/__init__.py +2 -0
  104. smftools/machine_learning/utils/device.py +10 -0
  105. smftools/machine_learning/utils/grl.py +14 -0
  106. smftools/plotting/__init__.py +18 -0
  107. smftools/plotting/autocorrelation_plotting.py +611 -0
  108. smftools/plotting/classifiers.py +355 -0
  109. smftools/plotting/general_plotting.py +682 -0
  110. smftools/plotting/hmm_plotting.py +260 -0
  111. smftools/plotting/position_stats.py +462 -0
  112. smftools/plotting/qc_plotting.py +270 -0
  113. smftools/preprocessing/__init__.py +38 -0
  114. smftools/preprocessing/add_read_length_and_mapping_qc.py +129 -0
  115. smftools/preprocessing/append_base_context.py +122 -0
  116. smftools/preprocessing/append_binary_layer_by_base_context.py +143 -0
  117. smftools/preprocessing/archives/mark_duplicates.py +146 -0
  118. smftools/preprocessing/archives/preprocessing.py +614 -0
  119. smftools/preprocessing/archives/remove_duplicates.py +21 -0
  120. smftools/preprocessing/binarize_on_Youden.py +45 -0
  121. smftools/preprocessing/binary_layers_to_ohe.py +40 -0
  122. smftools/preprocessing/calculate_complexity.py +72 -0
  123. smftools/preprocessing/calculate_complexity_II.py +248 -0
  124. smftools/preprocessing/calculate_consensus.py +47 -0
  125. smftools/preprocessing/calculate_coverage.py +51 -0
  126. smftools/preprocessing/calculate_pairwise_differences.py +49 -0
  127. smftools/preprocessing/calculate_pairwise_hamming_distances.py +27 -0
  128. smftools/preprocessing/calculate_position_Youden.py +115 -0
  129. smftools/preprocessing/calculate_read_length_stats.py +79 -0
  130. smftools/preprocessing/calculate_read_modification_stats.py +101 -0
  131. smftools/preprocessing/clean_NaN.py +62 -0
  132. smftools/preprocessing/filter_adata_by_nan_proportion.py +31 -0
  133. smftools/preprocessing/filter_reads_on_length_quality_mapping.py +158 -0
  134. smftools/preprocessing/filter_reads_on_modification_thresholds.py +352 -0
  135. smftools/preprocessing/flag_duplicate_reads.py +1351 -0
  136. smftools/preprocessing/invert_adata.py +37 -0
  137. smftools/preprocessing/load_sample_sheet.py +53 -0
  138. smftools/preprocessing/make_dirs.py +21 -0
  139. smftools/preprocessing/min_non_diagonal.py +25 -0
  140. smftools/preprocessing/recipes.py +127 -0
  141. smftools/preprocessing/subsample_adata.py +58 -0
  142. smftools/readwrite.py +1004 -0
  143. smftools/tools/__init__.py +20 -0
  144. smftools/tools/archived/apply_hmm.py +202 -0
  145. smftools/tools/archived/classifiers.py +787 -0
  146. smftools/tools/archived/classify_methylated_features.py +66 -0
  147. smftools/tools/archived/classify_non_methylated_features.py +75 -0
  148. smftools/tools/archived/subset_adata_v1.py +32 -0
  149. smftools/tools/archived/subset_adata_v2.py +46 -0
  150. smftools/tools/calculate_umap.py +62 -0
  151. smftools/tools/cluster_adata_on_methylation.py +105 -0
  152. smftools/tools/general_tools.py +69 -0
  153. smftools/tools/position_stats.py +601 -0
  154. smftools/tools/read_stats.py +184 -0
  155. smftools/tools/spatial_autocorrelation.py +562 -0
  156. smftools/tools/subset_adata.py +28 -0
  157. {smftools-0.1.6.dist-info → smftools-0.2.1.dist-info}/METADATA +9 -2
  158. smftools-0.2.1.dist-info/RECORD +161 -0
  159. smftools-0.2.1.dist-info/entry_points.txt +2 -0
  160. smftools-0.1.6.dist-info/RECORD +0 -4
  161. {smftools-0.1.6.dist-info → smftools-0.2.1.dist-info}/WHEEL +0 -0
  162. {smftools-0.1.6.dist-info → smftools-0.2.1.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,59 @@
1
+ ## bam_conversion
2
+
3
+ def bam_conversion(fasta, output_directory, conversion_types, strands, basecalled_path, split_dir, mapping_threshold, experiment_name, bam_suffix):
4
+ """
5
+ Converts a BAM file from a nanopore conversion SMF experiment to an adata object.
6
+
7
+ Parameters:
8
+ fasta (str): File path to the reference genome to align to.
9
+ output_directory (str): A file path to the directory to output all the analyses.
10
+ conversion_type (list): A list of strings of the conversion types to use in the analysis.
11
+ strands (list): A list of converstion strands to use in the experiment.
12
+ basecalled_path (str): a string representing the file path to the experiment BAM or FASTQ file.
13
+ split_dir (str): A string representing the file path to the directory to split the BAMs into.
14
+ mapping_threshold (float): A value in between 0 and 1 to threshold the minimal fraction of aligned reads which map to the reference region. References with values above the threshold are included in the output adata.
15
+ experiment_name (str): A string to provide an experiment name to the output adata file.
16
+ bam_suffix (str): A suffix to add to the bam file.
17
+
18
+ Returns:
19
+ None
20
+ """
21
+ from .helpers import align_and_sort_BAM, converted_BAM_to_adata, generate_converted_FASTA, split_and_index_BAM, make_dirs
22
+ import os
23
+ input_basecalled_basename = os.path.basename(basecalled_path)
24
+ bam_basename = input_basecalled_basename.split(".")[0]
25
+ output_bam=f"{output_directory}/{bam_basename}"
26
+ aligned_BAM=f"{output_bam}_aligned"
27
+ aligned_sorted_BAM=f"{aligned_BAM}_sorted"
28
+
29
+ os.chdir(output_directory)
30
+
31
+ # 1) Convert FASTA file
32
+ fasta_basename = os.path.basename(fasta)
33
+ converted_FASTA_basename = fasta_basename.split('.fa')[0]+'_converted.fasta'
34
+ converted_FASTA = os.path.join(output_directory, converted_FASTA_basename)
35
+ if 'converted.fa' in fasta:
36
+ print(fasta + ' is already converted. Using existing converted FASTA.')
37
+ converted_FASTA = fasta
38
+ elif os.path.exists(converted_FASTA):
39
+ print(converted_FASTA + ' already exists. Using existing converted FASTA.')
40
+ else:
41
+ generate_converted_FASTA(fasta, conversion_types, strands, converted_FASTA)
42
+
43
+ # 2) Align the basecalled file to the converted reference FASTA and sort the bam on positional coordinates. Also make an index and a bed file of mapped reads
44
+ aligned_output = aligned_BAM + bam_suffix
45
+ sorted_output = aligned_sorted_BAM + bam_suffix
46
+ if os.path.exists(aligned_output) and os.path.exists(sorted_output):
47
+ print(sorted_output + ' already exists. Using existing aligned/sorted BAM.')
48
+ else:
49
+ align_and_sort_BAM(converted_FASTA, basecalled_path, bam_suffix, output_directory)
50
+
51
+ ### 3) Split the aligned and sorted BAM files by barcode (BC Tag) into the split_BAM directory###
52
+ if os.path.isdir(split_dir):
53
+ print(split_dir + ' already exists. Using existing aligned/sorted/split BAMs.')
54
+ else:
55
+ make_dirs([split_dir])
56
+ split_and_index_BAM(aligned_sorted_BAM, split_dir, bam_suffix, output_directory)
57
+
58
+ # 4) Take the converted BAM and load it into an adata object.
59
+ converted_BAM_to_adata(converted_FASTA, split_dir, mapping_threshold, experiment_name, conversion_types, bam_suffix)
@@ -0,0 +1,63 @@
1
+ ## bam_direct
2
+
3
+ def bam_direct(fasta, output_directory, mod_list, thresholds, bam_path, split_dir, mapping_threshold, experiment_name, bam_suffix, batch_size):
4
+ """
5
+ Converts a POD5 file from a nanopore native SMF experiment to an adata object.
6
+
7
+ Parameters:
8
+ fasta (str): File path to the reference genome to align to.
9
+ output_directory (str): A file path to the directory to output all the analyses.
10
+ mod_list (list): A list of strings of the modification types to use in the analysis.
11
+ thresholds (list): A list of floats to pass for call thresholds.
12
+ bam_path (str): a string representing the file path to the the BAM file.
13
+ split_dir (str): A string representing the file path to the directory to split the BAMs into.
14
+ mapping_threshold (float): A value in between 0 and 1 to threshold the minimal fraction of aligned reads which map to the reference region. References with values above the threshold are included in the output adata.
15
+ experiment_name (str): A string to provide an experiment name to the output adata file.
16
+ bam_suffix (str): A suffix to add to the bam file.
17
+ batch_size (int): An integer number of TSV files to analyze in memory at once while loading the final adata object.
18
+
19
+ Returns:
20
+ None
21
+ """
22
+ from .helpers import align_and_sort_BAM, extract_mods, make_modbed, modkit_extract_to_adata, modQC, split_and_index_BAM, make_dirs
23
+ import os
24
+ input_bam_base = os.path.basename(bam_path)
25
+ bam_basename = input_bam_base.split(bam_suffix)[0]
26
+ output_bam=f"{output_directory}/{bam_basename}"
27
+ aligned_BAM=f"{output_bam}_aligned"
28
+ aligned_sorted_BAM=f"{aligned_BAM}_sorted"
29
+ mod_bed_dir=f"{output_directory}/split_mod_beds"
30
+ mod_tsv_dir=f"{output_directory}/split_mod_tsvs"
31
+
32
+ aligned_output = aligned_BAM + bam_suffix
33
+ aligned_sorted_output = aligned_sorted_BAM + bam_suffix
34
+ mod_map = {'6mA': '6mA', '5mC_5hmC': '5mC'}
35
+ mods = [mod_map[mod] for mod in mod_list]
36
+
37
+ os.chdir(output_directory)
38
+
39
+ # 1) Align the BAM to the reference FASTA. Also make an index and a bed file of mapped reads
40
+ if os.path.exists(aligned_output) and os.path.exists(aligned_sorted_output):
41
+ print(aligned_sorted_output + ' already exists. Using existing aligned/sorted BAM.')
42
+ else:
43
+ align_and_sort_BAM(fasta, bam_path, bam_suffix, output_directory)
44
+ # 2) Split the aligned and sorted BAM files by barcode (BC Tag) into the split_BAM directory
45
+ if os.path.isdir(split_dir):
46
+ print(split_dir + ' already exists. Using existing aligned/sorted/split BAMs.')
47
+ else:
48
+ make_dirs([split_dir])
49
+ split_and_index_BAM(aligned_sorted_BAM, split_dir, bam_suffix, output_directory)
50
+ # 3) Using nanopore modkit to work with modified BAM files ###
51
+ if os.path.isdir(mod_bed_dir):
52
+ print(mod_bed_dir + ' already exists')
53
+ else:
54
+ make_dirs([mod_bed_dir])
55
+ modQC(aligned_sorted_output, thresholds) # get QC metrics for mod calls
56
+ make_modbed(aligned_sorted_output, thresholds, mod_bed_dir) # Generate bed files of position methylation summaries for every sample
57
+ if os.path.isdir(mod_tsv_dir):
58
+ print(mod_tsv_dir + ' already exists')
59
+ else:
60
+ make_dirs([mod_tsv_dir])
61
+ extract_mods(thresholds, mod_tsv_dir, split_dir, bam_suffix) # Extract methylations calls for split BAM files into split TSV files
62
+ #4 Load the modification data from TSVs into an adata object
63
+ modkit_extract_to_adata(fasta, split_dir, mapping_threshold, experiment_name, mods, batch_size, mod_tsv_dir)
@@ -0,0 +1,71 @@
1
+ ## basecalls_to_adata
2
+
3
+ def basecalls_to_adata(config_path):
4
+ """
5
+ High-level function to call for loading basecalled SMF data from a BAM file into an adata object. Also works with FASTQ for conversion SMF.
6
+
7
+ Parameters:
8
+ config_path (str): A string representing the file path to the experiment configuration csv file.
9
+
10
+ Returns:
11
+ None
12
+ """
13
+ from .helpers import LoadExperimentConfig, make_dirs
14
+ from .subsample_fasta_from_bed import subsample_fasta_from_bed
15
+ import os
16
+ import numpy as np
17
+ bam_suffix = '.bam' # If different, change from here.
18
+ split_dir = 'split_BAMs' # If different, change from here.
19
+ strands = ['bottom', 'top'] # If different, change from here. Having both listed generally doesn't slow things down too much.
20
+ conversions = ['unconverted'] # The name to use for the unconverted files. If different, change from here.
21
+
22
+ # Load experiment config parameters into global variables
23
+ experiment_config = LoadExperimentConfig(config_path)
24
+ var_dict = experiment_config.var_dict
25
+
26
+ # These below variables will point to the value np.nan if they are either empty in the experiment_config.csv or if the variable is fully omitted from the csv.
27
+ default_value = None
28
+
29
+ conversion_types = var_dict.get('conversion_types', default_value)
30
+ output_directory = var_dict.get('output_directory', default_value)
31
+ smf_modality = var_dict.get('smf_modality', default_value)
32
+ fasta = var_dict.get('fasta', default_value)
33
+ fasta_regions_of_interest = var_dict.get("fasta_regions_of_interest", default_value)
34
+ basecalled_path = var_dict.get('basecalled_path', default_value)
35
+ mapping_threshold = var_dict.get('mapping_threshold', default_value)
36
+ experiment_name = var_dict.get('experiment_name', default_value)
37
+ filter_threshold = var_dict.get('filter_threshold', default_value)
38
+ m6A_threshold = var_dict.get('m6A_threshold', default_value)
39
+ m5C_threshold = var_dict.get('m5C_threshold', default_value)
40
+ hm5C_threshold = var_dict.get('hm5C_threshold', default_value)
41
+ mod_list = var_dict.get('mod_list', default_value)
42
+ batch_size = var_dict.get('batch_size', default_value)
43
+ thresholds = [filter_threshold, m6A_threshold, m5C_threshold, hm5C_threshold]
44
+
45
+ split_path = os.path.join(output_directory, split_dir)
46
+
47
+ make_dirs([output_directory])
48
+ os.chdir(output_directory)
49
+
50
+ conversions += conversion_types
51
+
52
+ # If a bed file is passed, subsample the input FASTA on regions of interest and use the subsampled FASTA.
53
+ if fasta_regions_of_interest != None:
54
+ if '.bed' in fasta_regions_of_interest:
55
+ fasta_basename = os.path.basename(fasta)
56
+ bed_basename_minus_suffix = os.path.basename(fasta_regions_of_interest).split('.bed')[0]
57
+ output_FASTA = bed_basename_minus_suffix + '_' + fasta_basename
58
+ subsample_fasta_from_bed(fasta, fasta_regions_of_interest, output_directory, output_FASTA)
59
+ fasta = output_FASTA
60
+
61
+ if smf_modality == 'conversion':
62
+ from .bam_conversion import bam_conversion
63
+ bam_conversion(fasta, output_directory, conversions, strands, basecalled_path, split_path, mapping_threshold, experiment_name, bam_suffix)
64
+ elif smf_modality == 'direct':
65
+ if bam_suffix in basecalled_path:
66
+ from .bam_direct import bam_direct
67
+ bam_direct(fasta, output_directory, mod_list, thresholds, basecalled_path, split_path, mapping_threshold, experiment_name, bam_suffix, batch_size)
68
+ else:
69
+ print('basecalls_to_adata function only work with the direct modality when the input filetype is BAM and not FASTQ.')
70
+ else:
71
+ print("Error")
@@ -0,0 +1,132 @@
1
+ ## conversion_smf
2
+
3
+ def conversion_smf(fasta, output_directory, conversion_types, strands, model_dir, model, input_data_path, split_dir, barcode_kit, mapping_threshold, experiment_name, bam_suffix, basecall, barcode_both_ends, trim, device, make_bigwigs, threads, input_already_demuxed):
4
+ """
5
+ Processes sequencing data from a conversion SMF experiment to an adata object.
6
+
7
+ Parameters:
8
+ fasta (str): File path to the reference genome to align to.
9
+ output_directory (str): A file path to the directory to output all the analyses.
10
+ conversion_type (list): A list of strings of the conversion types to use in the analysis.
11
+ strands (list): A list of converstion strands to use in the experiment.
12
+ model_dir (str): a string representing the file path to the dorado basecalling model directory.
13
+ model (str): a string representing the dorado basecalling model.
14
+ input_data_path (str): a string representing the file path to the experiment directory/file containing sequencing data
15
+ split_dir (str): A string representing the file path to the directory to split the BAMs into.
16
+ barcode_kit (str): A string representing the barcoding kit used in the experiment.
17
+ mapping_threshold (float): A value in between 0 and 1 to threshold the minimal fraction of aligned reads which map to the reference region. References with values above the threshold are included in the output adata.
18
+ experiment_name (str): A string to provide an experiment name to the output adata file.
19
+ bam_suffix (str): A suffix to add to the bam file.
20
+ basecall (bool): Whether to go through basecalling or not.
21
+ barcode_both_ends (bool): Whether to require a barcode detection on both ends for demultiplexing.
22
+ trim (bool): Whether to trim barcodes, adapters, and primers from read ends.
23
+ device (str): Device to use for basecalling. auto, metal, cpu, cuda
24
+ make_bigwigs (bool): Whether to make bigwigs
25
+ threads (int): cpu threads available for processing.
26
+ input_already_demuxed (bool): Whether the input files were already demultiplexed
27
+
28
+ Returns:
29
+ final_adata_path (str): Path to the final adata object
30
+ sorted_output (str): Path to the aligned, sorted BAM
31
+ """
32
+ from .helpers import align_and_sort_BAM, aligned_BAM_to_bed, canoncall, converted_BAM_to_adata_II, generate_converted_FASTA, get_chromosome_lengths, demux_and_index_BAM, make_dirs, bam_qc, run_multiqc, split_and_index_BAM
33
+ import os
34
+ import glob
35
+
36
+ if basecall:
37
+ model_basename = os.path.basename(model)
38
+ model_basename = model_basename.replace('.', '_')
39
+ bam=f"{output_directory}/{model_basename}_canonical_basecalls"
40
+ else:
41
+ bam_base=os.path.basename(input_data_path).split('.bam')[0]
42
+ bam=os.path.join(output_directory, bam_base)
43
+ aligned_BAM=f"{bam}_aligned"
44
+ aligned_sorted_BAM=f"{aligned_BAM}_sorted"
45
+
46
+ os.chdir(output_directory)
47
+
48
+ # 1) Convert FASTA file
49
+ fasta_basename = os.path.basename(fasta)
50
+ converted_FASTA_basename = fasta_basename.split('.fa')[0]+'_converted.fasta'
51
+ converted_FASTA = os.path.join(output_directory, converted_FASTA_basename)
52
+ if 'converted.fa' in fasta:
53
+ print(fasta + ' is already converted. Using existing converted FASTA.')
54
+ converted_FASTA = fasta
55
+ elif os.path.exists(converted_FASTA):
56
+ print(converted_FASTA + ' already exists. Using existing converted FASTA.')
57
+ else:
58
+ generate_converted_FASTA(fasta, conversion_types, strands, converted_FASTA)
59
+
60
+ # Make a FAI and .chrom.names file for the converted fasta
61
+ get_chromosome_lengths(converted_FASTA)
62
+
63
+ # 2) Basecall from the input POD5 to generate a singular output BAM
64
+ if basecall:
65
+ canoncall_output = bam + bam_suffix
66
+ if os.path.exists(canoncall_output):
67
+ print(canoncall_output + ' already exists. Using existing basecalled BAM.')
68
+ else:
69
+ canoncall(model_dir, model, input_data_path, barcode_kit, bam, bam_suffix, barcode_both_ends, trim, device)
70
+ else:
71
+ canoncall_output = input_data_path
72
+
73
+ # 3) Align the BAM to the converted reference FASTA and sort the bam on positional coordinates. Also make an index and a bed file of mapped reads
74
+ aligned_output = aligned_BAM + bam_suffix
75
+ sorted_output = aligned_sorted_BAM + bam_suffix
76
+ if os.path.exists(aligned_output) and os.path.exists(sorted_output):
77
+ print(sorted_output + ' already exists. Using existing aligned/sorted BAM.')
78
+ else:
79
+ align_and_sort_BAM(converted_FASTA, canoncall_output, bam_suffix, output_directory, make_bigwigs, threads)
80
+
81
+ # Make beds and provide basic histograms
82
+ bed_dir = os.path.join(output_directory, 'beds')
83
+ if os.path.isdir(bed_dir):
84
+ print(bed_dir + ' already exists. Skipping BAM -> BED conversion for ' + sorted_output)
85
+ else:
86
+ aligned_BAM_to_bed(aligned_output, output_directory, converted_FASTA, make_bigwigs, threads)
87
+
88
+ ### 4) Split the aligned and sorted BAM files by barcode (BC Tag) into the split_BAM directory###
89
+ if barcode_both_ends:
90
+ split_dir = split_dir + '_both_ends_barcoded'
91
+ else:
92
+ split_dir = split_dir + '_at_least_one_end_barcoded'
93
+
94
+ if os.path.isdir(split_dir):
95
+ print(split_dir + ' already exists. Using existing demultiplexed BAMs.')
96
+ bam_pattern = '*' + bam_suffix
97
+ bam_files = glob.glob(os.path.join(split_dir, bam_pattern))
98
+ bam_files = [bam for bam in bam_files if '.bai' not in bam and 'unclassified' not in bam]
99
+ bam_files.sort()
100
+ else:
101
+ make_dirs([split_dir])
102
+ if input_already_demuxed:
103
+ bam_files = split_and_index_BAM(aligned_sorted_BAM, split_dir, bam_suffix, output_directory) # custom for non-nanopore
104
+ else:
105
+ bam_files = demux_and_index_BAM(aligned_sorted_BAM, split_dir, bam_suffix, barcode_kit, barcode_both_ends, trim, fasta, make_bigwigs, threads)
106
+
107
+ # Make beds and provide basic histograms
108
+ bed_dir = os.path.join(split_dir, 'beds')
109
+ if os.path.isdir(bed_dir):
110
+ print(bed_dir + ' already exists. Skipping BAM -> BED conversion for demultiplexed bams')
111
+ else:
112
+ for bam in bam_files:
113
+ aligned_BAM_to_bed(bam, split_dir, converted_FASTA, make_bigwigs, threads)
114
+
115
+ # 5) Samtools QC metrics on split BAM files
116
+ bam_qc_dir = f"{split_dir}/bam_qc"
117
+ if os.path.isdir(bam_qc_dir):
118
+ print(bam_qc_dir + ' already exists. Using existing BAM QC calculations.')
119
+ else:
120
+ make_dirs([bam_qc_dir])
121
+ bam_qc(bam_files, bam_qc_dir, threads, modality='conversion')
122
+
123
+ # multiqc ###
124
+ if os.path.isdir(f"{split_dir}/multiqc"):
125
+ print(f"{split_dir}/multiqc" + ' already exists, skipping multiqc')
126
+ else:
127
+ run_multiqc(split_dir, f"{split_dir}/multiqc")
128
+
129
+ # 6) Take the converted BAM and load it into an adata object.
130
+ final_adata, final_adata_path = converted_BAM_to_adata_II(converted_FASTA, split_dir, mapping_threshold, experiment_name, conversion_types, bam_suffix, device)
131
+
132
+ return final_adata, final_adata_path, sorted_output, bam_files
@@ -0,0 +1,132 @@
1
+
2
+ def deaminase_smf(fasta, output_directory, conversion_types, strands, model_dir, model, input_data_path, split_dir, barcode_kit, mapping_threshold, experiment_name, bam_suffix, basecall, barcode_both_ends, trim, device, make_bigwigs, threads, input_already_demuxed):
3
+ """
4
+ Processes sequencing data from a conversion SMF experiment to an adata object.
5
+
6
+ Parameters:
7
+ fasta (str): File path to the reference genome to align to.
8
+ output_directory (str): A file path to the directory to output all the analyses.
9
+ conversion_type (list): A list of strings of the conversion types to use in the analysis.
10
+ strands (list): A list of converstion strands to use in the experiment.
11
+ model_dir (str): a string representing the file path to the dorado basecalling model directory.
12
+ model (str): a string representing the dorado basecalling model.
13
+ input_data_path (str): a string representing the file path to the experiment directory/file containing sequencing data
14
+ split_dir (str): A string representing the file path to the directory to split the BAMs into.
15
+ barcode_kit (str): A string representing the barcoding kit used in the experiment.
16
+ mapping_threshold (float): A value in between 0 and 1 to threshold the minimal fraction of aligned reads which map to the reference region. References with values above the threshold are included in the output adata.
17
+ experiment_name (str): A string to provide an experiment name to the output adata file.
18
+ bam_suffix (str): A suffix to add to the bam file.
19
+ basecall (bool): Whether to go through basecalling or not.
20
+ barcode_both_ends (bool): Whether to require a barcode detection on both ends for demultiplexing.
21
+ trim (bool): Whether to trim barcodes, adapters, and primers from read ends.
22
+ device (str): Device to use for basecalling. auto, metal, cpu, cuda
23
+ make_bigwigs (bool): Whether to make bigwigs
24
+ threads (int): cpu threads available for processing.
25
+ input_already_demuxed (bool): Whether the input files were already demultiplexed
26
+
27
+ Returns:
28
+ final_adata_path (str): Path to the final adata object
29
+ sorted_output (str): Path to the aligned, sorted BAM
30
+ """
31
+ from .helpers import align_and_sort_BAM, aligned_BAM_to_bed, canoncall, converted_BAM_to_adata_II, generate_converted_FASTA, get_chromosome_lengths, demux_and_index_BAM, make_dirs, bam_qc, run_multiqc, split_and_index_BAM
32
+ import os
33
+ import shutil
34
+ import glob
35
+
36
+ if basecall:
37
+ model_basename = os.path.basename(model)
38
+ model_basename = model_basename.replace('.', '_')
39
+ bam=f"{output_directory}/{model_basename}_canonical_basecalls"
40
+ else:
41
+ bam_base=os.path.basename(input_data_path).split('.bam')[0]
42
+ bam=os.path.join(output_directory, bam_base)
43
+ aligned_BAM=f"{bam}_aligned"
44
+ aligned_sorted_BAM=f"{aligned_BAM}_sorted"
45
+
46
+ os.chdir(output_directory)
47
+
48
+ # 1) Convert FASTA file
49
+ fasta_basename = os.path.basename(fasta)
50
+ converted_FASTA_basename = fasta_basename.split('.fa')[0]+'_converted.fasta'
51
+ converted_FASTA = os.path.join(output_directory, converted_FASTA_basename)
52
+ if 'converted.fa' in fasta:
53
+ print(fasta + ' is already converted. Using existing converted FASTA.')
54
+ converted_FASTA = fasta
55
+ elif os.path.exists(converted_FASTA):
56
+ print(converted_FASTA + ' already exists. Using existing converted FASTA.')
57
+ else:
58
+ generate_converted_FASTA(fasta, conversion_types, strands, converted_FASTA)
59
+
60
+ # Make a FAI and .chrom.names file for the converted fasta
61
+ get_chromosome_lengths(converted_FASTA)
62
+
63
+ # 2) Basecall from the input POD5 to generate a singular output BAM
64
+ if basecall:
65
+ canoncall_output = bam + bam_suffix
66
+ if os.path.exists(canoncall_output):
67
+ print(canoncall_output + ' already exists. Using existing basecalled BAM.')
68
+ else:
69
+ canoncall(model_dir, model, input_data_path, barcode_kit, bam, bam_suffix, barcode_both_ends, trim, device)
70
+ else:
71
+ canoncall_output = input_data_path
72
+
73
+ # 3) Align the BAM to the reference FASTA and sort the bam on positional coordinates. Also make an index and a bed file of mapped reads
74
+ aligned_output = aligned_BAM + bam_suffix
75
+ sorted_output = aligned_sorted_BAM + bam_suffix
76
+ if os.path.exists(aligned_output) and os.path.exists(sorted_output):
77
+ print(sorted_output + ' already exists. Using existing aligned/sorted BAM.')
78
+ else:
79
+ align_and_sort_BAM(converted_FASTA, canoncall_output, bam_suffix, output_directory, make_bigwigs, threads, deaminase_alignment=True)
80
+
81
+ # Make beds and provide basic histograms
82
+ bed_dir = os.path.join(output_directory, 'beds')
83
+ if os.path.isdir(bed_dir):
84
+ print(bed_dir + ' already exists. Skipping BAM -> BED conversion for ' + sorted_output)
85
+ else:
86
+ aligned_BAM_to_bed(aligned_output, output_directory, converted_FASTA, make_bigwigs, threads)
87
+
88
+ ### 4) Split the aligned and sorted BAM files by barcode (BC Tag) into the split_BAM directory###
89
+ if barcode_both_ends:
90
+ split_dir = split_dir + '_both_ends_barcoded'
91
+ else:
92
+ split_dir = split_dir + '_at_least_one_end_barcoded'
93
+
94
+ if os.path.isdir(split_dir):
95
+ print(split_dir + ' already exists. Using existing demultiplexed BAMs.')
96
+ bam_pattern = '*' + bam_suffix
97
+ bam_files = glob.glob(os.path.join(split_dir, bam_pattern))
98
+ bam_files = [bam for bam in bam_files if '.bai' not in bam and 'unclassified' not in bam]
99
+ bam_files.sort()
100
+ else:
101
+ make_dirs([split_dir])
102
+ if input_already_demuxed:
103
+ bam_files = split_and_index_BAM(aligned_sorted_BAM, split_dir, bam_suffix, output_directory) # custom for non-nanopore
104
+ else:
105
+ bam_files = demux_and_index_BAM(aligned_sorted_BAM, split_dir, bam_suffix, barcode_kit, barcode_both_ends, trim, fasta, make_bigwigs, threads)
106
+
107
+ # Make beds and provide basic histograms
108
+ bed_dir = os.path.join(split_dir, 'beds')
109
+ if os.path.isdir(bed_dir):
110
+ print(bed_dir + ' already exists. Skipping BAM -> BED conversion for demultiplexed bams')
111
+ else:
112
+ for bam in bam_files:
113
+ aligned_BAM_to_bed(bam, split_dir, converted_FASTA, make_bigwigs, threads)
114
+
115
+ # 5) Samtools QC metrics on split BAM files
116
+ bam_qc_dir = f"{split_dir}/bam_qc"
117
+ if os.path.isdir(bam_qc_dir):
118
+ print(bam_qc_dir + ' already exists. Using existing BAM QC calculations.')
119
+ else:
120
+ make_dirs([bam_qc_dir])
121
+ bam_qc(bam_files, bam_qc_dir, threads, modality='conversion')
122
+
123
+ # multiqc ###
124
+ if os.path.isdir(f"{split_dir}/multiqc"):
125
+ print(f"{split_dir}/multiqc" + ' already exists, skipping multiqc')
126
+ else:
127
+ run_multiqc(split_dir, f"{split_dir}/multiqc")
128
+
129
+ # 6) Take the converted BAM and load it into an adata object.
130
+ final_adata, final_adata_path = converted_BAM_to_adata_II(converted_FASTA, split_dir, mapping_threshold, experiment_name, conversion_types, bam_suffix, device, deaminase_footprinting=True)
131
+
132
+ return final_adata, final_adata_path, sorted_output, bam_files
@@ -0,0 +1,137 @@
1
+ ## direct_smf
2
+
3
+ def direct_smf(fasta, output_directory, mod_list, model_dir, model, thresholds, input_data_path, split_dir, barcode_kit, mapping_threshold, experiment_name, bam_suffix, batch_size, basecall, barcode_both_ends, trim, device, make_bigwigs, skip_unclassified, delete_batch_hdfs, threads):
4
+ """
5
+ Processes sequencing data from a direct methylation detection Nanopore SMF experiment to an AnnData object.
6
+
7
+ Parameters:
8
+ fasta (str): File path to the reference genome to align to.
9
+ output_directory (str): A file path to the directory to output all the analyses.
10
+ mod_list (list): A list of strings of the modification types to use in the analysis.
11
+ model_dir (str): a string representing the file path to the dorado basecalling model directory.
12
+ model (str): a string representing the dorado basecalling model.
13
+ thresholds (list): A list of floats to pass for call thresholds.
14
+ input_data_path (str): a string representing the file path to the experiment directory containing the input sequencing files.
15
+ split_dir (str): A string representing the file path to the directory to split the BAMs into.
16
+ barcode_kit (str): A string representing the barcoding kit used in the experiment.
17
+ mapping_threshold (float): A value in between 0 and 1 to threshold the minimal fraction of aligned reads which map to the reference region. References with values above the threshold are included in the output adata.
18
+ experiment_name (str): A string to provide an experiment name to the output adata file.
19
+ bam_suffix (str): A suffix to add to the bam file.
20
+ batch_size (int): An integer number of TSV files to analyze in memory at once while loading the final adata object.
21
+ basecall (bool): Whether to basecall
22
+ barcode_both_ends (bool): Whether to require a barcode detection on both ends for demultiplexing.
23
+ trim (bool): Whether to trim barcodes, adapters, and primers from read ends
24
+ device (str): Device to use for basecalling. auto, metal, cpu, cuda
25
+ make_bigwigs (bool): Whether to make bigwigs
26
+ skip_unclassified (bool): Whether to skip unclassified reads when extracting mods and loading anndata
27
+ delete_batch_hdfs (bool): Whether to delete intermediate hdf5 files.
28
+ threads (int): cpu threads available for processing.
29
+
30
+ Returns:
31
+ final_adata_path (str): Path to the final adata object
32
+ sorted_output (str): Path to the aligned, sorted BAM
33
+ """
34
+ from .helpers import align_and_sort_BAM, aligned_BAM_to_bed, extract_mods, get_chromosome_lengths, make_modbed, modcall, modkit_extract_to_adata, modQC, demux_and_index_BAM, make_dirs, bam_qc, run_multiqc
35
+ import os
36
+
37
+ if basecall:
38
+ model_basename = os.path.basename(model)
39
+ model_basename = model_basename.replace('.', '_')
40
+ mod_string = "_".join(mod_list)
41
+ bam=f"{output_directory}/{model_basename}_{mod_string}_calls"
42
+ else:
43
+ bam_base=os.path.basename(input_data_path).split('.bam')[0]
44
+ bam=os.path.join(output_directory, bam_base)
45
+ aligned_BAM=f"{bam}_aligned"
46
+ aligned_sorted_BAM=f"{aligned_BAM}_sorted"
47
+
48
+ if barcode_both_ends:
49
+ split_dir = split_dir + '_both_ends_barcoded'
50
+ else:
51
+ split_dir = split_dir + '_at_least_one_end_barcoded'
52
+
53
+ mod_bed_dir=f"{split_dir}/split_mod_beds"
54
+ mod_tsv_dir=f"{split_dir}/split_mod_tsvs"
55
+ bam_qc_dir = f"{split_dir}/bam_qc"
56
+
57
+ aligned_sorted_output = aligned_sorted_BAM + bam_suffix
58
+ mod_map = {'6mA': '6mA', '5mC_5hmC': '5mC'}
59
+ mods = [mod_map[mod] for mod in mod_list]
60
+
61
+ # Make a FAI and .chrom.names file for the fasta
62
+ get_chromosome_lengths(fasta)
63
+
64
+ os.chdir(output_directory)
65
+
66
+ # 1) Basecall using dorado
67
+ if basecall:
68
+ modcall_output = bam + bam_suffix
69
+ if os.path.exists(modcall_output):
70
+ print(modcall_output + ' already exists. Using existing basecalled BAM.')
71
+ else:
72
+ modcall(model_dir, model, input_data_path, barcode_kit, mod_list, bam, bam_suffix, barcode_both_ends, trim, device)
73
+ else:
74
+ modcall_output = input_data_path
75
+
76
+ # 2) Align the BAM to the reference FASTA. Also make an index and a bed file of mapped reads
77
+ aligned_output = aligned_BAM + bam_suffix
78
+ sorted_output = aligned_sorted_BAM + bam_suffix
79
+ if os.path.exists(aligned_output) and os.path.exists(sorted_output):
80
+ print(sorted_output + ' already exists. Using existing aligned/sorted BAM.')
81
+ else:
82
+ align_and_sort_BAM(fasta, modcall_output, bam_suffix, output_directory, make_bigwigs, threads)
83
+
84
+ # Make beds and provide basic histograms
85
+ bed_dir = os.path.join(output_directory, 'beds')
86
+ if os.path.isdir(bed_dir):
87
+ print(bed_dir + ' already exists. Skipping BAM -> BED conversion for ' + sorted_output)
88
+ else:
89
+ aligned_BAM_to_bed(aligned_output, output_directory, fasta, make_bigwigs, threads)
90
+
91
+ # 3) Split the aligned and sorted BAM files by barcode (BC Tag) into the split_BAM directory
92
+ if os.path.isdir(split_dir):
93
+ print(split_dir + ' already exists. Using existing demultiplexed BAMs.')
94
+ bam_files = os.listdir(split_dir)
95
+ bam_files = [os.path.join(split_dir, file) for file in bam_files if '.bam' in file and '.bai' not in file and 'unclassified' not in file]
96
+ bam_files.sort()
97
+ else:
98
+ make_dirs([split_dir])
99
+ bam_files = demux_and_index_BAM(aligned_sorted_BAM, split_dir, bam_suffix, barcode_kit, barcode_both_ends, trim, fasta, make_bigwigs, threads)
100
+ # split_and_index_BAM(aligned_sorted_BAM, split_dir, bam_suffix, output_directory, converted_FASTA) # deprecated, just use dorado demux
101
+
102
+ # Make beds and provide basic histograms
103
+ bed_dir = os.path.join(split_dir, 'beds')
104
+ if os.path.isdir(bed_dir):
105
+ print(bed_dir + ' already exists. Skipping BAM -> BED conversion for demultiplexed bams')
106
+ else:
107
+ for bam in bam_files:
108
+ aligned_BAM_to_bed(bam, split_dir, fasta, make_bigwigs, threads)
109
+
110
+ # 4) Samtools QC metrics on split BAM files
111
+ if os.path.isdir(bam_qc_dir):
112
+ print(bam_qc_dir + ' already exists. Using existing BAM QC calculations.')
113
+ else:
114
+ make_dirs([bam_qc_dir])
115
+ bam_qc(bam_files, bam_qc_dir, threads, modality='direct')
116
+
117
+ # 5) Using nanopore modkit to work with modified BAM files ###
118
+ if os.path.isdir(mod_bed_dir):
119
+ print(mod_bed_dir + ' already exists, skipping making modbeds')
120
+ else:
121
+ make_dirs([mod_bed_dir])
122
+ modQC(aligned_sorted_output, thresholds) # get QC metrics for mod calls
123
+ make_modbed(aligned_sorted_output, thresholds, mod_bed_dir) # Generate bed files of position methylation summaries for every sample
124
+
125
+ # multiqc ###
126
+ if os.path.isdir(f"{split_dir}/multiqc"):
127
+ print(f"{split_dir}/multiqc" + ' already exists, skipping multiqc')
128
+ else:
129
+ run_multiqc(split_dir, f"{split_dir}/multiqc")
130
+
131
+ make_dirs([mod_tsv_dir])
132
+ extract_mods(thresholds, mod_tsv_dir, split_dir, bam_suffix, skip_unclassified, threads) # Extract methylations calls for split BAM files into split TSV files
133
+
134
+ #6 Load the modification data from TSVs into an adata object
135
+ final_adata, final_adata_path = modkit_extract_to_adata(fasta, split_dir, mapping_threshold, experiment_name, mods, batch_size, mod_tsv_dir, delete_batch_hdfs, threads)
136
+
137
+ return final_adata, final_adata_path, sorted_output, bam_files
@@ -0,0 +1,29 @@
1
+ import pysam
2
+ import sys
3
+
4
+ def extract_reads(bam_file_path, num_reads=10):
5
+ # Open the BAM file
6
+ bam_file = pysam.AlignmentFile(bam_file_path, "rb")
7
+
8
+ # Iterate through the first 'num_reads' reads and print the sequences
9
+ count = 0
10
+ for read in bam_file:
11
+ print(f"Read {count + 1}: {read.query_sequence}")
12
+ count += 1
13
+ if count >= num_reads:
14
+ break
15
+
16
+ # Close the BAM file
17
+ bam_file.close()
18
+
19
+ if __name__ == "__main__":
20
+ # Ensure a BAM file path is provided as a command line argument
21
+ if len(sys.argv) < 2:
22
+ print("Usage: python extract_reads.py <path_to_bam_file>")
23
+ sys.exit(1)
24
+
25
+ # Get the BAM file path from command line arguments
26
+ bam_file_path = sys.argv[1]
27
+
28
+ # Call the function to extract the first 10 reads
29
+ extract_reads(bam_file_path)