causilo-db 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
causilo_db/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Run Causilo on database tables: fill the blank cells of a column."""
2
+
3
+ from .core import CausiloDBError, PartialPredictionError, Prediction, infer_task, predict_frame
4
+ from .sql import predict_table, read_table
5
+
6
+ __version__ = "0.2.0"
7
+ __all__ = ["CausiloDBError", "PartialPredictionError", "Prediction", "infer_task", "predict_frame", "predict_table", "read_table"]
causilo_db/cli.py ADDED
@@ -0,0 +1,79 @@
1
+ """causilo-db command line: predict the blank cells of a column of a database table."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from . import __version__
9
+ from .core import CausiloDBError
10
+ from .sql import predict_table
11
+
12
+ EPILOG = """example:
13
+ export CAUSILO_API_KEY=csl_...
14
+ causilo-db predict postgresql+psycopg://user@host/shop customers churn \\
15
+ --id customer_id --out customers_churn_prediction
16
+
17
+ The API key is read from CAUSILO_API_KEY; calls are billed to it."""
18
+
19
+
20
+ def main(argv: list[str] | None = None) -> int:
21
+ parser = argparse.ArgumentParser(
22
+ prog="causilo-db", description="Predict the blank cells of a database column with the hosted Causilo API.",
23
+ epilog=EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter)
24
+ parser.add_argument("--version", action="version", version=f"causilo-db {__version__}")
25
+ sub = parser.add_subparsers(dest="command", required=True)
26
+ p = sub.add_parser("predict", help="predict the blank cells of a column", epilog=EPILOG,
27
+ formatter_class=argparse.RawDescriptionHelpFormatter)
28
+ p.add_argument("url", help="SQLAlchemy URL, e.g. postgresql+psycopg://user@host/db "
29
+ "(a password here shows in shell history; prefer the driver's password file)")
30
+ p.add_argument("table", help="the table to read (see --schema)")
31
+ p.add_argument("target", help="the column whose blank cells are predicted")
32
+ p.add_argument("--schema", help="the schema of the table")
33
+ p.add_argument("--where", help="SQL condition choosing the rows to read")
34
+ p.add_argument("--id", dest="id_column", help="a column that identifies rows; not used as a feature")
35
+ p.add_argument("--features", help="comma-separated feature columns (default: all others)")
36
+ p.add_argument("--task", choices=["clf", "reg"], help="classification or regression (default: inferred)")
37
+ p.add_argument("--out", dest="out_table", help="write the result to this table")
38
+ p.add_argument("--out-schema", help="the schema of the result table")
39
+ p.add_argument("--if-exists", choices=["fail", "replace", "append"], default="fail",
40
+ help="when the result table exists (default: fail, checked before predicting)")
41
+ args = parser.parse_args(argv)
42
+
43
+ try:
44
+ result, pred = predict_table(
45
+ args.url, args.table, args.target, schema=args.schema, where=args.where,
46
+ id_column=args.id_column, task=args.task,
47
+ features=[f.strip() for f in args.features.split(",") if f.strip()] if args.features else None,
48
+ out_table=args.out_table, out_schema=args.out_schema, if_exists=args.if_exists,
49
+ )
50
+ except CausiloDBError as exc:
51
+ print(f"causilo-db: {exc}", file=sys.stderr)
52
+ saved = getattr(exc, "result", None)
53
+ if saved is not None:
54
+ # Paid for but not written: keep it on stdout rather than lose it.
55
+ saved.to_csv(sys.stdout, index=False)
56
+ print("causilo-db: the predictions were printed to stdout instead", file=sys.stderr)
57
+ return 2
58
+ except ModuleNotFoundError as exc:
59
+ print(f"causilo-db: the driver {exc.name!r} is not installed; install the matching extra, "
60
+ 'e.g. pip install "causilo-db[postgres]", and check the URL prefix', file=sys.stderr)
61
+ return 2
62
+ except Exception as exc: # database and API errors: one line, not a traceback
63
+ first = str(exc).strip().splitlines()[0] if str(exc).strip() else ""
64
+ print(f"causilo-db: {type(exc).__name__}: {first}", file=sys.stderr)
65
+ return 2
66
+ summary = (f"{pred.n_query:,} blank cells of {pred.target} predicted from {pred.n_context:,} rows "
67
+ f"({'regression' if pred.task == 'reg' else 'classification'}, {pred.calls} call(s))")
68
+ print(summary, file=sys.stderr)
69
+ for note in pred.notes:
70
+ print(f"note: {note}", file=sys.stderr)
71
+ if args.out_table:
72
+ print(f"written to {args.out_table}", file=sys.stderr)
73
+ else:
74
+ result.to_csv(sys.stdout, index=False)
75
+ return 0
76
+
77
+
78
+ if __name__ == "__main__":
79
+ raise SystemExit(main())
causilo_db/core.py ADDED
@@ -0,0 +1,356 @@
1
+ """Fill the blank cells of one column of a table with Causilo.
2
+
3
+ Every adapter (SQLAlchemy, PostgreSQL, DuckDB, Snowflake, Spark) reads a table
4
+ into a DataFrame and hands it here. The rows where ``target`` has a value are
5
+ the examples; the rows where it is blank are predicted. Nothing else about the table is
6
+ assumed: no column has to be an id, and the result keeps the input's row order
7
+ through ``row_number``.
8
+
9
+ The call goes to the hosted API with the person's own key; this package keeps
10
+ no key and writes nothing anywhere.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import datetime as _dt
16
+ import decimal
17
+ import os
18
+ import re
19
+ from dataclasses import dataclass, field
20
+ from typing import Any, Callable
21
+
22
+ import numpy as np
23
+ import pandas as pd
24
+
25
+ DEFAULT_ENDPOINT = "https://api.nums.world"
26
+ MODEL_CLF = "causilo-clf"
27
+ MODEL_REG = "causilo-reg"
28
+
29
+ # The API's limit on cells per call; staying under it here turns a 413 into a
30
+ # split. Context beyond 50,000 rows stops helping and is billed.
31
+ MAX_CELLS_PER_CALL = 7_000_000
32
+ MAX_CONTEXT_ROWS = 50_000
33
+ DEFAULT_QUANTILES = (0.25, 0.5, 0.75)
34
+
35
+ # A numeric column with at most this many distinct whole values is read as classes.
36
+ CLASS_LIMIT = 20
37
+
38
+ # A text target with more distinct values than this is more likely a name or a
39
+ # code than a class; refuse it unless task="clf" was asked for.
40
+ MAX_INFERRED_CLASSES = 200
41
+
42
+ # Longest class column name: PostgreSQL keeps 63 bytes and MySQL allows 64;
43
+ # the rest is room for a clash number.
44
+ MAX_NAME = 56
45
+
46
+
47
+ class CausiloDBError(Exception):
48
+ """A table that cannot be predicted as asked. The message says why."""
49
+
50
+
51
+ class PartialPredictionError(CausiloDBError):
52
+ """A prediction failed after one or more of its calls were charged.
53
+
54
+ Either a call failed after earlier calls had completed, or a call was
55
+ answered and its answer could not be used. The charged calls' predictions
56
+ are not returned. The original error is ``__cause__``; ``calls_completed``
57
+ counts the calls that were charged and ``rows_completed`` the rows they
58
+ covered, out of ``calls_planned`` and ``n_query``.
59
+ """
60
+
61
+ def __init__(self, message: str, *, calls_completed: int, calls_planned: int,
62
+ rows_completed: int, n_query: int) -> None:
63
+ super().__init__(message)
64
+ self.calls_completed = calls_completed
65
+ self.calls_planned = calls_planned
66
+ self.rows_completed = rows_completed
67
+ self.n_query = n_query
68
+
69
+
70
+ @dataclass
71
+ class Prediction:
72
+ """The predicted rows, and what was done to get them."""
73
+
74
+ frame: pd.DataFrame
75
+ task: str
76
+ target: str
77
+ features: list[str]
78
+ n_context: int
79
+ n_query: int
80
+ calls: int
81
+ notes: list[str] = field(default_factory=list)
82
+
83
+
84
+ def infer_task(values: pd.Series) -> str:
85
+ """'reg' for a number with many values, 'clf' for anything else."""
86
+ known = values.dropna()
87
+ if known.empty:
88
+ raise CausiloDBError(f"Column {values.name!r} has no values to learn from.")
89
+ if pd.api.types.is_bool_dtype(known):
90
+ return "clf"
91
+ if pd.api.types.is_numeric_dtype(known):
92
+ if known.nunique() > CLASS_LIMIT:
93
+ return "reg"
94
+ if not np.allclose(known.astype("float64"), np.round(known.astype("float64"))):
95
+ return "reg"
96
+ return "clf"
97
+ return "clf"
98
+
99
+
100
+ def _normalize(df: pd.DataFrame) -> pd.DataFrame:
101
+ """Give object columns that hold numbers or dates a real dtype.
102
+
103
+ Drivers hand back DECIMAL and DATE columns, and integer columns with blanks
104
+ after a concat, as Python objects; read as they are, a price would become a
105
+ class label and a date a category.
106
+ """
107
+ out = df.copy()
108
+ for name in out.columns:
109
+ col = out[name]
110
+ if col.dtype != object:
111
+ continue
112
+ known = col.dropna()
113
+ if known.empty:
114
+ continue
115
+ if known.map(lambda v: isinstance(v, (int, float, decimal.Decimal, np.integer, np.floating))
116
+ and not isinstance(v, (bool, np.bool_))).all():
117
+ out[name] = pd.to_numeric(col, errors="coerce").astype("float64")
118
+ elif known.map(lambda v: isinstance(v, (_dt.date, _dt.datetime, pd.Timestamp))).all():
119
+ out[name] = pd.to_datetime(col, errors="coerce", utc=True)
120
+ return out
121
+
122
+
123
+ def _usable(df: pd.DataFrame, target: str, features: list[str] | None, exclude: list[str]) -> tuple[pd.DataFrame, list[str], list[str]]:
124
+ """The feature columns the API can take, converted, and notes on what was dropped."""
125
+ notes: list[str] = []
126
+ if isinstance(features, str):
127
+ features = [features]
128
+ if features is None:
129
+ features = [c for c in df.columns if c != target and c not in exclude]
130
+ features = list(dict.fromkeys(c for c in features if c != target and c not in exclude))
131
+ missing = [c for c in features if c not in df.columns]
132
+ if missing:
133
+ raise CausiloDBError(f"No such columns: {', '.join(missing)}.")
134
+ cols: dict[str, pd.Series] = {}
135
+ for name in features:
136
+ col = df[name]
137
+ if pd.api.types.is_datetime64_any_dtype(col):
138
+ # The API refuses datetimes; seconds since the epoch keep the order.
139
+ col = pd.to_datetime(col, utc=True)
140
+ col = (col - pd.Timestamp("1970-01-01", tz="UTC")).dt.total_seconds()
141
+ notes.append(f"{name}: dates sent as seconds since 1970-01-01")
142
+ elif not (pd.api.types.is_numeric_dtype(col) or pd.api.types.is_bool_dtype(col)):
143
+ col = col.map(lambda v: None if v is None or (pd.api.types.is_scalar(v) and pd.isna(v)) else str(v))
144
+ if col.isna().all():
145
+ notes.append(f"{name}: dropped, every value is blank")
146
+ continue
147
+ cols[name] = col
148
+ if not cols:
149
+ raise CausiloDBError("No feature columns are left to predict from.")
150
+ # One concat rather than a column at a time: a wide table stays one block.
151
+ return pd.concat(cols, axis=1), list(cols), notes
152
+
153
+
154
+ def _class_columns(target: str, classes: list[str]) -> list[str]:
155
+ """``<target>_prob_<class>`` names that every database accepts.
156
+
157
+ Class labels can hold spaces, commas or anything else, and databases fold
158
+ case, so "A" and "a" would land on one column; letters, digits and "_" are
159
+ kept, the rest becomes "_", and a clash gets a number.
160
+ """
161
+ names: list[str] = []
162
+ seen: set[str] = set()
163
+ for c in classes:
164
+ base = (f"{target}_prob_" + (re.sub(r"[^0-9A-Za-z_]", "_", str(c)) or "_"))[:MAX_NAME]
165
+ name, k = base, 2
166
+ while name.lower() in seen:
167
+ name, k = f"{base}_{k}", k + 1
168
+ seen.add(name.lower())
169
+ names.append(name)
170
+ return names
171
+
172
+
173
+ def is_result_name(name: str, target: str) -> bool:
174
+ """Whether ``name`` is, or folds to, a column the result adds (``row_number``, ``<target>_p50`` ...)."""
175
+ low = str(name).lower()
176
+ return low == "row_number" or re.fullmatch(
177
+ rf"{re.escape(str(target).lower())}_(p\d+|probability|prob_.*)", low) is not None
178
+
179
+
180
+ def check_id_column(id_column: str | None, target: str) -> None:
181
+ """Refuse an id column that would clash with a result column, before anything is paid for."""
182
+ if id_column is None:
183
+ return
184
+ if str(id_column).lower() == str(target).lower():
185
+ raise CausiloDBError("The id column cannot be the target column.")
186
+ if is_result_name(id_column, target):
187
+ raise CausiloDBError(f"An id column named {id_column!r} clashes with a result column; use another one.")
188
+
189
+
190
+ def _label(v: Any) -> str:
191
+ if isinstance(v, (float, np.floating)) and float(v).is_integer():
192
+ return str(int(v))
193
+ if isinstance(v, (np.integer,)):
194
+ return str(int(v))
195
+ return str(v)
196
+
197
+
198
+ def predict_frame(
199
+ df: pd.DataFrame,
200
+ target: str,
201
+ *,
202
+ api_key: str | None = None,
203
+ endpoint: str | None = None,
204
+ features: list[str] | None = None,
205
+ exclude: list[str] | None = None,
206
+ task: str | None = None,
207
+ quantiles: tuple[float, ...] = DEFAULT_QUANTILES,
208
+ client: Any = None,
209
+ progress: Callable[[int, int], None] | None = None,
210
+ ) -> Prediction:
211
+ """Predict the blank cells of ``target`` from the rows where it is filled.
212
+
213
+ Returns one row per blank cell: ``row_number`` (0-based position in
214
+ ``df``), the predicted ``target``, and for a regression one column per
215
+ quantile (``target_p25`` ...), for a classification ``target_probability``
216
+ and one ``target_prob_<class>`` column per class.
217
+
218
+ ``exclude`` names columns that are not features, an id for example.
219
+ ``api_key`` defaults to the ``CAUSILO_API_KEY`` environment variable.
220
+
221
+ A large table is sent in several calls, each charged. If a call fails
222
+ after one or more have completed, or an answer comes back that cannot be
223
+ used, :class:`PartialPredictionError` is raised from the original error and
224
+ says how many calls were charged; a failure of the first call before the
225
+ API answers raises the original error.
226
+ """
227
+ if target not in df.columns:
228
+ raise CausiloDBError(f"No column named {target!r}.")
229
+ df = _normalize(df.reset_index(drop=True))
230
+ exclude = list(exclude or [])
231
+ if str(target).lower() == "row_number":
232
+ raise CausiloDBError("A target named 'row_number' clashes with the result's row_number column; rename it.")
233
+ if len(set(round(q * 100) for q in quantiles)) != len(quantiles) or not all(0 < q < 1 for q in quantiles):
234
+ raise CausiloDBError("quantiles must be distinct whole percentiles between 0 and 1, e.g. (0.1, 0.5, 0.9).")
235
+ blank = df[target].isna().to_numpy()
236
+ query_rows = np.flatnonzero(blank)
237
+ context_rows = np.flatnonzero(~blank)
238
+ if len(query_rows) == 0:
239
+ raise CausiloDBError(f"Column {target!r} has no blank cells, so there is nothing to predict.")
240
+ if len(context_rows) < 2:
241
+ raise CausiloDBError(f"Column {target!r} has {len(context_rows)} filled rows; at least 2 are needed.")
242
+
243
+ asked = task
244
+ task = task or infer_task(df[target])
245
+ if task not in ("clf", "reg"):
246
+ raise CausiloDBError("task must be 'clf' or 'reg'.")
247
+ X, feats, notes = _usable(df, target, features, exclude)
248
+ known = df[target].iloc[context_rows]
249
+ if task == "clf":
250
+ n_classes = known.nunique()
251
+ if asked is None and n_classes > MAX_INFERRED_CLASSES:
252
+ raise CausiloDBError(f"Column {target!r} has {n_classes:,} distinct values, which looks more like a name "
253
+ "or a code than a class; pass task='clf' if it really is one.")
254
+ if asked is None and pd.api.types.is_numeric_dtype(known) and not pd.api.types.is_bool_dtype(known):
255
+ notes.append(f"{target}: whole numbers with {n_classes} distinct values, read as classes; "
256
+ "pass task='reg' if it is a quantity")
257
+ elif not pd.api.types.is_numeric_dtype(known):
258
+ try:
259
+ known.astype("float64")
260
+ except (TypeError, ValueError) as exc:
261
+ raise CausiloDBError(f"Column {target!r} is not numeric; task='reg' needs numbers.") from exc
262
+
263
+ n_cols = len(feats) + 1
264
+ budget_rows = MAX_CELLS_PER_CALL // n_cols
265
+ # Every call carries the context and is billed for it, so a wide table must
266
+ # not be answered a few hundred rows per call: the context gets at most half
267
+ # of a call, unless the rows to predict fit in what is left anyway.
268
+ keep = min(MAX_CONTEXT_ROWS, max(budget_rows // 2, budget_rows - len(query_rows)))
269
+ if len(context_rows) > keep:
270
+ rng = np.random.default_rng(0)
271
+ notes.append(f"context sampled from {len(context_rows):,} to {keep:,} rows")
272
+ context_rows = np.sort(rng.choice(context_rows, size=keep, replace=False))
273
+ chunk = max(min(budget_rows - len(context_rows), len(query_rows)), 1)
274
+
275
+ if client is None:
276
+ import causilo_client
277
+
278
+ key = api_key or os.environ.get("CAUSILO_API_KEY", "")
279
+ if not key:
280
+ raise CausiloDBError("A Causilo API key is needed: pass api_key or set CAUSILO_API_KEY.")
281
+ client = causilo_client.Causilo(endpoint or os.environ.get("CAUSILO_ENDPOINT", DEFAULT_ENDPOINT), token=key)
282
+
283
+ y = df[target]
284
+ context = X.iloc[context_rows].reset_index(drop=True)
285
+ if task == "clf":
286
+ labels = {_label(v): (v.item() if hasattr(v, "item") else v) for v in y.iloc[context_rows].dropna().unique()}
287
+ answers = y.iloc[context_rows].map(_label).to_numpy()
288
+ else:
289
+ answers = y.iloc[context_rows].astype("float64").to_numpy()
290
+ context = pd.concat([context, pd.Series(answers, name=target)], axis=1)
291
+
292
+ parts: list[np.ndarray] = []
293
+ classes: list[str] = []
294
+ calls = 0
295
+ planned = -(-len(query_rows) // chunk)
296
+ for start in range(0, len(query_rows), chunk):
297
+ rows = query_rows[start:start + chunk]
298
+ query = X.iloc[rows].reset_index(drop=True)
299
+ if progress:
300
+ progress(start, len(query_rows))
301
+ try:
302
+ if task == "clf":
303
+ pred, meta = client.predict_with_metadata(context, query, target=target, model=MODEL_CLF)
304
+ else:
305
+ pred, meta = client.predict_with_metadata(context, query, target=target, model=MODEL_REG,
306
+ output_type="quantiles", quantiles=list(quantiles))
307
+ except Exception as exc:
308
+ if calls == 0:
309
+ raise
310
+ # The calls before this one were charged; say so rather than let a
311
+ # retry of the whole table look free.
312
+ raise PartialPredictionError(
313
+ f"Call {calls + 1} of {planned} failed ({type(exc).__name__}: {exc}). "
314
+ f"The {calls} call{'s' if calls != 1 else ''} before it completed and "
315
+ f"{'were' if calls != 1 else 'was'} charged ({start:,} of {len(query_rows):,} rows); "
316
+ "those predictions are not returned.",
317
+ calls_completed=calls, calls_planned=planned, rows_completed=start, n_query=len(query_rows),
318
+ ) from exc
319
+ # The API answered, so this call was charged whatever happens next.
320
+ calls += 1
321
+ try:
322
+ if task == "clf":
323
+ got = [str(c) for c in meta.get("classes", [])]
324
+ if classes and got != classes:
325
+ raise CausiloDBError("The class order changed between calls; run again with fewer rows.")
326
+ classes = classes or got
327
+ m = np.asarray(pred, dtype="float64")
328
+ if m.ndim == 1:
329
+ m = m.reshape(len(rows), -1)
330
+ except Exception as exc:
331
+ done = start + len(rows)
332
+ raise PartialPredictionError(
333
+ f"Call {calls} of {planned} was answered, but the answer could not be used "
334
+ f"({type(exc).__name__}: {exc}). The {calls} call{'s' if calls != 1 else ''} up to and "
335
+ f"including it {'were' if calls != 1 else 'was'} charged ({done:,} of {len(query_rows):,} rows); "
336
+ "no predictions are returned.",
337
+ calls_completed=calls, calls_planned=planned, rows_completed=done, n_query=len(query_rows),
338
+ ) from exc
339
+ parts.append(m)
340
+ matrix = np.vstack(parts)
341
+
342
+ out = pd.DataFrame({"row_number": query_rows.astype("int64")})
343
+ if task == "reg":
344
+ qs = list(quantiles)
345
+ median = matrix[:, qs.index(0.5)] if 0.5 in qs else matrix.mean(axis=1)
346
+ out[target] = median
347
+ for i, q in enumerate(qs):
348
+ out[f"{target}_p{round(q * 100):g}"] = matrix[:, i]
349
+ else:
350
+ best = matrix.argmax(axis=1)
351
+ out[target] = [labels.get(classes[j], classes[j]) for j in best]
352
+ out[f"{target}_probability"] = matrix[np.arange(len(best)), best]
353
+ for j, name in enumerate(_class_columns(target, classes)):
354
+ out[name] = matrix[:, j]
355
+ return Prediction(frame=out, task=task, target=target, features=feats,
356
+ n_context=len(context_rows), n_query=len(query_rows), calls=calls, notes=notes)
causilo_db/duckdb.py ADDED
@@ -0,0 +1,36 @@
1
+ """DuckDB: predict from a table or a query, get a DuckDB relation back.
2
+
3
+ import duckdb, causilo_db.duckdb as cx
4
+ con = duckdb.connect("shop.duckdb")
5
+ rel = cx.predict(con, "customers", "churn", id_column="customer_id")
6
+ rel.create("customers_churn_prediction") # or rel.df(), or query it:
7
+ con.sql("SELECT * FROM rel WHERE churn_probability > 0.8")
8
+
9
+ ``source`` is a table name (``schema.table`` works) or any SELECT.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from typing import Any
16
+
17
+ from .core import CausiloDBError, Prediction, check_id_column, predict_frame
18
+
19
+
20
+ def predict(con: Any, source: str, target: str, *, id_column: str | None = None,
21
+ features: list[str] | None = None, task: str | None = None,
22
+ api_key: str | None = None, endpoint: str | None = None, client: Any = None) -> Any:
23
+ """The predicted rows as a DuckDB relation."""
24
+ # A query starts with a keyword followed by a space; "selected_rows" is a table.
25
+ is_query = re.match(r"\s*\(?\s*(select|with|from)\s", source, re.IGNORECASE) is not None
26
+ check_id_column(id_column, target)
27
+ df = (con.sql(source) if is_query else con.table(source)).df()
28
+ if id_column is not None and id_column not in df.columns:
29
+ raise CausiloDBError(f"No column named {id_column!r}.")
30
+ pred: Prediction = predict_frame(df, target, features=features, exclude=[id_column] if id_column else None,
31
+ task=task, api_key=api_key, endpoint=endpoint, client=client)
32
+ result = pred.frame.copy()
33
+ if id_column is not None:
34
+ result.insert(0, id_column, df[id_column].reset_index(drop=True).iloc[result["row_number"]].to_numpy())
35
+ result = result.drop(columns=["row_number"])
36
+ return con.from_df(result)
causilo_db/spark.py ADDED
@@ -0,0 +1,126 @@
1
+ """Spark and Databricks: predict the blank cells of a column of a Spark DataFrame.
2
+
3
+ from causilo_db.spark import predict, predict_table
4
+ out = predict(spark.table("main.sales.customers"), "churn", id_column="customer_id")
5
+ predict_table(spark, "main.sales.customers", "churn", id_column="customer_id",
6
+ output_table="main.sales.customers_churn_prediction")
7
+
8
+ Only what the API needs reaches the driver: the rows to predict, and a sample of
9
+ at most 50,000 filled rows drawn inside Spark. The table itself stays where it is.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Any
15
+
16
+ import pandas as pd
17
+
18
+ from .core import MAX_CONTEXT_ROWS, CausiloDBError, check_id_column, is_result_name, predict_frame
19
+
20
+ # Rows to predict that are pulled to the driver in one go. Above this, filter
21
+ # the DataFrame first (or raise it, if the driver has the memory).
22
+ MAX_QUERY_ROWS = 1_000_000
23
+
24
+
25
+ def _blank(sdf: Any, column: str) -> Any:
26
+ from pyspark.sql import functions as F
27
+ from pyspark.sql.types import DoubleType, FloatType
28
+
29
+ col = F.col(f"`{column}`")
30
+ cond = col.isNull()
31
+ if isinstance(sdf.schema[column].dataType, (DoubleType, FloatType)):
32
+ cond = cond | F.isnan(col)
33
+ return cond
34
+
35
+
36
+ def predict(sdf: Any, target: str, *, id_column: str | None = None, features: list[str] | None = None,
37
+ task: str | None = None, api_key: str | None = None, endpoint: str | None = None,
38
+ client: Any = None, seed: int = 0, max_query_rows: int = MAX_QUERY_ROWS) -> Any:
39
+ """Predict the rows of ``sdf`` whose ``target`` is blank; returns a Spark DataFrame.
40
+
41
+ With ``id_column`` the result is that column plus the prediction columns, ready
42
+ to join back. Without it, the result is the blank rows as they are, with the
43
+ prediction columns filled in after them.
44
+ """
45
+ check_id_column(id_column, target)
46
+ names = list(sdf.columns)
47
+ for name in [target] + ([id_column] if id_column else []) + list(features or []):
48
+ if name not in names:
49
+ raise CausiloDBError(f"No column named {name!r}.")
50
+ if features is not None:
51
+ keep = [c for c in names if c in features or c == target or c == id_column]
52
+ sdf = sdf.select(*[f"`{c}`" for c in keep])
53
+ if id_column is None:
54
+ # The result keeps the source columns, so a result name must not be one.
55
+ clash = [c for c in sdf.columns if is_result_name(c, target)]
56
+ if clash:
57
+ raise CausiloDBError(f"Column {clash[0]!r} clashes with a result column; pass id_column instead.")
58
+
59
+ blank = _blank(sdf, target)
60
+ query = sdf.filter(blank)
61
+ filled = sdf.filter(~blank)
62
+
63
+ n_query = query.count()
64
+ if n_query == 0:
65
+ raise CausiloDBError(f"{target!r} has no blank cells to predict.")
66
+ if n_query > max_query_rows:
67
+ raise CausiloDBError(
68
+ f"{n_query:,} rows to predict is more than max_query_rows={max_query_rows:,}; "
69
+ "filter the DataFrame first, or raise the limit."
70
+ )
71
+ n_filled = filled.count()
72
+ if n_filled == 0:
73
+ raise CausiloDBError(f"{target!r} has no filled cells to learn from.")
74
+ notes: list[str] = []
75
+ if n_filled > MAX_CONTEXT_ROWS:
76
+ # Oversample a little in Spark, then cut to size on the driver at random:
77
+ # .limit() would keep the first partitions and drop the tail.
78
+ fraction = min(1.0, MAX_CONTEXT_ROWS * 1.1 / n_filled)
79
+ filled = filled.sample(withReplacement=False, fraction=fraction, seed=seed)
80
+ notes.append(f"context sampled in Spark from {n_filled:,} rows")
81
+
82
+ context_pd = filled.toPandas()
83
+ if len(context_pd) > MAX_CONTEXT_ROWS:
84
+ context_pd = context_pd.sample(n=MAX_CONTEXT_ROWS, random_state=seed)
85
+ query_pd = query.toPandas()
86
+ df = pd.concat([context_pd, query_pd], ignore_index=True)
87
+
88
+ pred = predict_frame(df, target, features=None, exclude=[id_column] if id_column else None,
89
+ task=task, api_key=api_key, endpoint=endpoint, client=client)
90
+ result = pred.frame
91
+ rows = df.iloc[result["row_number"].to_numpy()].reset_index(drop=True)
92
+ predicted = result.drop(columns=["row_number"]).reset_index(drop=True)
93
+ if id_column is not None:
94
+ out = pd.concat([rows[[id_column]], predicted], axis=1)
95
+ else:
96
+ # The blank rows in their own column order, the target filled in where
97
+ # it was, and the extra prediction columns after.
98
+ out = rows.copy()
99
+ out[target] = predicted[target].to_numpy()
100
+ out = pd.concat([out, predicted.drop(columns=[target])], axis=1)
101
+ # Spark cannot infer a type for a column that is blank in every row.
102
+ for name in out.columns:
103
+ if out[name].isna().all() and out[name].dtype == object:
104
+ out[name] = out[name].astype("string")
105
+ spark = sdf.sparkSession
106
+ return spark.createDataFrame(out)
107
+
108
+
109
+ def predict_table(spark: Any, table: str, target: str, *, output_table: str | None = None,
110
+ mode: str = "error", **kwargs: Any) -> Any:
111
+ """Predict a table by name; with ``output_table``, also save the result there.
112
+
113
+ ``mode`` is Spark's save mode: ``error`` (the default, as with the other
114
+ adapters) refuses an existing table before anything is predicted;
115
+ ``overwrite`` and ``append`` do what they say.
116
+ """
117
+ if mode not in ("error", "errorifexists", "overwrite", "append"):
118
+ raise CausiloDBError(f"mode must be 'error', 'overwrite' or 'append', not {mode!r}.")
119
+ if output_table and output_table == table:
120
+ raise CausiloDBError("output_table is the table being read; write the result to another table.")
121
+ if output_table and mode in ("error", "errorifexists") and spark.catalog.tableExists(output_table):
122
+ raise CausiloDBError(f"Table {output_table} already exists; pass mode='overwrite' or 'append'.")
123
+ out = predict(spark.table(table), target, **kwargs)
124
+ if output_table:
125
+ out.write.mode(mode).saveAsTable(output_table)
126
+ return out