zensols.datdesc package¶
Submodules¶
zensols.datdesc.app module¶
Generate LaTeX tables in a .sty file from CSV files. The paths to the CSV
files to create tables from and their metadata is given as a YAML configuration
file. Paraemters are both files or both directories. When using directories,
only files that match *-table.yml are considered.
- class zensols.datdesc.app.Application(config_factory, renderable_factory)[source]¶
Bases:
objectGenerate LaTeX tables files from CSV files and hyperparameter .sty files.
- __init__(config_factory, renderable_factory)¶
-
config_factory:
ConfigFactory¶ Creates table and figure factories.
- generate_figures(input_path, output_path, output_image_format=None, output_sty=None)[source]¶
Generate figures.
- generate_tables(input_path, output_path, output_format=OutputFormat.table)[source]¶
Create LaTeX tables.
- Parameters:
input_path (
Path) – YAML definitions or JSON serialized fileoutput_path (
Path) – output file or directory
- list_figures(input_path)[source]¶
List figures.
- Parameters:
input_path (
Path) – YAML definitions or JSON serialized fileoutput_path – output file or directory
output_image_format – the output format (defaults to
svg)
-
renderable_factory:
RenderableFactory¶ Creates instances of
Renderablefrom file paths.
- show_table(name=None)[source]¶
Print a list of example LaTeX tables.
- Parameters:
name (
str) – the name of the example table or a listing of tables if omitted
- write_excel(input_path, output_file=None, output_latex_format=False)[source]¶
Create an Excel file from table data.
- Parameters:
input_path (
Path) – YAML definitions or JSON serialized fileoutput_file (
Path) – the output file, which defaults to the input prefix with the approproate extensionoutput_latex_format (
bool) – whether to output with LaTeX commands
zensols.datdesc.cli module¶
Command line entry point to the application.
- class zensols.datdesc.cli.ApplicationFactory(*args, **kwargs)[source]¶
Bases:
ApplicationFactory- classmethod get_renderable_factory(**kwargs)[source]¶
Return a factory that creates instances of
Renderablefrom file paths.- Return type:
zensols.datdesc.desc module¶
Metadata container classes.
- class zensols.datdesc.desc.DataDescriber(describers, name='default', mangle_sheet_name=False)[source]¶
Bases:
PersistableContainer,DictableContainer class for
DataFrameDescriberinstances. It also saves their instances as CSV data files and YAML configuration files.- DEFAULT_CSV_DIR: ClassVar[Path] = PosixPath('config/csv')¶
- DEFAULT_EXCEL_DIR: ClassVar[Path] = PosixPath('results')¶
- DEFAULT_YAML_DIR: ClassVar[Path] = PosixPath('results/config')¶
- SHEET_NAME_MAXLEN: ClassVar[int] = 31¶
Maximum allowed characters in an Excel spreadsheet’s name.
- __init__(describers, name='default', mangle_sheet_name=False)¶
- add_summary()[source]¶
Add a new metadata like
DataFrameDescriberas a first entry indescribersthat describes what data this instance currently has.- Return type:
- Returns:
the added metadata
DataFrameDescriberinstance
- derive(**kwargs)[source]¶
Create a new instance based on this instance and replace any non-
Nonekwargs.- Parameters:
kwargs – the key word arguments to replace any field data from this instance
- Return type:
- Returns:
a new instance with replaced data, or a clone if called with no key word arguments
- derive_with_index_meta(index_format=None)[source]¶
Applies
DataFrameDescriber.derive_with_index_meta()to each element ofdescribers.- Return type:
- describers: tuple[DataFrameDescriber, ...]¶
The contained dataframe and metadata.
- property describers_by_name: dict[str, DataFrameDescriber]¶
Data frame describers keyed by the describer name.
- classmethod from_describer(dfd)[source]¶
Create a singleton describer. The
nameis taken from thedfdDataFrameDescriber.name.- Return type:
- classmethod from_excel(path, *, dataset_name_fmt='{path.stem}', read_excel_kwargs=None, header_row=None, data_start_row=None, include_sheets=None, exclude_sheets=None, table_desc_fmt="From {path.name} (sheet '{sheet}')", head=None, mangle_sheet_name=False, mangle_file_names=False)[source]¶
Read all sheets from an Excel workbook using pandas, and populate:
DataFrameDescriber.metafrom COMMENTS (a.k.a. Excel “notes”) on header cellsDataFrameDescriber.index_metafrom COMMENTS on index-column cells (one per row)
Conventions (workbook layout assumptions):
Header row contains column names. Put each column description as a cell comment on the corresponding header cell.
- If you set pandas index_col=…, put row descriptions as cell
comments on the cells of that index column for each data row.
Note:
openpyxlsupports the legacy Excel “notes” comment objects, but not newer threaded comments. Use Notes if you want this to work.- Parameters:
read_excel_kwargs (
Mapping[str,Any] |None) –pandas.read_excel()keyword paramsheader_row (
int|None) – start row of header; if omitted inferred from pandas If omitted, inferred from pandasheader(default 0 => row 1)data_start_row (
int|None) – start row of header; if omitted inferred from pandas If omitted, inferred from pandasheader(default 0 => row 1)
- Return type:
- classmethod from_json(reader)[source]¶
Unserialize a JSON stream into a data descriptor.
- Parameters:
reader (
TextIOWrapper) – the file / data stream- Return type:
- classmethod from_json_file(path)[source]¶
Like
from_yaml_file()but a JSON file written with meth:save_json.- Return type:
- classmethod from_tables(tables, name=None)[source]¶
Create a data descriptor from a
Table.- Return type:
- classmethod from_yaml_file(path)[source]¶
Create a data descriptor from a previously written YAML/CSV files using
save().- See:
- See:
- Return type:
- mangle_sheet_name: bool = False¶
Whether to normalize the Excel sheet names when
xlsxwriter.exceptions.InvalidWorksheetNameis raised.
- name: str = 'default'¶
The name of the dataset.
- save(csv_dir=None, yaml_dir=None, excel_path=None)[source]¶
Save both the CSV and YAML configuration file.
- Parameters:
- See:
- See:
- Return type:
list[Path]
- save_csv(csv_dir)[source]¶
Save all provided dataframe describers to an CSV files.
- Parameters:
csv_dir (
Path) – the directory of where to save the data- Return type:
list[Path]
- save_excel(output_file=None)[source]¶
Save all provided dataframe describers to an Excel file.
- Parameters:
output_file (
Path) – the Excel file to write;.xlsxwill be postpend if no extension exists- Return type:
Path
- save_json(output_path=PosixPath('.'))[source]¶
Serialize the this instance as a JSON file. Most or all of the state is kept in tact and unserialized / restored with
from_json().- Return type:
Path
- save_yaml(csv_dir, yaml_dir)[source]¶
Save all provided dataframe describers YAML files used by the
datdesccommand.- Parameters:
csv_dir (
Path) – the directory of where to save the datayaml_dir (
Path) – the directory where the YAML config files are saved
- Return type:
list[Path]
- to_json(writer)[source]¶
Serialize the object to JSON that can be re-instantiated using
from_json().- Parameters:
writer (
TextIOBase) – the data sinkkwargs – the key word arguments to give to
json.dump()
- class zensols.datdesc.desc.DataFrameDescriber(name, df, desc, head=None, meta_path=None, meta=None, table_kwargs=<factory>, index_meta=None, mangle_file_names=False)[source]¶
Bases:
PersistableContainer,DictableA class that contains a Pandas dataframe, a description of the data, and descriptions of all the columns in that dataframe.
- property T: DataFrameDescriber¶
See
transpose().
- __init__(name, df, desc, head=None, meta_path=None, meta=None, table_kwargs=<factory>, index_meta=None, mangle_file_names=False)¶
- property column_descriptions: dict[str, str]¶
A dictionary of name to Descriptions of the column metadata created from
meta. Any missing column metadata will result inNonedictionary values.
- property csv_path: Path¶
The CVS file that contains the data this instance describes.
- derive(*, name=None, df=None, desc=None, meta=None, index_meta=None)[source]¶
Create a new instance based on this instance and replace any non-
Nonekwargs.If
metais provided, it is merged with the metadata of this instance. However, any metadata provided must match in both column names and descriptions.
- derive_with_index_meta(index_format=None)[source]¶
Like
derive(), but the dataframe is generated withdf_with_index_meta()usingindex_formatas a parameter.- Parameters:
index_format (
str) – seedf_with_index_meta()- Return type:
- desc: str¶
The description of the data frame.
- df: pd.DataFrame¶
The dataframe to describe.
- df_with_index_meta(index_format=None)[source]¶
Create a dataframe with the first column containing index metadata. This uses
index_metato create the column values.- Parameters:
index_format (
str) – the new index column format usingindexandvalue, which defaults to{index}- Return type:
- Returns:
the dataframe with a new first column of the index metadata, or
dfifindex_metaisNone
- format_table()[source]¶
Replace (in place) dataframe
dfwith the formatted table obtained withTable.formatted_dataframe. TheTableis created by withcreate_table().
- classmethod from_columns(source, name=None, desc=None)[source]¶
Create a new instance by transposing a column data into a new dataframe describer. If
sourceis a dataframe, it that has the following columns:Otherwise, each element of the sequence is a row of column, meta descriptions, and data sequences.
- classmethod from_dataclasses(data, meta=None, member_names=None)[source]¶
Create a new instance from dataclasses.
- Parameters:
data (
Sequence[Any]) – at least one@dataclassobject fromdataclassesmeta (
DataclassMetadata) – dataclass metadata, or ifNonecreated fromdata[0]member_names (
Sequence[str]) – dataclass members to copy, or all if not given
- Return type:
- Returns:
a new instance containing
data
- head: str = None¶
A short summary of the table and used in
Table.head.
- index_meta: dict[Any, str] = None¶
The index metadata, which maps index values to descriptions of the respective row.
- mangle_file_names: bool = False¶
Whether to normalize output file names.
- merge(objs, on=None)[source]¶
Merge using the same semantics as
pandas.DataFrame.merge(). Only the column metadata and columns are merged. The remaining data (i.e.name,desc,index_meta) are taken from this instance.- Parameters:
- Return type:
- Returns:
a new describer with
objsmerged
- property meta: DataFrame¶
The column metadata for
dataframe, which needs columnsnameanddescription. If this is not provided, it is read from filemeta_path. If this is set to a tuple of tuples, a dataframe is generated from the form:((<column name 1>, <column description 1>), (<column name 2>, <column description 2>) ...
If both this and
meta_pathare not provided, the following is used:(('description', 'Description'), ('value', 'Value')))
- name: str¶
The description of the data this describer holds.
- save_excel(output_path=PosixPath('.'), is_dir=True)[source]¶
Save as an Excel file. To add column labels use instances of this object with
DataDescriber.save_excel().- Parameters:
- See:
- Return type:
Path
- table_kwargs: dict[str, Any]¶
Additional key word arguments given when creating a table in
create_table().
- transpose(row_names=((0, 'value', 'Value'),), name_column='name', name_description='Name', index_column='description')[source]¶
Transpose all data in this descriptor by transposing
dfand swappingmetawithindex_metaas a new instance.- Parameters:
row_names (
tuple[int,str,str]) – a tuple of (row index indf, the column in the newdfand the metadata description of that column in the newdf; the default takes only the first rowdescription_column – the column description this instance’s
dfindex_column (
str) – the name of the new index in the returned instance
- Return type:
- Returns:
a new derived instance of the transposed data
- class zensols.datdesc.desc.RenderableDataFrameDescriber(path)[source]¶
Bases:
RenderableReads instances serialized with
DataDescriber.to_json()and writes the CVS, YAML and Excel files.- __init__(path)¶
zensols.datdesc.dfstash module¶
A stash implementation that uses a Pandas dataframe and stored as a CSV file.
- class zensols.datdesc.dfstash.DataFrameStash(path, dataframe=None, key_column='key', columns=('value',), sort_columns=(), mkdirs=True, auto_commit=True, single_column_index=0)[source]¶
Bases:
CloseableStash,DictableA backing stash that persists to a CSV file via a Pandas dataframe. All modification go through the
pandas.DataFrameand then saved withcommit()orclose().- __init__(path, dataframe=None, key_column='key', columns=('value',), sort_columns=(), mkdirs=True, auto_commit=True, single_column_index=0)¶
- clear()[source]¶
Delete all data from the from the stash.
Important: Exercise caution with this method, of course.
-
columns:
tuple[str,...] = ('value',)¶ The columns to create in the spreadsheet. These must be consistent when the data is restored.
- property dataframe: DataFrame¶
The dataframe to proxy in memory. This is settable on instantiation but read-only afterward. If this is not set an empty dataframe is created with the metadata in this class.
- delete(name=None)[source]¶
Delete the resource for data pointed to by
nameor the entire resource ifnameis not given.
- exists(name)[source]¶
Return
Trueif data with keynameexists.Implementation note: This
Stash.exists()method is very inefficient and should be overriden.- Return type:
- get(name, default=None)[source]¶
Load an object or a default if key
namedoesn’t exist. Semantically, this method tries not to re-create the data if it already exists. This means that if a stash has built-in caching mechanisms, this method uses it.
- load(name)[source]¶
Load a data value from the pickled data with key
name. Semantically, this method loads the using the stash’s implementation. For exampleDirectoryStashloads the data from a file if it exists, but factory type stashes will always re-generate the data.
-
mkdirs:
bool= True¶ Whether to recusively create the directory where
pathis stored if it does not already exist.
-
path:
Path¶ The path of the file from which to read and write.
- class zensols.datdesc.dfstash.DataclassStash(path, dataframe=None, key_column='key', columns=('value',), sort_columns=(), mkdirs=True, auto_commit=True, single_column_index=0, data_name=None, desc=None, metadata=None)[source]¶
Bases:
DataFrameStashMap CSV rows in
DataFrameStashstashes to Python dataclasses.- __init__(path, dataframe=None, key_column='key', columns=('value',), sort_columns=(), mkdirs=True, auto_commit=True, single_column_index=0, data_name=None, desc=None, metadata=None)¶
-
desc:
str= None¶ The description used in
describer. If not provided, it is taken from the class docstring.
-
metadata:
DataclassMetadata= None¶ Get the metadata of dataclass
data_class.
zensols.datdesc.domain module¶
Application domain.
- exception zensols.datdesc.domain.DataDescriptionError[source]¶
Bases:
APIErrorThrown for any application level error.
- __firstlineno__ = 8¶
- __module__ = 'zensols.datdesc.domain'¶
- __static_attributes__ = ()¶
- exception zensols.datdesc.domain.FigureError(reason, figure=None, definition_file=None)[source]¶
Bases:
DataDescriptionErrorThrown for any application level error related to creating figures.
- __annotations__ = {}¶
- __firstlineno__ = 26¶
- __module__ = 'zensols.datdesc.domain'¶
- __static_attributes__ = ('figure',)¶
zensols.datdesc.figure module¶
A simple object oriented plotting API.
- class zensols.datdesc.figure.Figure(name, path, template, template_params=<factory>, caption='', definition_file=None, head=None, writes=<factory>, uses=<factory>, default_params=<factory>, params=<factory>, config_factory=None, title_font_size=0, height=5, width=5, padding=5.0, metadata=<factory>, plots=(), image_dir=PosixPath('.'), image_format='svg', image_file_norm=True, seaborn=<factory>, subplot_params=<factory>, savefig_params=<factory>)[source]¶
Bases:
RenderableLatexArtifactManage a Matplotlib figure and its collection of plots.
A figure is the top-level rendering object for one or more
Plotinstances. Each plot is assigned a row and column and rendered on the correspondingmatplotlib.axes.Axescreated bymatplotlib.pyplot.subplots().The figure controls the overall image dimensions, subplot layout, optional Seaborn styling, image metadata, and parameters used when saving the resulting image. Plots can be supplied at construction time, added with
add_plot(), or created from configuration withFigureFactory.Plot definitions loaded by
FigureFactorysupport several code hooks. These run at two different stages of the figure lifecycle.code_preExecuted by
FigureFactory._parse_plot()while parsing the plot definition, before thePlotinstance is created. The YAML mapping is first wrapped in aSettingsinstance and made available asplot. The code can therefore modify constructor parameters using attribute notation. After the hook executes, the settings are converted back to a dictionary and passed toFigureFactory.create().code_postExecuted by
FigureFactory._parse_plot()immediately after thePlotinstance has been created. Hereplotrefers to the newly instantiatedPlot, so the hook can modify the actual plot object.code_pre_renderStored on the
Plotinstance and executed by_render()immediately beforePlot.render(). At this point theFigure, Matplotlib figure, and axes have already been created. The execution context providesplot,fig, andaxes.code_post_renderStored on the
Plotinstance and executed by_render()immediately afterPlot.render(), with the same rendering context. This is useful for modifying Matplotlib objects after the plot has populated its axes.
Thus,
code_preandcode_postare configuration/instantiation hooks handled byFigureFactory, whereascode_pre_renderandcode_post_renderare rendering hooks invoked later by this class.For example:
example_fig: width: 6 height: 4 plots: - type: bar data: 'dataframe: data.csv' code_pre: | plot.y_axis_label = 'Score' code_post: | plot.title = 'Results' code_post_render: | axes.grid(False)
Rendering is lazy: the underlying
matplotlib.figure.Figureand axes are created when first needed and reused until the figure is reset. Callingsave()renders all managed plots and writes the image topath.In addition to image generation, this class is a
RenderableLatexArtifact, allowing the generated image to be referenced by the LaTeX rendering infrastructure.- __init__(name, path, template, template_params=<factory>, caption='', definition_file=None, head=None, writes=<factory>, uses=<factory>, default_params=<factory>, params=<factory>, config_factory=None, title_font_size=0, height=5, width=5, padding=5.0, metadata=<factory>, plots=(), image_dir=PosixPath('.'), image_format='svg', image_file_norm=True, seaborn=<factory>, subplot_params=<factory>, savefig_params=<factory>)¶
- add_plot(plot)[source]¶
Add to the collection of managed plots. This is needed for the plot to work if not created from this manager instance.
- Parameters:
plot (
Plot) – the plot to be managed
- clear()[source]¶
Remove all plots and reset the
matplotlibmodule.
- config_factory: ConfigFactory = None¶
The configuration factory used to create plots.
- height: int = 5¶
The height in inches of the entire figure.
- image_dir: Path = PosixPath('.')¶
The default image save directory.
- image_file_norm: bool = True¶
Whether to normalize the image output file name.
- image_format: str = 'svg'¶
The image format to use when saving plots.
- metadata: dict[str, str]¶
Metadata added to the image when saved.
- padding: float = 5.0¶
Tight layout padding.
- plots: tuple[Plot, ...] = ()¶
The plots managed by this object instance. Use
add_plot()to add new plots.
- save()[source]¶
Save the figure of subplot(s) to at location
path.- Param:
if provided, overrides the save location
path- Return type:
Path- Returns:
the value of
path
- savefig_params: dict[str, Any]¶
Additional parameters given to
matplotlib.figure.Figure.savefig().
- seaborn: dict[str, Any]¶
Seaborn (
seaborn) rendering configuration. It has the following optional keys:style: parameters used withsns.set_style()context: parameters used withsns.set_context()
- subplot_params: dict[str, Any]¶
Additional parameters given to
matplotlib.pyplot.subplots().
- title_font_size: int = 0¶
The font size
name. A size of 0 means do not render the title. Typically a font size of 16 is appropriate.
- width: int = 5¶
The width in inches of the entire figure.
- class zensols.datdesc.figure.FigureFactory(config_factory, plot_section_regex)[source]¶
Bases:
DictableCreate instances of :.Figure using
create()or from configuration files withfrom_file(). See the usage documentation for information about the configuration files used byfrom_file().- __init__(config_factory, plot_section_regex)¶
-
config_factory:
ConfigFactory¶ The configuration factory used to create
Tableinstances.
- from_dict(figure_config)[source]¶
Return figures parsed from nested
builtins.dict(see class documentation).
- from_file(figure_path)[source]¶
Like
from_dict()but read from a YAML file.
- classmethod reset_default_instance()[source]¶
Force
default_instance()to re-instantiate a new instance on a subsequent call.
- class zensols.datdesc.figure.Plot(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None)[source]¶
Bases:
DictableAn abstract base class for plots. The subclass overrides
plot()to generate the plot. Then the client can usesave()orrender()it. The plot is created as a subplot providing attributes for space to be taken in rows, columns, height and width.- __init__(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None)¶
-
code_post_render:
str= None¶ If provided, execute code after the plot has been created. The code is executed with variable
axset theAxes,figset tomatplotlib.figure.Figureandplotset to this instance.
-
code_pre_render:
str= None¶ If provided, execute code before the plot has been created. The code is executed with variable
axset theAxes,figset tomatplotlib.figure.Figureandplotset to this instance.
- class zensols.datdesc.figure.RenderableFigure(path, factory, image_format=None, output_sty=False)[source]¶
Bases:
RenderableA renderable for figures. The output is either a directory where all figures will be written, or a file.
- __init__(path, factory, image_format=None, output_sty=False)¶
-
factory:
FigureFactory¶ .Figure using
create()or from configuration files withfrom_file().- Type:
Create instances of
- class zensols.datdesc.figure.RenderableFigureLatexPackage(artifacts, name, description='{date} Artifacts', sty_file=None)[source]¶
Bases:
RenderableLatexPackageA figure package that makes figure paths relative to
sty_file.- __init__(artifacts, name, description='{date} Artifacts', sty_file=None)¶
- sty_file: Path = None¶
The sty file to write; used to make fig paths relative.
zensols.datdesc.hyperparam module¶
Hyperparameter metadata: access and documentation. This package was designed for the following purposes:
Provide a basic scaffolding to update model hyperparameters such as
hyperopt.Generate LaTeX tables of the hyperparamers and their descriptions for academic papers.
The object instance graph hierarchy is:
HyperparamSet| +--HyperparamModel| +--Hyperparam
Access to the hyperparameters is done by calling the set or model levels
with a dotted path notation string. For example, svm.C first navigates to
model svm, then to the hyperparameter named C.
- class zensols.datdesc.hyperparam.Hyperparam(name, type, doc, choices=None, value=None, interval=None)[source]¶
Bases:
DictableA hyperparameter’s metadata, documentation and value. The value is accessed (retrieval and setting) at runtime. Do not use this class explicitly. Instead use
HyperparamModel.The index access only applies when
typeislistordict. Otherwise, thevaluemember has the value of the hyperparameter.-
CLASS_MAP:
ClassVar[dict[str,type]] = {'bool': <class 'bool'>, 'choice': <class 'str'>, 'dict': <class 'dict'>, 'float': <class 'float'>, 'int': <class 'int'>, 'list': <class 'list'>, 'str': <class 'str'>}¶ A mapping for values set in
typeto their Python class equivalents.
-
VALID_TYPES:
ClassVar[str] = frozenset({'bool', 'choice', 'dict', 'float', 'int', 'list', 'str'})¶ Valid settings for
type.
- __init__(name, type, doc, choices=None, value=None, interval=None)¶
-
doc:
str¶ The human readable documentation for the hyperparameter. This is used in documentation generation tasks.
-
CLASS_MAP:
- class zensols.datdesc.hyperparam.HyperparamContainer[source]¶
Bases:
DictableA container class for
Hyperparaminstances.- __init__()¶
- abstract flatten(deep=False)[source]¶
Return a flattened directory with the dotted path notation (see module docs).
- exception zensols.datdesc.hyperparam.HyperparamError[source]¶
Bases:
DataDescriptionErrorRaised for any error related hyperparameter access.
- __annotations__ = {}¶
- __firstlineno__ = 53¶
- __module__ = 'zensols.datdesc.hyperparam'¶
- __static_attributes__ = ()¶
- class zensols.datdesc.hyperparam.HyperparamModel(name, doc, desc=None, params=<factory>, table=None)[source]¶
Bases:
HyperparamContainerThe model level class that contains the parameters. This class represents a machine learning model such as a SVM with hyperparameters such as
Candmaximum iterations.- __init__(name, doc, desc=None, params=<factory>, table=None)¶
- create_dataframe_describer()[source]¶
Return an object with metadata fully describing the hyperparameters of this model.
- Return type:
-
desc:
str= None¶ name is not sufficient. Since
namehas naming constraints, this can be used as in place during documentation generation.- Type:
The description the model used in the documentation when obj
- flatten(deep=False)[source]¶
Return a flattened directory with the dotted path notation (see module docs).
- property metadata_dataframe: DataFrame¶
A dataframe describing the
values_dataframe.
-
name:
str¶ The name of the model (i.e.
svm). This name can have only alpha-numeric and underscore charaters.
-
params:
dict[str,Hyperparam]¶ The hyperparameters keyed by their names.
-
table:
dict[str,Any|None] = None¶ Overriding data used when creating a
TablefromDataFrameDescriber.create_table().
- property values_dataframe: DataFrame¶
A dataframe with parameter data. This includes the name, type, value and documentation.
- write(depth=0, writer=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, include_doc=False)[source]¶
Write this instance as either a
Writableor as aDictable. If class attribute_DICTABLE_WRITABLE_DESCENDANTSis set asTrue, then use thewrite()method on children instead of writing the generated dictionary. Otherwise, write this instance by first creating adictrecursively usingasdict(), then formatting the output.If the attribute
_DICTABLE_WRITE_EXCLUDESis set, those attributes are removed from what is written in thewrite()method.Note that this attribute will need to be set in all descendants in the instance hierarchy since writing the object instance graph is done recursively.
- Parameters:
depth (
int) – the starting indentation depthwriter (
TextIOBase) – the writer to dump the content of this writable
- class zensols.datdesc.hyperparam.HyperparamSet(models=<factory>, name=None)[source]¶
Bases:
HyperparamContainerThe top level in the object graph hierarchy (see module docs). This contains a set of models and typically where calls by packages such as
hyperoptare used to update the hyperparameters of the model(s).- __init__(models=<factory>, name=None)¶
- create_describer(meta_path=None)[source]¶
Return an object with metadata fully describing the hyperparameters of this model.
- Parameters:
meta_path (
Path) – if provided, set the path on the returned instance- Return type:
- flatten(deep=False)[source]¶
Return a flattened directory with the dotted path notation (see module docs).
-
models:
dict[str,HyperparamModel]¶ The models containing hyperparameters for this set.
- write(depth=0, writer=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, include_doc=False)[source]¶
Write this instance as either a
Writableor as aDictable. If class attribute_DICTABLE_WRITABLE_DESCENDANTSis set asTrue, then use thewrite()method on children instead of writing the generated dictionary. Otherwise, write this instance by first creating adictrecursively usingasdict(), then formatting the output.If the attribute
_DICTABLE_WRITE_EXCLUDESis set, those attributes are removed from what is written in thewrite()method.Note that this attribute will need to be set in all descendants in the instance hierarchy since writing the object instance graph is done recursively.
- Parameters:
depth (
int) – the starting indentation depthwriter (
TextIOBase) – the writer to dump the content of this writable
- class zensols.datdesc.hyperparam.HyperparamSetLoader(data, config=None, updates=())[source]¶
Bases:
objectLoads a set of hyperparameters from a YAML
pathlib.Path,dictor streamio.TextIOBase.- __init__(data, config=None, updates=())¶
-
config:
Configurable= None¶ The application configuration used to update the hyperparameters from other sections.
-
data:
dict[str,Any] |Path|TextIOBase¶ The source of data to load, which is a YAML
pathlib.Path,dictor streamio.TextIOBase.- See:
- load(**kwargs) HyperparamSet¶
Load and return the hyperparameter object graph from
data.- Return type:
HyperparamSet
- exception zensols.datdesc.hyperparam.HyperparamValueError[source]¶
Bases:
HyperparamErrorRaised for bad values set on a hyperparameter.
- __annotations__ = {}¶
- __firstlineno__ = 60¶
- __module__ = 'zensols.datdesc.hyperparam'¶
- __static_attributes__ = ()¶
- class zensols.datdesc.hyperparam.RenderableHyperparamSet(path, hyperparam_table_default=None)[source]¶
Bases:
RenderableReads
HyperparamSetinstances and writes latex tables.- __init__(path, hyperparam_table_default=None)¶
zensols.datdesc.latex module¶
Contains the manager classes that invoke the tables to generate.
- class zensols.datdesc.latex.LatexTable(name, path, template, template_params=<factory>, caption='', definition_file=None, head=None, writes=<factory>, uses=<factory>, default_params=<factory>, params=<factory>, type=None, hlines=<factory>, double_hlines=<factory>, rules=<factory>, column_keeps=None, column_removes=<factory>, column_renames=<factory>, column_value_replaces=<factory>, column_aligns=None, round_column_names=<factory>, percent_column_names=(), make_percent_column_names=<factory>, format_thousands_column_names=<factory>, format_scientific_column_names=<factory>, read_params=<factory>, tabulate_params=<factory>, replace_nan=None, blank_columns=<factory>, bold_cells=<factory>, bold_max_columns=<factory>, capitalize_columns=<factory>, index_col_name=None, variables=<factory>, code_pre=None, code_post=None, code_format=None, code_render=None, row_range=(1, -1), row_deletes=frozenset({}), booktabs=False)[source]¶
Bases:
TableThis subclass generates LaTeX tables.
- __init__(name, path, template, template_params=<factory>, caption='', definition_file=None, head=None, writes=<factory>, uses=<factory>, default_params=<factory>, params=<factory>, type=None, hlines=<factory>, double_hlines=<factory>, rules=<factory>, column_keeps=None, column_removes=<factory>, column_renames=<factory>, column_value_replaces=<factory>, column_aligns=None, round_column_names=<factory>, percent_column_names=(), make_percent_column_names=<factory>, format_thousands_column_names=<factory>, format_scientific_column_names=<factory>, read_params=<factory>, tabulate_params=<factory>, replace_nan=None, blank_columns=<factory>, bold_cells=<factory>, bold_max_columns=<factory>, capitalize_columns=<factory>, index_col_name=None, variables=<factory>, code_pre=None, code_post=None, code_format=None, code_render=None, row_range=(1, -1), row_deletes=frozenset({}), booktabs=False)¶
-
booktabs:
bool= False¶ Whether or not to use the
booktabsstyle table and to format using its style.
- class zensols.datdesc.latex.RenderableLatexTable(path, factory)[source]¶
Bases:
RenderableA renderable for table definitions in yaml files. The output is a latex
.styfile with the output table as a command (seetable_factory).- __init__(path, factory)¶
-
factory:
TableFactory¶ Reads the table definitions file and writes a Latex
.styfile of the generated tables from the CSV data.
- class zensols.datdesc.latex.SlackTable(name, path, template, template_params=<factory>, caption='', definition_file=None, head=None, writes=<factory>, uses=<factory>, default_params=<factory>, params=<factory>, type=None, hlines=<factory>, double_hlines=<factory>, rules=<factory>, column_keeps=None, column_removes=<factory>, column_renames=<factory>, column_value_replaces=<factory>, column_aligns=None, round_column_names=<factory>, percent_column_names=(), make_percent_column_names=<factory>, format_thousands_column_names=<factory>, format_scientific_column_names=<factory>, read_params=<factory>, tabulate_params=<factory>, replace_nan=None, blank_columns=<factory>, bold_cells=<factory>, bold_max_columns=<factory>, capitalize_columns=<factory>, index_col_name=None, variables=<factory>, code_pre=None, code_post=None, code_format=None, code_render=None, row_range=(1, -1), row_deletes=frozenset({}), booktabs=False, slack_column=0)[source]¶
Bases:
LatexTableAn instance of the table that fills up space based on the widest column.
- __init__(name, path, template, template_params=<factory>, caption='', definition_file=None, head=None, writes=<factory>, uses=<factory>, default_params=<factory>, params=<factory>, type=None, hlines=<factory>, double_hlines=<factory>, rules=<factory>, column_keeps=None, column_removes=<factory>, column_renames=<factory>, column_value_replaces=<factory>, column_aligns=None, round_column_names=<factory>, percent_column_names=(), make_percent_column_names=<factory>, format_thousands_column_names=<factory>, format_scientific_column_names=<factory>, read_params=<factory>, tabulate_params=<factory>, replace_nan=None, blank_columns=<factory>, bold_cells=<factory>, bold_max_columns=<factory>, capitalize_columns=<factory>, index_col_name=None, variables=<factory>, code_pre=None, code_post=None, code_format=None, code_render=None, row_range=(1, -1), row_deletes=frozenset({}), booktabs=False, slack_column=0)¶
zensols.datdesc.opt module¶
zensols.datdesc.optscore module¶
zensols.datdesc.plots module¶
Common used plots for ML.
- class zensols.datdesc.plots.BarPlot(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, data=None, palette=None, x_axis_label=None, y_axis_label=None, x_column_name=None, y_column_name=None, hue_column_name=None, x_label_rotation=0, key_title=None, log_scale=None, render_value_font_size=None, render_value_format=None, hue_palette=False, plot_params=<factory>)[source]¶
Bases:
PaletteContainerPlot,DataFramePlotCreate a bar plot using
seaborn.barplot().- __init__(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, data=None, palette=None, x_axis_label=None, y_axis_label=None, x_column_name=None, y_column_name=None, hue_column_name=None, x_label_rotation=0, key_title=None, log_scale=None, render_value_font_size=None, render_value_format=None, hue_palette=False, plot_params=<factory>)¶
-
hue_column_name:
str= None¶ The column in
dataused for the data hue (each data category will have a unique inpalette.
- class zensols.datdesc.plots.CodePlot(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, palette=None, code='', context=None)[source]¶
Bases:
PaletteContainerPlotA plotter that executes
code_renderas a Python block.- __init__(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, palette=None, code='', context=None)¶
- class zensols.datdesc.plots.DataFramePlot(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, data=None)[source]¶
Bases:
PlotA base class for plots that render data from a Pandas dataframe.
- __init__(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, data=None)¶
- class zensols.datdesc.plots.HeatMapPlot(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, data=None, palette=None, format='.2f', x_label_rotation=0, params=<factory>)[source]¶
Bases:
PaletteContainerPlot,DataFramePlotCreate heat map plot and optionally normalize. This uses
seaborn’sheatmap.- __init__(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, data=None, palette=None, format='.2f', x_label_rotation=0, params=<factory>)¶
- class zensols.datdesc.plots.HistPlot(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, palette=None, data=<factory>, x_axis_label=None, y_axis_label=None, key_title=None, log_scale=None, plot_params=<factory>)[source]¶
Bases:
PaletteContainerPlotCreate a histogram plot using
seaborn.histplot().- __init__(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, palette=None, data=<factory>, x_axis_label=None, y_axis_label=None, key_title=None, log_scale=None, plot_params=<factory>)¶
-
data:
list[tuple[str,DataFrame]]¶ The data to plot. Each element is tuple first components with the plot name.
- class zensols.datdesc.plots.PaletteContainerPlot(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, palette=None)[source]¶
Bases:
PlotA base class that supports creating a color palette for subclasses.
- __init__(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, palette=None)¶
- class zensols.datdesc.plots.PointPlot(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, data=None, palette=None, point_data=None, x_axis_name=None, y_axis_name=None, x_column_name='x', y_column_name='y', key_title=None, sample_rate=0, plot_params=<factory>, hue_name=None, hue_names=None)[source]¶
Bases:
PaletteContainerPlot,DataFramePlotAn abstract base class that renders overlapping lines that uses a
seabornpointplot.- __init__(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, data=None, palette=None, point_data=None, x_axis_name=None, y_axis_name=None, x_column_name='x', y_column_name='y', key_title=None, sample_rate=0, plot_params=<factory>, hue_name=None, hue_names=None)¶
- add(name, line, x_vals=None)[source]¶
Add the losses of a dataset by adding X values as incrementing integers the size of
line.
-
plot_params:
dict[str,Any]¶ Parameters given to
seaborn.plotpoint(). The default are decorative parameters for the marker size and line width.
-
point_data:
list[tuple[str,DataFrame]] = None¶ The data to plot. Each element is tuple first components with the plot name. The second component is a dataframe with columns:
x_column_name: the X values of the graph, usually an incrementing numbery_column_name: a list loss float values
Optionally use
add_line()to populate this list.
- class zensols.datdesc.plots.RadarPlot(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, data=None, key_title=None, frame='circle', render_value_font_size=None, label_gap=None, alpha=0.25)[source]¶
Bases:
DataFramePlotA radar plot (a.k.a. spider plolt).
- __init__(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, data=None, key_title=None, frame='circle', render_value_font_size=None, label_gap=None, alpha=0.25)¶
- class zensols.datdesc.plots.ScatterPlot(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, data=None, palette=None, scatter_data=None, x_axis_name=None, y_axis_name=None, x_column_name='x', y_column_name='y', key_title=None, sample_rate=0, plot_params=<factory>, hue_name=None, hue_names=None)[source]¶
Bases:
PaletteContainerPlot,DataFramePlotRender a scatter plot using
seabornscatterplot.This is a simpler version of
PointPlotfor when only point rendering is needed.- __init__(title=None, row=0, column=0, post_hooks=<factory>, legend_params=<factory>, code_pre_render=None, code_post_render=None, data=None, palette=None, scatter_data=None, x_axis_name=None, y_axis_name=None, x_column_name='x', y_column_name='y', key_title=None, sample_rate=0, plot_params=<factory>, hue_name=None, hue_names=None)¶
-
scatter_data:
list[tuple[str,DataFrame]] = None¶ The data to plot. Each element is a tuple with the plot name and a dataframe with columns:
x_column_name: the X values of the graphy_column_name: the Y values of the graph
Optionally use
add()to populate this list.
zensols.datdesc.proto module¶
zensols.datdesc.render module¶
Classes to create first class object and process files.
- class zensols.datdesc.render.Renderable(path)[source]¶
Bases:
DictableCreates rendered output from a machine readble input file.
- __init__(path)¶
-
path:
Path¶ The input definition of the object to render.
- class zensols.datdesc.render.RenderableArtifact(name, path, template, template_params=<factory>, caption='', definition_file=None, head=None, writes=<factory>)[source]¶
Bases:
PersistableContainer,DictableData that can be rendered from a
Renderable.- __init__(name, path, template, template_params=<factory>, caption='', definition_file=None, head=None, writes=<factory>)¶
-
definition_file:
Path= None¶ The YAML file from which this instance was created.
-
head:
str= None¶ The header to use for the table, which is used as the text in the list of tables and made bold in the table.
- property path: Path¶
The file that has the data used to populate this artifiact.
- write(depth=0, writer=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Write this instance as either a
Writableor as aDictable. If class attribute_DICTABLE_WRITABLE_DESCENDANTSis set asTrue, then use thewrite()method on children instead of writing the generated dictionary. Otherwise, write this instance by first creating adictrecursively usingasdict(), then formatting the output.If the attribute
_DICTABLE_WRITE_EXCLUDESis set, those attributes are removed from what is written in thewrite()method.Note that this attribute will need to be set in all descendants in the instance hierarchy since writing the object instance graph is done recursively.
- Parameters:
depth (
int) – the starting indentation depthwriter (
TextIOBase) – the writer to dump the content of this writable
- class zensols.datdesc.render.RenderableFactory(config_factory, types, name_format)[source]¶
Bases:
DictableCreates instances of
Renderablefrom file paths.- __init__(config_factory, types, name_format)¶
-
config_factory:
ConfigFactory¶ Creates table and figure factories.
zensols.datdesc.renderlatex module¶
Things rendered for LaTeX files (usually .sty).
- class zensols.datdesc.renderlatex.RenderableLatexArtifact(name, path, template, template_params=<factory>, caption='', definition_file=None, head=None, writes=<factory>, uses=<factory>, default_params=<factory>, params=<factory>)[source]¶
Bases:
RenderableArtifactSubclasses implement behavior to render LaTeX files. There are also utility method for generating latex commands.
- __init__(name, path, template, template_params=<factory>, caption='', definition_file=None, head=None, writes=<factory>, uses=<factory>, default_params=<factory>, params=<factory>)¶
-
default_params:
Sequence[Sequence[str]]¶ Default parameters to be substituted in the template that are interpolated by (i.e. LaTeX) numeric values such as #1, #2, etc. This is a sequence (list or tuple) of
(<name>, [<default>])wherenameis substituted by name in the template anddefaultis the default if not given inparams.For any that have no default, which is a singleton paramenter name, arguments are created for the function that must be supplied to the function.
-
params:
dict[str,str]¶ Parameters used in the template that override of the
default_params.
- class zensols.datdesc.renderlatex.RenderableLatexPackage(artifacts, name, description='{date} Artifacts')[source]¶
Bases:
DictableGenerate a Latex table from a CSV file.
- __init__(artifacts, name, description='{date} Artifacts')¶
-
artifacts:
Sequence[RenderableLatexArtifact]¶ A list of instances to create Latex definitions.
zensols.datdesc.table module¶
This module contains classes that generate tables.
- class zensols.datdesc.table.Table(name, path, template, template_params=<factory>, caption='', definition_file=None, head=None, writes=<factory>, uses=<factory>, default_params=<factory>, params=<factory>, type=None, hlines=<factory>, double_hlines=<factory>, rules=<factory>, column_keeps=None, column_removes=<factory>, column_renames=<factory>, column_value_replaces=<factory>, column_aligns=None, round_column_names=<factory>, percent_column_names=(), make_percent_column_names=<factory>, format_thousands_column_names=<factory>, format_scientific_column_names=<factory>, read_params=<factory>, tabulate_params=<factory>, replace_nan=None, blank_columns=<factory>, bold_cells=<factory>, bold_max_columns=<factory>, capitalize_columns=<factory>, index_col_name=None, variables=<factory>, code_pre=None, code_post=None, code_format=None, code_render=None)[source]¶
Bases:
RenderableLatexArtifactGenerate and render a formatted table from tabular data.
A table manages the transformation of a dataframe into a rendered artifact, typically a LaTeX table. The source dataframe passes through several processing stages before being rendered with
tabulateand the configured table template.The dataframe processing stages are:
nascentThe original dataframe before any table-specific processing.
unformattedThe dataframe after
code_prehas executed, but before numeric formatting is applied.postformatThe dataframe after numeric formatting and
code_posthave been applied.formattedThe final dataframe after structural and presentation formatting, including column manipulation, capitalization, font formatting, and
code_format. This dataframe is used to generate the table.
Several Python code hooks allow customization at specific stages of the processing pipeline:
code_preExecuted before numeric or presentation formatting. The local variable
dfcontains the dataframe and may be modified or replaced.code_postExecuted after numeric formatting, including rounding, percentages, thousands separators, and scientific notation, but before the final structural and presentation formatting steps.
code_formatExecuted after all built-in dataframe formatting has completed. This is the final opportunity to modify
dfbefore it is passed totabulate.code_renderExecuted after
tabulatehas rendered the dataframe to text but before the surrounding table template is rendered. The local variabletablecontains the rendered table lines and may be modified in place. This is useful for output-specific changes such as inserting LaTeX\multicolumncommands.
For example:
results: path: results.csv round_column_names: score: 2 code_pre: | df = df[df['enabled']] code_post: | df['score'] = df['score'].astype(str)
Table variables may also reference values from intermediate processing stages through
variables, allowing generated commands or rendered values to use either raw or formatted dataframe values. Subclasses provide output-specific behavior such as scientific-number formatting, row extraction fortabulate, and rendering of table and variable content.- __init__(name, path, template, template_params=<factory>, caption='', definition_file=None, head=None, writes=<factory>, uses=<factory>, default_params=<factory>, params=<factory>, type=None, hlines=<factory>, double_hlines=<factory>, rules=<factory>, column_keeps=None, column_removes=<factory>, column_renames=<factory>, column_value_replaces=<factory>, column_aligns=None, round_column_names=<factory>, percent_column_names=(), make_percent_column_names=<factory>, format_thousands_column_names=<factory>, format_scientific_column_names=<factory>, read_params=<factory>, tabulate_params=<factory>, replace_nan=None, blank_columns=<factory>, bold_cells=<factory>, bold_max_columns=<factory>, capitalize_columns=<factory>, index_col_name=None, variables=<factory>, code_pre=None, code_post=None, code_format=None, code_render=None)¶
- asflatdict(*args, **kwargs)[source]¶
Like
asdict()but flatten in to a data structure suitable for writing to JSON or YAML.
- blank_columns: list[int]¶
A list of column indexes to set to the empty string (i.e. 0th to fixed the
Unnamed: 0issues).
- bold_cells: list[tuple[int, int]]¶
A list of row/column cells to bold.
- bold_max_columns: list[str]¶
A list of column names that will have its max value bolded.
- capitalize_columns: dict[str, bool]¶
Capitalize either sentences (
Falsevalues) or every word (Truevalues). The keys are column names.
- code_format: str = None¶
Like
code_postbut modifies the table after this class’s all formatting of the table (including those applied by this class).
- code_post: str = None¶
Like
code_prebut modifies the table after this class’s modifications of the table.
- code_pre: str = None¶
Python code executed that manipulates the table’s dataframe before modifications made by this class. The code has a local
dfvariable and the returned value is used as the replacement. This is usually a one-liner used to subset the data etc. The code is evaluated witheval().
- code_render: str = None¶
Like
code_formatbut modifies the rendered table as atyping.Listof lines with variable nametable. Modify this list to change the final rendered output of the table, such as applying Latex multicolumn lines.
- column_aligns: str = None¶
The alignment/justification (i.e.
|l|l|for two columns). If not provided, they are automatically generated based on the columns of the table.
- column_keeps: list[str] | None = None¶
If provided, only keep the columns in the list
- column_removes: list[str]¶
The name of the columns to remove from the table, if any.
- column_renames: dict[str, str]¶
Columns to rename, if any.
- column_value_replaces: dict[str, dict[Any, Any]]¶
Data values to replace in the dataframe. It is keyed by the column name and values are the replacements. Each value is a
dictwith orignal value keys and the replacements as values.
- double_hlines: Sequence[int]¶
Indexes of rows to put double horizontal line breaks.
- format_scientific_column_names: dict[str, int | None]¶
Format a column using LaTeX formatted scientific notation using
format_scientific(). Keys are column names and values is the mantissa length or 1 ifNone.
- static format_thousand(x, apply_k=True, add_comma=True, round=None, max_k=1000)[source]¶
Format a number as a string with comma separating thousands.
- format_thousands_column_names: dict[str, dict[str, Any] | None]¶
Columns to format using thousands, and optionally round. The keys are the column names of the table and the values are either
Noneor the keyword arguments toformat_thousand().
- property formatted_dataframe: DataFrame¶
The
dataframewith the formatting applied to it used to create the Latex table. Modifications such as string replacements for adding percents is done.
- hlines: Sequence[int]¶
Indexes of rows to put horizontal line breaks.
- index_col_name: str = None¶
If set, add an index column with the given name.
- make_percent_column_names: dict[str, int | str]¶
Each columnn in the map will get rounded to the value * 100 of the name. For example,
{'ann_per': 3}will round columnann_perto 3 decimal places.If the values are strings then it is interpreted as a Python f-string using
vas the value. For example,{'ann_per': '{v:.1f}'}gives a percentage to the first decimal without the percentage sign (%).
- percent_column_names: Sequence[str] = ()¶
Column names that have a percent sign to be escaped.
- read_params: dict[str, str]¶
Keyword arguments used in the
read_csv()call when reading the CSV file.
- replace_nan: str = None¶
Replace NaN values with a the value of this field as
tabulate()is not using the missing value due to some bug I assume.
- round_column_names: dict[str, tuple[int, int] | int]¶
Each column in the map will get rounded to their respective values.
For tuple values the number will be rounded as an integer if higher than a cutoff (second element), otherwise it is rounded to the decimal (first element).
- rules: dict[int, str]¶
Like
hlinesbut allows other horizontal lines such astoprule. Each key/value is a tuple of row and the verbatim text to add at that place.
- tabulate_params: dict[str, str]¶
Keyword arguments used in the
tabulate()call when writing the table. The default tellstabulateto not parse/format numerical data.
- type: str = None¶
The type of table (i.e.
one_column).
- variables: dict[str, tuple[int, int] | str]¶
A mapping of variable names to a dataframe cell or Python code snipped that is evaluated with
exec(). In LaTeX, this is done by setting anewcommand(seeLatexTable).If set to a tuple of
(<row>, <column>)the value of the pre-formatted dataframe is used (seeunformattedbelow).If a Python evalution string, the code values must set variables
vto the variable value. A variablestagesis aDictused to get one of the dataframes created at various stages of formatting the table with entries:nascent: same asdataframeunformatted: after the pre-evaluation but before any formattingpostformat: after number formatting and post evaluation, but before remaining column and cell modificationsformatted: same asformatted_dataframe
For example, the following uses the value at row 2 and column 3 of the unformatted dataframe:
v = stages['unformatted'].iloc[2, 3]
- writes: list[str]¶
A list of what to output for this table. Entries are
tableandvaraibles.
- class zensols.datdesc.table.TableFactory(config_factory, table_section_regex, default_table_type)[source]¶
Bases:
DictableReads the table definitions file and writes a Latex
.styfile of the generated tables from the CSV data. Tables are created with eitherusage()orfrom_file(). See the usage documentation for information about the configuration files used byfrom_file().- __init__(config_factory, table_section_regex, default_table_type)¶
-
config_factory:
ConfigFactory¶ The configuration factory used to create
Tableinstances.
-
default_table_type:
str¶ The default name, which resolves to a section name, to use when creating anonymous tables.
- classmethod reset_default_instance()[source]¶
Force
default_instance()to re-instantiate a new instance on a subsequent call.
Module contents¶
Generate Latex tables in a .sty file from CSV files. The paths to the CSV files to create tables from and their metadata is given as a YAML configuration file.