Skip to content

Commit

Permalink
Make pre-commit happy about code style
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelosthege committed Jan 30, 2024
1 parent 5466828 commit 1087df5
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 14 deletions.
27 changes: 18 additions & 9 deletions mcbackend/backends/clickhouse.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@
}


class ClickHouseBackendError(Exception):
"""Something bad happened in the ClickHouse backend."""


def create_runs_table(client: clickhouse_driver.Client):
query = """
CREATE TABLE IF NOT EXISTS runs (
Expand Down Expand Up @@ -80,7 +84,7 @@ def create_chain_table(client: clickhouse_driver.Client, meta: ChainMeta, rmeta:
# Check that it does not already exist
cid = chain_id(meta)
if client.execute(f"SHOW TABLES LIKE '{cid}';"):
raise Exception(f"A table for {cid} already exists.")
raise ClickHouseBackendError(f"A table for {cid} already exists.")

# Create a table with columns corresponding to the model variables
columns = []
Expand Down Expand Up @@ -236,7 +240,7 @@ def _get_row_at(
query = f"SELECT (`{names}`,) FROM {self.cid} WHERE _draw_idx={idx};"
data = self._client.execute(query)
if not data:
raise Exception(f"No record found for draw index {idx}.")
raise ClickHouseBackendError(f"No record found for draw index {idx}.")
result = dict(zip(var_names, data[0][0]))
return result

Expand Down Expand Up @@ -364,7 +368,10 @@ def __init__(
raise ValueError("Either a `client` or a `client_fn` must be provided.")

if client_fn is None:
client_fn = lambda: client

def client_fn():
return client

if client is None:
client = client_fn()

Expand All @@ -382,11 +389,11 @@ def init_run(self, meta: RunMeta) -> ClickHouseRun:
else:
created_at = datetime.now().astimezone(timezone.utc)
query = "INSERT INTO runs (created_at, rid, proto) VALUES"
params = dict(
created_at=created_at,
rid=meta.rid,
proto=base64.encodebytes(bytes(meta)).decode("ascii"),
)
params = {
"created_at": created_at,
"rid": meta.rid,
"proto": base64.encodebytes(bytes(meta)).decode("ascii"),
}
self._client.execute(query, [params])
return ClickHouseRun(meta, client_fn=self._client_fn, created_at=created_at)

Expand All @@ -408,7 +415,9 @@ def get_run(self, rid: str) -> ClickHouseRun:
{"rid": rid},
)
if len(rows) != 1:
raise Exception(f"Unexpected number of {len(rows)} results for rid='{rid}'.")
raise ClickHouseBackendError(
f"Unexpected number of {len(rows)} results for rid='{rid}'."
)
data = base64.decodebytes(rows[0][2].encode("ascii"))
meta = RunMeta().parse(data)
return ClickHouseRun(
Expand Down
6 changes: 2 additions & 4 deletions mcbackend/backends/numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ class NumPyRun(Run):
"""An MCMC run where samples are kept in memory."""

def __init__(self, meta: RunMeta, *, preallocate: int) -> None:
self._settings = dict(preallocate=preallocate)
self._settings = {"preallocate": preallocate}
self._chains: List[NumPyChain] = []
super().__init__(meta)

Expand All @@ -129,9 +129,7 @@ class NumPyBackend(Backend):
"""An in-memory backend using NumPy."""

def __init__(self, preallocate: int = 1_000) -> None:
self._settings = dict(
preallocate=preallocate,
)
self._settings = {"preallocate": preallocate}
super().__init__()

def init_run(self, meta: RunMeta) -> NumPyRun:
Expand Down
6 changes: 5 additions & 1 deletion mcbackend/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@
__all__ = ("is_rigid", "chain_id", "Chain", "Run", "Backend")


class ChainError(Exception):
"""Something is not right in one chain."""


def is_rigid(nshape: Optional[Shape]):
"""Determines wheather the shape is constant.
Expand Down Expand Up @@ -119,7 +123,7 @@ def __len__(self) -> int:
]:
for var in items:
return len(method(var.name))
raise Exception("This chain has no variables or sample stats.")
raise ChainError("This chain has no variables or sample stats.")

@property
def cid(self) -> str:
Expand Down

0 comments on commit 1087df5

Please sign in to comment.