def __repr__(self): h, r = self._get_repr_() h, r = formatted_cells(r, header=h) result = simple_format(h, r, title=self.test_name) components = CategoryCounts(self.observed.to_dict(), expected=self.expected.to_dict()) result = [result, str(components)] return "\n".join(result)
def array_repr(self, a): if len(a.shape) == 1: heading = [str(n) for n in self.names[0]] a = a[numpy.newaxis, :] elif len(a.shape) == 2: heading = [""] + [str(n) for n in self.names[1]] a = [[str(name)] + list(row) for (name, row) in zip(self.names[0], a)] else: return "%s dimensional %s" % (len(self.names), type(self).__name__) formatted = table.formatted_cells(rows=a, header=heading) return str(table.simple_format(formatted[0], formatted[1], space=4))
def to_plotly(self, width=500, font_size=12, layout=None, **kwargs): """returns a Plotly Table""" import plotly.graph_objs as go from cogent3.draw.drawable import Drawable rows = self.array.tolist() header, rows = table_format.formatted_cells( rows, self.header, digits=self._digits, column_templates=self._column_templates, missing_data=self._missing_data, center=False, ) # we strip white space padding from header and cells header = [e.strip() for e in header] rows = [[e.strip() for e in row] for row in rows] rows = list(zip(*rows)) if self._row_ids: body_colour = ["white"] * self.shape[0] index_colour = ["rgba(161, 195, 209, 0.5)"] * self.shape[0] colours = [index_colour ] + [body_colour[:] for i in range(self.shape[1])] rows[0] = [f"<b>{e}</b>" for e in rows[0]] else: colours = "white" tab = UnionDict( type="table", header=dict( values=[f"<b>{c}</b>" for c in header], fill=dict(color="rgba(161, 195, 209, 1)"), font=dict(size=font_size), align="center", ), cells=dict(values=rows, fill=dict(color=colours)), ) draw = Drawable() aspect_ratio = self.shape[0] / self.shape[1] layout = layout or {} default_layout = dict( width=width, height=aspect_ratio * width, autosize=False, title=self.title, margin=dict(l=10, r=10, t=30, b=10, pad=10), ) default_layout.update(layout) draw.traces.append(tab) draw.layout |= default_layout return draw
def to_rich_html( self, row_cell_func=None, header_cell_func=None, element_formatters=None, merge_identical=False, compact=False, ): """returns just the table html code. Parameters ---------- row_cell_func callback function that formats the row values. Must take the row value and coordinates (row index, column index). header_cell_func callback function that formats the column headings must take the header label value and coordinate element_formatters a dictionary of specific callback funcs for formatting individual html table elements. e.g. {'table': lambda x: '<table border="1" class="docutils">'} merge_identical cells within a row are merged to one span. """ element_formatters = element_formatters or {} formatted_table = self.array.tolist() header, formatted_table = table_format.formatted_cells( formatted_table, self.header, digits=self._digits, column_templates=self._column_templates, missing_data=self._missing_data, ) subtables = table_format.get_continuation_tables( header, formatted_table, identifiers=self._row_ids, max_width=self._max_width, ) tables = [] title = self.title if self.title else "" if title: title = escape(title) legend = self.legend if self.legend else "" if legend: legend = escape(legend) for i, (h, t) in enumerate(subtables): # but we strip the cell spacing sh = [v.strip() for v in h] t = [[c.strip() for c in r] for r in t] if title and i == 0: st = element_formatters.get( "caption", f'<span style="font-weight:bold">{title}</span>') elif title: st = element_formatters.get( "caption", f'<span style="font-weight:bold">continuation</span>') else: st = None legend = self.legend if self.legend else "" if legend and i == 0: title = f"{st} {legend}" if st else legend caption = st if st else None subtable = table_format.rich_html( t, row_cell_func=row_cell_func, header=sh, header_cell_func=header_cell_func, element_formatters=element_formatters, merge_identical=merge_identical, compact=compact, caption=caption, ) tables.append(subtable) return "\n".join(tables)
def to_string(self, format="", borders=True, sep=None, center=False, **kwargs): """Return the table as a formatted string. Parameters ---------- format possible formats are 'rest'/'rst', 'markdown'/'md', 'latex', 'html', 'phylip', 'bedgraph', 'csv', 'tsv', or 'simple' (default). sep A string separator for delineating columns, e.g. ',' or '\t'. Overrides format. center content is centered in the column, default is right justified NOTE: If format is bedgraph, assumes that column headers are chrom, start, end, value. In that order! """ if format.lower() == "phylip": missing_data = "%.4f" % 0.0 else: missing_data = self._missing_data if format.lower() in ("tsv", "csv"): sep = sep or {"tsv": "\t", "csv": ","}[format.lower()] format = "" # convert self to a 2D list formatted_table = self.array.tolist() if format != "bedgraph": header, formatted_table = table_format.formatted_cells( formatted_table, self.header, digits=self._digits, column_templates=self._column_templates, missing_data=missing_data, center=center, ) args = (header, formatted_table, self.title, self.legend) if sep and format != "bedgraph": return table_format.separator_format(*args + (sep, )) elif format in ("rest", "rst"): return table_format.grid_table_format(*args) elif format in ("markdown", "md"): return table_format.markdown(header, formatted_table, **kwargs) elif format.endswith("tex"): caption = None if self.title or self.legend: caption = " ".join([self.title or "", self.legend or ""]) return table_format.latex(formatted_table, header, caption=caption, **kwargs) elif format == "html": return self.to_rich_html(**kwargs) elif format == "phylip": # need to eliminate row identifiers formatted_table = [row[self._row_ids:] for row in formatted_table] header = header[self._row_ids:] return table_format.phylip_matrix(formatted_table, header) elif format == "bedgraph": assert self.shape[1] == 4, "bedgraph format is for 4 column tables" # assuming that header order is chrom, start, end, val formatted_table = bedgraph.bedgraph(self.sorted().array.tolist(), **kwargs) return formatted_table else: return table_format.simple_format( *args + (self._max_width, self._row_ids, borders, self.space))
def _get_repr_(self, html=False): obs = self.observed.array.tolist() exp = self.expected.array.tolist() res = self.residuals.array.tolist() ndim = len(self.observed.shape) if ndim == 1: row_labels = "Observed", "Expected", "Residuals" row_cell_func = _format_row_cell(row_labels) col_labels = [str(c) for c in self.observed.template.names[0]] rows = [] # format floats for expecteds and resid for row_label, row in zip(row_labels, [obs, exp, res]): if row_label == "Observed": row = [row_label] + [f"{v:,}" for v in row] else: row = [row_label] + [f"{v:,.2f}" for v in row] rows.append(row) if html: rows = rich_html( rows, header=[""] + col_labels, row_cell_func=row_cell_func, merge_identical=False, ) else: header, rows = formatted_cells(rows, header=[""] + col_labels) rows = simple_format(header, rows) else: row_labels = self.observed.template.names[0] col_labels = self.observed.template.names[1] row_cell_func = _format_row_cell(row_labels) result = [] for caption, table in zip(("Observed", "Expected", "Residuals"), (obs, exp, res)): rows = [] for i, r in enumerate(table): if caption == "Observed": r = [f"{v:,}" for v in r] else: r = [f"{v:,.2f}" for v in r] rows.append([row_labels[i]] + r) if html: result.append( rich_html( rows, header=[""] + col_labels, caption=f"<b>{caption}</b>", row_cell_func=row_cell_func, merge_identical=False, )) else: header, rows = formatted_cells(rows, header=[""] + col_labels) result.append(simple_format(header, rows, title=caption)) joiner = "<br>" if html else "\n" rows = joiner.join(result) return rows