rustynetics/granges_table_writer.rs
1// Copyright (C) 2024 Philipp Benner
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the “Software”), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21use std::io;
22use std::io::{BufRead, Write};
23
24use crate::granges::GRanges;
25
26/* -------------------------------------------------------------------------- */
27
28
29/// A writer for formatting and outputting a `GRanges` instance as a table.
30///
31/// This struct holds a reference to a `GRanges` instance and is responsible for determining the width of
32/// columns based on the content of the `GRanges` and for writing the formatted output to a specified writer.
33pub struct GRangesTableWriter<'a> {
34 granges : &'a GRanges,
35 widths : Vec<usize>,
36 use_scientific: bool,
37 use_strand : bool,
38 }
39
40/* -------------------------------------------------------------------------- */
41
42impl<'a> GRangesTableWriter<'a> {
43
44 /// Creates a new instance of `GRangesTableWriter`.
45 ///
46 /// # Arguments
47 /// - `granges`: A reference to a `GRanges` instance that this writer will format and output.
48 /// - `use_scientific`: A boolean indicating whether to use scientific notation for numeric output.
49 /// - `use_strand`: A boolean indicating whether to include strand information in the output.
50 ///
51 /// # Returns
52 /// A new instance of `GRangesTableWriter`.
53 pub fn new(granges: &'a GRanges, use_scientific: bool, use_strand: bool) -> Self {
54 GRangesTableWriter{
55 granges : granges,
56 widths : vec![8, 4, 2, 6],
57 use_scientific: use_scientific,
58 use_strand : use_strand,
59 }
60 }
61
62 /// Determines the maximum widths of columns based on the data in the `GRanges` instance.
63 ///
64 /// This method updates the `widths` field by calculating the lengths of each column's contents
65 /// for all rows. It is called to ensure proper alignment when writing the table.
66 ///
67 /// # Returns
68 /// An `io::Result<()>`, which will be `Ok(())` if the operation succeeds, or an error if width
69 /// calculation fails.
70 pub fn determine_widths(&mut self) -> io::Result<()> {
71 for i in 0..self.granges.num_rows() {
72 update_max_widths(self.granges, i, &mut self.widths, self.use_scientific)?;
73 }
74 Ok(())
75 }
76
77 /// Writes the header row of the table to the specified writer.
78 ///
79 /// This method writes the column names (headers) to the output, including strand information if requested.
80 ///
81 /// # Arguments
82 /// - `writer`: A mutable reference to a writer that implements the `Write` trait, where the header will be written.
83 /// - `meta_reader`: A mutable reference to a buffer reader for reading metadata associated with the `GRanges`.
84 ///
85 /// # Returns
86 /// An `io::Result<()>`, which will be `Ok(())` if the operation succeeds, or an error if writing fails.
87 pub fn write_header<R: BufRead, W: Write>(&self, writer: &mut W, meta_reader: &mut R) -> io::Result<()> {
88 write_header(writer, &self.widths, self.use_strand)?;
89 write_row_meta(self.granges, writer, meta_reader)?;
90 writeln!(writer)
91 }
92
93 /// Writes a single row of `GRanges` data to the specified writer.
94 ///
95 /// This method formats and writes the data for a specific row, including metadata if present.
96 ///
97 /// # Arguments
98 /// - `writer`: A mutable reference to a writer that implements the `Write` trait, where the row will be written.
99 /// - `meta_reader`: A mutable reference to a buffer reader for reading metadata associated with the `GRanges`.
100 /// - `i`: The index of the row to write.
101 ///
102 /// # Returns
103 /// An `io::Result<()>`, which will be `Ok(())` if the operation succeeds, or an error if writing fails.
104 pub fn write_row<R: BufRead, W: Write>(&self, writer: &mut W, meta_reader: &mut R, i: usize) -> io::Result<()> {
105 write_row (self.granges, writer, i, &self.widths, self.use_strand)?;
106 write_row_meta(self.granges, writer, meta_reader)?;
107 writeln!(writer)
108 }
109
110}
111
112/* -------------------------------------------------------------------------- */
113
114fn update_max_widths(granges: &GRanges, i: usize, widths: &mut [usize], strand: bool) -> io::Result<()> {
115 let seqname_width = granges.seqnames[i].len();
116 if seqname_width > widths[0] {
117 widths[0] = seqname_width;
118 }
119 let from_width = granges.ranges[i].from.to_string().len();
120 if from_width > widths[1] {
121 widths[1] = from_width;
122 }
123 let to_width = granges.ranges[i].to.to_string().len();
124 if to_width > widths[2] {
125 widths[2] = to_width;
126 }
127 if strand {
128 let strand_width = granges.strand[i].to_string().len();
129 if strand_width > widths[3] {
130 widths[3] = strand_width;
131 }
132 }
133 Ok(())
134}
135
136fn write_header<W: Write>(writer: &mut W, widths: &[usize], strand: bool) -> io::Result<()> {
137 if strand {
138 write!(writer,
139 "{:width0$} {:width1$} {:width2$} {:width3$}",
140 "seqnames", "from", "to", "strand",
141 width0=widths[0], width1=widths[1], width2=widths[2], width3=widths[3])?;
142 } else {
143 write!(writer,
144 "{:width0$} {:width1$} {:width2$}",
145 "seqnames", "from", "to",
146 width0=widths[0], width1=widths[1], width2=widths[2])?;
147 }
148 Ok(())
149}
150
151fn write_row_meta(granges: &GRanges, writer: &mut dyn Write, meta_reader: &mut dyn BufRead) -> io::Result<()> {
152 if granges.meta.num_cols() > 0 {
153 let mut line = String::new();
154 meta_reader.read_line(&mut line)?;
155 write!(writer, " | {}", line.trim_end_matches('\n'))?;
156 }
157 Ok(())
158}
159
160fn write_row<W: Write>(granges: &GRanges, writer: &mut W, i: usize, widths: &[usize], strand: bool) -> io::Result<()> {
161 if strand {
162 write!(writer,
163 "{:width0$} {:width1$} {:width2$} {:width3$}",
164 granges.seqnames[i], granges.ranges[i].from, granges.ranges[i].to, granges.strand[i],
165 width0=widths[0], width1=widths[1], width2=widths[2], width3=widths[3])?;
166 } else {
167 write!(writer,
168 "{:width0$} {:width1$} {:width2$}",
169 granges.seqnames[i], granges.ranges[i].from, granges.ranges[i].to,
170 width0=widths[0], width1=widths[1], width2=widths[2])?;
171 }
172 Ok(())
173}