Skip to content

Commit d38dfd7

Browse files
committed
Calculate the number of decimal places to output to wig file format
1 parent dfcf85a commit d38dfd7

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

newmap/unique_counts_conversion.py

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,8 @@ def write_single_read_bed(bed_file: BinaryIO,
9595

9696
def write_multi_read_wig(wig_file: BinaryIO,
9797
multi_read_mappability: npt.NDArray[np.float64],
98-
chr_name: str):
98+
chr_name: str,
99+
decimal_places: int = 2):
99100

100101
# Write out the fixedStep declaration
101102
wig_file.write(WIG_FIXED_STEP_DECLARATION_FORMAT
@@ -104,8 +105,19 @@ def write_multi_read_wig(wig_file: BinaryIO,
104105

105106
for mappability_chunk in np.nditer(multi_read_mappability,
106107
flags=['external_loop', 'buffered']):
107-
wig_file.writelines(f"{value}\n".encode()
108-
for value in mappability_chunk)
108+
wig_file.writelines(
109+
float_format(value, decimal_places) + b'\n' # type: ignore
110+
for value in mappability_chunk)
111+
112+
113+
def float_format(value: float,
114+
decimal_places: int) -> bytes:
115+
# Special case for 0, ignore trailing decimal places
116+
if value == 0.0:
117+
return b"0.0"
118+
119+
# Otherwise print the specified number of decimal places
120+
return f"{value:.{decimal_places}f}".encode()
109121

110122

111123
def safe_remove(filename: str):
@@ -199,16 +211,21 @@ def write_mappability_files(unique_count_filenames: list[Path],
199211
verbose_print(verbose, f"Appending multi-read mappability regions"
200212
f" to {multi_read_wig_filename}")
201213

214+
# Calculate the number of decimal places
215+
decimal_places = int(np.ceil(np.log10(kmer_length)))
216+
202217
if multi_read_wig_filename == STDOUT_FILENAME:
203218
write_multi_read_wig(sys.stdout.buffer,
204219
multi_read_mappability,
205-
chr_name)
220+
chr_name,
221+
decimal_places)
206222
else:
207223
with open(multi_read_wig_filename, "ab") as \
208224
multi_read_wig_file:
209225
write_multi_read_wig(multi_read_wig_file,
210226
multi_read_mappability,
211-
chr_name)
227+
chr_name,
228+
decimal_places)
212229

213230

214231
def main(args):

0 commit comments

Comments
 (0)