corrlens 0.1.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.
corrlens/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ """corrlens - automated, assumption-aware correlation and association analysis.
2
+
3
+ >>> import corrlens
4
+ >>> schema = corrlens.detect(df) # infer semantic types
5
+ >>> schema.review() # see what needs confirming
6
+ >>> schema.set("zip", "categorical").drop("customer_id").confirm()
7
+ >>> clean_df = corrlens.convert(df, schema) # typed copy of your data
8
+ >>> report = corrlens.analyze(df, schema) # missing="pairwise" | "listwise" | "impute"
9
+ >>> print(report.summary()); report.findings; report.plot(); report.to_html("report.html")
10
+ """
11
+
12
+ from .api import analyze
13
+ from .convert import convert
14
+ from .detect import ColumnInfo, Schema, detect
15
+ from .report import Report
16
+
17
+ __all__ = ["analyze", "convert", "detect", "Schema", "ColumnInfo", "Report"]
18
+ __version__ = "0.1.0"
corrlens/api.py ADDED
@@ -0,0 +1,118 @@
1
+ from __future__ import annotations
2
+
3
+ import warnings
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+
8
+ from .detect import NUMERIC, ORDINAL, Schema, _as_frame, detect, prepare
9
+ from .report import Report
10
+ from .stats import run_all
11
+
12
+ MISSING_MODES = ("pairwise", "listwise", "impute")
13
+
14
+
15
+ def handle_missing(data: pd.DataFrame, types: dict[str, str], missing: str = "pairwise",
16
+ min_rows: int = 30) -> tuple[pd.DataFrame, list[str], str]:
17
+ """Apply a missing-value strategy to prepared data.
18
+
19
+ Returns (data, notes, strategy actually used).
20
+
21
+ * ``pairwise`` - leave missing values; each pair uses rows where both values exist.
22
+ * ``listwise`` - drop every row with any missing value. If fewer than ``min_rows``
23
+ remain, fall back to ``pairwise`` (never silently impute).
24
+ * ``impute`` - fill numeric with the median, ordinal with the (rounded) median,
25
+ categorical/binary with the mode. Correlations are biased toward zero and
26
+ p-values are overconfident; the report says so.
27
+ """
28
+ if missing not in MISSING_MODES:
29
+ raise ValueError(f"missing must be one of {MISSING_MODES}")
30
+ notes: list[str] = []
31
+ n_missing = int(data.isna().any(axis=1).sum())
32
+ if missing == "pairwise" or n_missing == 0:
33
+ if n_missing:
34
+ notes.append(f"missing values: pairwise deletion ({n_missing:,} of {len(data):,} rows have at least "
35
+ "one gap; each pair uses its own complete rows - see n per pair)")
36
+ return data, notes, "pairwise"
37
+ if missing == "listwise":
38
+ kept = data.dropna()
39
+ if len(kept) < min_rows:
40
+ notes.append(f"missing values: listwise deletion would leave only {len(kept):,} of {len(data):,} rows "
41
+ f"(< {min_rows}); fell back to pairwise deletion. Use missing='impute' to fill "
42
+ "values instead, or drop the emptiest columns.")
43
+ worst = data.isna().mean().sort_values(ascending=False).head(3)
44
+ notes.append("emptiest columns: " + ", ".join(f"{c} ({v:.0%} missing)" for c, v in worst.items()))
45
+ return data, notes, "pairwise"
46
+ notes.append(f"missing values: listwise deletion dropped {len(data) - len(kept):,} rows; "
47
+ f"{len(kept):,} complete rows used for every test")
48
+ return kept, notes, "listwise"
49
+ # impute
50
+ filled = data.copy()
51
+ parts = []
52
+ for col in data.columns:
53
+ k = int(data[col].isna().sum())
54
+ if not k:
55
+ continue
56
+ t = types[col]
57
+ if t == NUMERIC:
58
+ val = data[col].median()
59
+ how = f"median {val:.4g}"
60
+ elif t == ORDINAL:
61
+ val = float(np.round(data[col].median()))
62
+ how = "median level"
63
+ else:
64
+ val = data[col].mode(dropna=True).iloc[0]
65
+ how = f"mode '{val}'"
66
+ filled[col] = data[col].fillna(val)
67
+ parts.append(f"{col}: {k:,} ({k / len(data):.0%}) with {how}")
68
+ notes.append("missing values IMPUTED - " + "; ".join(parts))
69
+ notes.append("imputation shrinks correlations toward zero and makes p-values overconfident; "
70
+ "compare with the default missing='pairwise' before trusting borderline results")
71
+ return filled, notes, "impute"
72
+
73
+
74
+ def analyze(data, schema: Schema | None = None, *, missing: str = "pairwise", alpha: float = 0.05,
75
+ correction: str = "fdr_bh", max_rows: int | None = 500_000, random_state: int = 0,
76
+ max_levels: int = 50, min_level_count: int = 5, min_rows: int = 30,
77
+ interactive: bool = False, columns: list[str] | None = None) -> Report:
78
+ """Detect types (or use ``schema``), run pairwise tests, return a :class:`Report`.
79
+
80
+ Parameters
81
+ ----------
82
+ data : DataFrame, or anything with ``to_pandas()`` (astropy Table, polars, pyarrow)
83
+ schema : a reviewed :class:`Schema`. If omitted, types are detected automatically
84
+ and a warning lists columns whose types should be confirmed.
85
+ missing : 'pairwise' (default), 'listwise' (drop incomplete rows; falls back to
86
+ pairwise if fewer than ``min_rows`` remain) or 'impute' (median / mode).
87
+ alpha : significance level applied to corrected p-values.
88
+ correction : 'fdr_bh' (Benjamini-Hochberg, default), 'bonferroni' or 'none'.
89
+ max_rows : rows are randomly sampled down to this many before testing (None = all).
90
+ interactive : prompt in the console for each flagged column.
91
+ columns : restrict analysis to these columns.
92
+ """
93
+ df = _as_frame(data)
94
+ if columns is not None:
95
+ df = df[columns]
96
+ if schema is None:
97
+ schema = detect(df)
98
+ if interactive:
99
+ schema.interactive_review()
100
+ elif schema.flagged:
101
+ warnings.warn(
102
+ f"corrlens: {len(schema.flagged)} column type(s) need review: {schema.flagged}. "
103
+ "Run `schema = corrlens.detect(df); schema.review()`, fix with schema.set()/drop()/confirm(), "
104
+ "then `corrlens.analyze(df, schema)`.", UserWarning, stacklevel=2)
105
+ source = df
106
+ n_rows = len(df)
107
+ notes = []
108
+ if max_rows is not None and n_rows > max_rows:
109
+ df = df.sample(max_rows, random_state=random_state)
110
+ notes.append(f"randomly sampled {max_rows:,} of {n_rows:,} rows (random_state={random_state})")
111
+ prepared, prep_notes = prepare(df, schema, max_levels=max_levels, min_level_count=min_level_count)
112
+ notes += prep_notes
113
+ types = {c: schema[c].semantic for c in prepared.columns}
114
+ prepared, miss_notes, used = handle_missing(prepared, types, missing, min_rows)
115
+ notes += miss_notes
116
+ results = run_all(prepared, types, alpha=alpha, correction=correction)
117
+ return Report(results, schema, alpha, correction, n_rows, len(df), notes,
118
+ missing=used, missing_requested=missing, _source=source)
corrlens/cli.py ADDED
@@ -0,0 +1,81 @@
1
+ """Command line: ``corrlens data.csv --out report.html``"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ import pandas as pd
9
+
10
+ from . import analyze, convert, detect
11
+ from .detect import Schema
12
+
13
+
14
+ def _read(path: str) -> pd.DataFrame:
15
+ p = path.lower()
16
+ if p.endswith((".parquet", ".pq")):
17
+ try:
18
+ return pd.read_parquet(path)
19
+ except ImportError:
20
+ sys.exit("Reading Parquet needs pyarrow: pip install corrlens[parquet]")
21
+ if p.endswith((".xlsx", ".xls")):
22
+ return pd.read_excel(path)
23
+ if p.endswith((".fits", ".fit", ".fits.gz")):
24
+ try:
25
+ from astropy.table import Table
26
+ except ImportError:
27
+ sys.exit("Reading FITS needs astropy: pip install corrlens[astro]")
28
+ t = Table.read(path)
29
+ t = t[[c for c in t.colnames if t[c].ndim == 1]] # drop multidimensional columns
30
+ return t.to_pandas()
31
+ if p.endswith((".tsv", ".tab")):
32
+ return pd.read_csv(path, sep="\t")
33
+ return pd.read_csv(path)
34
+
35
+
36
+ def main(argv=None):
37
+ ap = argparse.ArgumentParser(prog="corrlens", description="Automated correlation/association analysis")
38
+ ap.add_argument("path", help="CSV, TSV, Parquet, Excel or FITS file")
39
+ ap.add_argument("--out", default="corrlens_report.html", help="HTML report path")
40
+ ap.add_argument("--csv", help="also write the findings table to this CSV")
41
+ ap.add_argument("--schema", help="JSON schema to use (from a previous --save-schema)")
42
+ ap.add_argument("--save-schema", help="write detected schema JSON here and stop, so you can edit it")
43
+ ap.add_argument("--interactive", action="store_true", help="confirm flagged column types at the prompt")
44
+ ap.add_argument("--alpha", type=float, default=0.05)
45
+ ap.add_argument("--correction", default="fdr_bh", choices=["fdr_bh", "bonferroni", "none"])
46
+ ap.add_argument("--max-rows", type=int, default=500_000)
47
+ ap.add_argument("--missing", default="pairwise", choices=["pairwise", "listwise", "impute"],
48
+ help="missing-value strategy for the tests (default: pairwise)")
49
+ ap.add_argument("--clean-out", help="write the type-converted data here (.csv or .parquet)")
50
+ a = ap.parse_args(argv)
51
+
52
+ df = _read(a.path)
53
+ if a.save_schema:
54
+ s = detect(df)
55
+ s.to_json(a.save_schema)
56
+ print(s.review().to_string(index=False))
57
+ print(f"\nSchema written to {a.save_schema}. Edit 'semantic' values, then rerun with --schema.")
58
+ return
59
+ schema = Schema.from_json(a.schema) if a.schema else None
60
+ rep = analyze(df, schema, missing=a.missing, alpha=a.alpha, correction=a.correction,
61
+ max_rows=a.max_rows, interactive=a.interactive)
62
+ if a.clean_out:
63
+ clean = rep.clean_df
64
+ if a.clean_out.lower().endswith((".parquet", ".pq")):
65
+ try:
66
+ clean.to_parquet(a.clean_out)
67
+ except ImportError:
68
+ sys.exit("Writing Parquet needs pyarrow: pip install corrlens[parquet] "
69
+ "(or use a .csv path for --clean-out)")
70
+ else:
71
+ clean.to_csv(a.clean_out, index=False)
72
+ print(f"Converted data written to {a.clean_out}")
73
+ rep.to_html(a.out)
74
+ if a.csv:
75
+ rep.to_csv(a.csv)
76
+ print(rep.summary())
77
+ print(f"\nReport written to {a.out}")
78
+
79
+
80
+ if __name__ == "__main__":
81
+ main()
corrlens/convert.py ADDED
@@ -0,0 +1,133 @@
1
+ """Turn a DataFrame into one whose pandas dtypes match the (reviewed) semantic types."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+
10
+ from .detect import (BINARY, CATEGORICAL, CONSTANT, DATETIME, EMPTY, IDENTIFIER, NUMERIC, ORDINAL, TEXT,
11
+ Schema, _as_category, _as_frame, _match_col, clean_numeric_text, detect)
12
+
13
+ _TRUE = {"yes", "y", "true", "t", "1", "1.0", "on", "pass", "positive"}
14
+ _FALSE = {"no", "n", "false", "f", "0", "0.0", "off", "fail", "negative"}
15
+
16
+ # pandas dtype each semantic type is converted to
17
+ TARGET_DTYPE = {
18
+ NUMERIC: "float64",
19
+ ORDINAL: "category (ordered)",
20
+ BINARY: "boolean, or category if the two values are not true/false-like",
21
+ CATEGORICAL: "category",
22
+ DATETIME: "datetime64[ns]",
23
+ IDENTIFIER: "string",
24
+ TEXT: "string",
25
+ CONSTANT: "unchanged",
26
+ EMPTY: "unchanged",
27
+ }
28
+
29
+
30
+ def _to_numeric(s: pd.Series, parse: str | None) -> pd.Series:
31
+ if parse == "numeric_text" or not pd.api.types.is_numeric_dtype(s):
32
+ return clean_numeric_text(s)
33
+ return pd.to_numeric(s, errors="coerce").astype("float64")
34
+
35
+
36
+ def _to_binary(s: pd.Series) -> pd.Series:
37
+ if pd.api.types.is_bool_dtype(s):
38
+ return s.astype("boolean")
39
+ labels = _as_category(s)
40
+ low = labels.dropna().astype(str).str.strip().str.lower()
41
+ vals = set(low.unique())
42
+ if vals and vals <= (_TRUE | _FALSE) and vals & _TRUE and vals & _FALSE:
43
+ mapped = labels.astype(str).str.strip().str.lower().map(
44
+ lambda v: True if v in _TRUE else (False if v in _FALSE else pd.NA))
45
+ return mapped.where(labels.notna(), pd.NA).astype("boolean")
46
+ return labels.astype("category")
47
+
48
+
49
+ def _to_ordinal(s: pd.Series, levels: list | None, parse: str | None) -> pd.Series:
50
+ if levels:
51
+ return pd.Series(pd.Categorical(s.astype("string").str.strip(), categories=levels, ordered=True),
52
+ index=s.index)
53
+ if pd.api.types.is_numeric_dtype(s) or parse == "numeric_text":
54
+ num = clean_numeric_text(s) if parse else s.astype("float64")
55
+ cats = sorted(num.dropna().unique())
56
+ if all(float(c).is_integer() for c in cats):
57
+ num = num.astype("Int64")
58
+ cats = [int(c) for c in cats]
59
+ return pd.Series(pd.Categorical(num, categories=cats, ordered=True), index=s.index)
60
+ # text without an order: keep as unordered category
61
+ return _as_category(s).astype("category")
62
+
63
+
64
+ def _to_datetime(s: pd.Series) -> pd.Series:
65
+ if pd.api.types.is_datetime64_any_dtype(s):
66
+ return s
67
+ with warnings.catch_warnings():
68
+ warnings.simplefilter("ignore")
69
+ return pd.to_datetime(s, errors="coerce", format="mixed")
70
+
71
+
72
+ def _to_string(s: pd.Series) -> pd.Series:
73
+ if pd.api.types.is_numeric_dtype(s):
74
+ return _as_category(s).astype("string") # 1234.0 -> "1234"
75
+ return s.astype("string")
76
+
77
+
78
+ def convert(df, schema: Schema | None = None, *, drop_excluded: bool = False,
79
+ report: bool = False):
80
+ """Return a copy of ``df`` with each column converted to the pandas dtype matching its semantic type.
81
+
82
+ Parameters
83
+ ----------
84
+ df : DataFrame, or anything with ``to_pandas()``
85
+ schema : reviewed :class:`Schema`; detected automatically if omitted.
86
+ drop_excluded : drop identifier / datetime / text / constant / empty columns.
87
+ report : also return a DataFrame describing every change.
88
+
89
+ Missing values are kept as missing (NaN / NA / NaT) - nothing is imputed.
90
+ Values that cannot be converted (e.g. "abc" in a numeric column) become missing,
91
+ and the number of such values is shown in the change report.
92
+ """
93
+ src = _as_frame(df)
94
+ schema = schema if schema is not None else detect(src)
95
+ out, changes = {}, []
96
+ for col in src.columns:
97
+ name = str(col)
98
+ c = schema.columns.get(name)
99
+ s = src[col]
100
+ if c is None:
101
+ out[col] = s
102
+ continue
103
+ if drop_excluded and not c.analyzable:
104
+ changes.append((name, str(s.dtype), "(dropped)", c.semantic, 0))
105
+ continue
106
+ if c.semantic == NUMERIC:
107
+ new = _to_numeric(s, c.parse)
108
+ elif c.semantic == ORDINAL:
109
+ new = _to_ordinal(s, c.levels, c.parse)
110
+ elif c.semantic == BINARY:
111
+ new = _to_binary(s)
112
+ elif c.semantic == CATEGORICAL:
113
+ new = s.astype("category") if isinstance(s.dtype, pd.CategoricalDtype) else \
114
+ _as_category(s).astype("category")
115
+ elif c.semantic == DATETIME:
116
+ new = _to_datetime(s)
117
+ elif c.semantic in (IDENTIFIER, TEXT):
118
+ new = _to_string(s)
119
+ else: # constant / empty: leave alone
120
+ new = s
121
+ was_missing = s.isna() | (s.astype("string").str.strip() == "").fillna(False)
122
+ lost = int((new.isna() & ~was_missing).sum())
123
+ out[col] = new
124
+ changes.append((name, str(s.dtype), str(new.dtype), c.semantic, lost))
125
+ result = pd.DataFrame(out, index=src.index)
126
+ if lost_total := sum(ch[4] for ch in changes):
127
+ warnings.warn(f"corrlens.convert: {lost_total} value(s) could not be converted and became missing; "
128
+ "see convert(..., report=True).", UserWarning, stacklevel=2)
129
+ if report:
130
+ rep = pd.DataFrame(changes, columns=["column", "from_dtype", "to_dtype", "semantic_type",
131
+ "values_made_missing"])
132
+ return result, rep
133
+ return result