Skip to content

Commit

Permalink
Improve docstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
Verweijen committed Jan 10, 2025
1 parent ec099c1 commit f04c2a2
Show file tree
Hide file tree
Showing 27 changed files with 134 additions and 43 deletions.
40 changes: 23 additions & 17 deletions docs/source/api.rst
Original file line number Diff line number Diff line change
@@ -1,39 +1,45 @@
===
API
===

InputData
---------
.. automodule:: piargus.inputdata
Input Specification
===================

Input data
----------
.. automodule:: piargus.inputspec
:members: InputData, MetaData, MicroData, TableData, CodeList
:show-inheritance:

Hierarchies
-----------
.. automodule:: piargus.inputdata.hierarchy
:members: Hierarchy, TreeHierarchy, FlatHierarchy, LevelHierarchy
.. automodule:: piargus.inputspec.hierarchy
:members: Hierarchy, TreeHierarchy, FlatHierarchy, LevelHierarchy, TreeHierarchyNode
:show-inheritance:

Safety rule
-----------
.. automodule:: piargus
:members: dominance_rule, percent_rule, frequency_rule, request_rule, zero_rule, missing_rule, weight_rule, manual_rule, p_rule, nk_rule,
:show-inheritance:
Output Specification
====================

Output
Tables
------
.. automodule:: piargus.outputspec
:members: Table, Apriori, TreeRecode
:show-inheritance:

Safety rule
-----------
.. automodule:: piargus
:members: Table, Apriori, TreeRecode
:members: dominance_rule, percent_rule, frequency_rule, request_rule, zero_rule, missing_rule, weight_rule, manual_rule, p_rule, nk_rule,
:show-inheritance:

Jobs
----
Result
======
.. automodule:: piargus
:members: Job, JobSetupError
:members: ArgusReport, TableResult
:show-inheritance:

Tau-Argus
---------
=========
.. automodule:: piargus
:members: TauArgus, BatchWriter
:members: TauArgus, BatchWriter, Job, JobSetupError
:show-inheritance:
24 changes: 16 additions & 8 deletions src/piargus/__init__.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,31 @@
from .argusreport import TauArgusException
from .batchwriter import BatchWriter
from .constants import *
from .inputdata import InputData, MetaData, MicroData, TableData, CodeList
from .inputdata.hierarchy import Hierarchy, FlatHierarchy, TreeHierarchy, \
from .inputspec import InputData, MetaData, MicroData, TableData, CodeList
from .inputspec.hierarchy import Hierarchy, FlatHierarchy, TreeHierarchy, \
TreeHierarchyNode, Node, LevelHierarchy
from .job import Job, JobSetupError
from .table import Table, Apriori, TreeRecode
from .table.safetyrule import *
from .outputspec import Table, Apriori, TreeRecode
from .outputspec.safetyrule import *
from .result import TauArgusException, ArgusReport, TableResult
from .tauargus import TauArgus

__version__ = "1.0.2"

__all__ = [
"Apriori",
"TauArgus",
"TauArgusException",
"BatchWriter",
"CodeList",
"TreeRecode",
"Job",
"JobSetupError",

# Inputdata
"InputData",
"MetaData",
"MicroData",
"TableData",
"Job",
"JobSetupError",

# Hierarchy
"Hierarchy",
Expand All @@ -44,8 +47,13 @@
"manual_rule",
"p_rule",
"nk_rule",

# Table
"Table",
"TauArgus",

# Result
"ArgusReport",
"TableResult",

# Constants
"SAFE",
Expand Down
29 changes: 25 additions & 4 deletions src/piargus/batchwriter.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .constants import FREQUENCY_RESPONSE
from .table.safetyrule import make_safety_rule
from .utils import format_argument
from .outputspec.safetyrule import make_safety_rule
from .helpers import format_argument


class BatchWriter:
Expand All @@ -22,19 +22,30 @@ def write_command(self, command, arg=None):
return command, arg

def logbook(self, log_file):
"""Write LOGBOOK to batch file."""
self.write_command('LOGBOOK', format_argument(log_file))

def open_microdata(self, microdata):
"""Write OPENMICRODATA to batch file."""
return self.write_command("OPENMICRODATA", format_argument(microdata))

def open_tabledata(self, tabledata):
"""Write OPENTABLEDATA to batch file."""
return self.write_command("OPENTABLEDATA", format_argument(tabledata))

def open_metadata(self, metadata):
"""Write METADATA to batch file."""
return self.write_command("OPENMETADATA", format_argument(metadata))

def specify_table(self, explanatory, response=FREQUENCY_RESPONSE, shadow=None, cost=None,
labda=None):
def specify_table(
self,
explanatory,
response=FREQUENCY_RESPONSE,
shadow=None,
cost=None,
labda=None
):
"""Write SPECIFYTABLE to batch file."""
explanatory_str = "".join([format_argument(v) for v in explanatory])
response_str = format_argument(response)
shadow_str = format_argument(shadow)
Expand All @@ -45,15 +56,18 @@ def specify_table(self, explanatory, response=FREQUENCY_RESPONSE, shadow=None, c
return self.write_command('SPECIFYTABLE', options)

def read_microdata(self):
"""Write READMICRODATA to batch file."""
return self.write_command("READMICRODATA")

def read_table(self, compute_totals=None):
"""Write READTABLE to batch file."""
if compute_totals is None:
return self.write_command("READTABLE")
else:
return self.write_command("READTABLE", int(compute_totals))

def apriori(self, filename, table, separator=',', ignore_error=False, expand_trivial=True):
"""Write APRIORI to batch file."""
filename = format_argument(filename)
table = format_argument(table)
separator = format_argument(separator)
Expand All @@ -63,32 +77,39 @@ def apriori(self, filename, table, separator=',', ignore_error=False, expand_tri
return self.write_command("APRIORI", arg)

def recode(self, table, variable, file_or_treelevel):
"""Write RECODE to batch file."""
table = format_argument(table)
variable = format_argument(variable)
file_or_treelevel = format_argument(file_or_treelevel)
arg = f"{table}, {variable}, {file_or_treelevel}"
return self.write_command("RECODE", arg)

def safety_rule(self, rule="", /, *, individual="", holding=""):
"""Write SAFETYRULE to batch file."""
rule = make_safety_rule(rule, individual=individual, holding=holding)
return self.write_command('SAFETYRULE', rule)

def suppress(self, method, table, *method_args):
"""Write SUPPRESS to batch file."""
args = ",".join(map(format_argument, [table, *method_args]))
return self.write_command('SUPPRESS', f"{method}({args})")

def write_table(self, table, kind, options, filename):
"""Write WRITETABLE to batch file."""
if hasattr(options, 'items'):
options = "".join([k + {True: "+", False: "-"}[v] for k, v in options.items()])

result = f"({table}, {kind}, {options}, {format_argument(filename)})"
return self.write_command('WRITETABLE', result)

def version_info(self, filename):
"""Write VERSIONINFO to batch file."""
return self.write_command("VERSIONINFO", format_argument(filename))

def go_interactive(self):
"""Write GOINTERACTIVE to batch file."""
return self.write_command("GOINTERACTIVE")

def clear(self):
"""Write CLEAR to batch file."""
return self.write_command("CLEAR")
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class CodeList:

@classmethod
def from_cdl(cls, file):
"""Read cdl file."""
df = pd.read_csv(file, index_col=0, header=None)
codelist = CodeList(df.iloc[:, 0])
if isinstance(file, (str, Path)):
Expand All @@ -20,6 +21,7 @@ def from_cdl(cls, file):
return codelist

def __init__(self, codes):
"""Create a codelist."""
if hasattr(codes, 'keys'):
self._codes = pd.Series(codes)
else:
Expand All @@ -35,9 +37,11 @@ def __str__(self):
return self.to_cdl()

def __getitem__(self, key):
"""Get label of a code."""
return self._codes[key]

def __setitem__(self, key, value):
"""Set label of a code."""
self._codes[key] = value

def __iter__(self):
Expand All @@ -57,10 +61,12 @@ def keys(self):
return self._codes.keys()

def iter_codes(self):
"""Iterate through codes."""
for code in self._codes.index:
yield code

def to_cdl(self, file=None, length=0):
"""Store codelist in cdl file."""
codes = self._codes.copy()
codes.index = codes.index.str.rjust(length)
result = codes.to_csv(file, header=False)
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class FlatHierarchy(Hierarchy):
is_hierarchical = False

def __init__(self, *, total_code=DEFAULT_TOTAL_CODE):
"""Create a FlatHierarchy."""
self.total_code = total_code

def __repr__(self):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class LevelHierarchy(Hierarchy):
is_hierarchical = True

def __init__(self, levels, *, total_code: str = DEFAULT_TOTAL_CODE):
"""Create a tree hierarchy."""
self.levels = [int(level) for level in levels]
self.total_code = total_code

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class TreeHierarchy(Hierarchy):
is_hierarchical = True

def __init__(self, tree=None, *, total_code: str = DEFAULT_TOTAL_CODE, indent='@'):
"""Create a tree hierarchy."""
if not isinstance(tree, TreeHierarchyNode):
tree = TreeHierarchyNode(total_code, tree)
self.root = tree
Expand All @@ -40,18 +41,25 @@ def __hash__(self):

@property
def total_code(self) -> str:
"""The code used as a total."""
return self.root.code

@total_code.setter
def total_code(self, value):
self.root.code = value

def get_node(self, path) -> Optional["TreeHierarchyNode"]:
"""Return single Node, None if it doesn't exist, ValueError if path not unique."""
"""Obtain a node within the hierarchy.
Return single Node, None if it doesn't exist, ValueError if path not unique."""
return self.root.path.get(path)

def create_node(self, path) -> "TreeHierarchyNode":
"""Return single Node, None if it doesn't exist, ValueError if path not unique."""
"""Create a node within the hierarchy.
The newly created node is returned.
If the node already existed, the existing one is returned.
"""
return self.root.path.create(path)

@property
Expand All @@ -71,6 +79,7 @@ def code_length(self):

@classmethod
def from_hrc(cls, file, indent='@', total_code=DEFAULT_TOTAL_CODE):
"""Create hierarchy from a hrc-file."""
if isinstance(file, (str, Path)):
with open(file) as reader:
hierarchy = cls.from_hrc(reader, indent, total_code)
Expand All @@ -82,6 +91,7 @@ def from_hrc(cls, file, indent='@', total_code=DEFAULT_TOTAL_CODE):
return cls(root, indent=indent)

def to_hrc(self, file=None, length=0):
"""Write hierarchy to a hrc-file."""
if file is None:
file = io.StringIO(newline=os.linesep)
self.to_hrc(file, length)
Expand Down Expand Up @@ -122,9 +132,11 @@ def to_relations(self, child_name="code", parent_name="parent"):
return serializer.to_relations(self.root)

def to_image(self, **kwargs):
"""Export the hierarchy file as an image."""
return self.root.to_image(**kwargs)

def to_pillow(self, **kwargs):
"""Export the hierarchy file as a Pillow image."""
if hasattr(self.root, 'to_pillow'):
# Newer versions
return self.root.to_pillow(**kwargs)
Expand All @@ -151,6 +163,7 @@ def __init__(self, code=None, children=(), parent=None):

@property
def code(self):
"""Which code belongs to this node."""
return self.identifier

@code.setter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ def __init__(

@abc.abstractmethod
def to_csv(self, target):
"""Save data to a file in the csv-format which tau-argus requires."""
raise NotImplementedError

@abc.abstractmethod
Expand Down Expand Up @@ -106,6 +107,7 @@ def resolve_column_lengths(self, default=DEFAULT_COLUMN_LENGTH):

@property
def hierarchies(self):
"""The hierarchies attached to input data."""
return self._hierarchies

@hierarchies.setter
Expand All @@ -115,6 +117,7 @@ def hierarchies(self, value):

@property
def codelists(self):
"""The codelists attached to input data."""
return self._codelists

@codelists.setter
Expand Down
Loading

0 comments on commit f04c2a2

Please sign in to comment.