tomographia 0.1.1__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.
Files changed (54) hide show
  1. tomographia/__init__.py +2 -0
  2. tomographia/_slices.py +57 -0
  3. tomographia/classification/__init__.py +114 -0
  4. tomographia/classification/kmeans.py +92 -0
  5. tomographia/classification/logistic.py +386 -0
  6. tomographia/classification/patch_training.py +202 -0
  7. tomographia/classification/resnet2d.py +73 -0
  8. tomographia/components/__init__.py +24 -0
  9. tomographia/components/pipeline1.py +105 -0
  10. tomographia/components/pipeline2.py +341 -0
  11. tomographia/evaluation/__init__.py +37 -0
  12. tomographia/evaluation/calibration.py +144 -0
  13. tomographia/evaluation/metrics.py +177 -0
  14. tomographia/labelling/__init__.py +35 -0
  15. tomographia/labelling/app.py +89 -0
  16. tomographia/labelling/cli.py +71 -0
  17. tomographia/labelling/config.py +31 -0
  18. tomographia/labelling/io.py +32 -0
  19. tomographia/labelling/model_assist.py +53 -0
  20. tomographia/labelling/preprocess.py +14 -0
  21. tomographia/labelling/selection.py +44 -0
  22. tomographia/labelling/session.py +105 -0
  23. tomographia/labelling/visualize.py +41 -0
  24. tomographia/models/__init__.py +5 -0
  25. tomographia/models/unet.py +110 -0
  26. tomographia/models/utils.py +50 -0
  27. tomographia/patches/__init__.py +31 -0
  28. tomographia/patches/dataset.py +306 -0
  29. tomographia/prototypes/__init__.py +47 -0
  30. tomographia/prototypes/anchors.py +179 -0
  31. tomographia/prototypes/diagnostics.py +145 -0
  32. tomographia/prototypes/losses.py +178 -0
  33. tomographia/prototypes/model.py +226 -0
  34. tomographia/prototypes/plotting.py +103 -0
  35. tomographia/prototypes/training.py +227 -0
  36. tomographia/reporting/__init__.py +5 -0
  37. tomographia/reporting/pdf_report.py +180 -0
  38. tomographia/reporting/yield_report.py +133 -0
  39. tomographia/segmentation/__init__.py +37 -0
  40. tomographia/segmentation/_dataset.py +173 -0
  41. tomographia/segmentation/_io.py +178 -0
  42. tomographia/segmentation/_synthetic.py +71 -0
  43. tomographia/segmentation/_training_data.py +271 -0
  44. tomographia/segmentation/inference.py +276 -0
  45. tomographia/segmentation/training.py +853 -0
  46. tomographia/slice_inference/__init__.py +43 -0
  47. tomographia/slice_inference/predict.py +154 -0
  48. tomographia/slice_inference/volume.py +93 -0
  49. tomographia-0.1.1.dist-info/METADATA +881 -0
  50. tomographia-0.1.1.dist-info/RECORD +54 -0
  51. tomographia-0.1.1.dist-info/WHEEL +5 -0
  52. tomographia-0.1.1.dist-info/entry_points.txt +3 -0
  53. tomographia-0.1.1.dist-info/licenses/LICENSE +29 -0
  54. tomographia-0.1.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2 @@
1
+ """tomographia — open-source toolbox for defect analysis in X-ray computed tomography."""
2
+ __version__ = "0.1.1"
tomographia/_slices.py ADDED
@@ -0,0 +1,57 @@
1
+ """Slice-file discovery shared by every module that reads a stack of slices.
2
+
3
+ All readers order slices the same way (natural order: ``slice_2`` before
4
+ ``slice_10``) so that index ``z`` refers to the same image everywhere.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import re
10
+ from typing import List, Sequence
11
+
12
+ TIF_EXTENSIONS = (".tif", ".tiff")
13
+
14
+
15
+ def natural_key(name: str):
16
+ """Sort key that orders ``slice_2`` before ``slice_10`` (case-insensitive)."""
17
+ return [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", os.fspath(name))]
18
+
19
+
20
+ def list_slices(directory: str, extensions: Sequence[str] = TIF_EXTENSIONS) -> List[str]:
21
+ """Full paths of the slice images in *directory*, in natural order.
22
+
23
+ Hidden files are skipped; the extension match is case-insensitive.
24
+ """
25
+ exts = tuple(e.lower() for e in extensions)
26
+ names = [f for f in os.listdir(directory)
27
+ if not f.startswith(".") and f.lower().endswith(exts)]
28
+ return [os.path.join(directory, f) for f in sorted(names, key=natural_key)]
29
+
30
+
31
+ def read_slice(path: str):
32
+ """Read one slice image as a numpy array (any TIFF byte order or bit depth).
33
+
34
+ TIFFs are read with ``tifffile``; other formats (and TIFFs needing a codec
35
+ that is not installed) fall back to Pillow.
36
+ """
37
+ import numpy as np
38
+
39
+ if path.lower().endswith(TIF_EXTENSIONS):
40
+ import tifffile
41
+ try:
42
+ return np.asarray(tifffile.imread(path))
43
+ except ValueError as exc:
44
+ if "imagecodecs" not in str(exc):
45
+ raise
46
+ from PIL import Image
47
+ with Image.open(path) as im:
48
+ return np.array(im)
49
+
50
+
51
+ def read_volume(paths: Sequence[str]):
52
+ """Stack slice images into a ``(Z, Y, X)`` array."""
53
+ import numpy as np
54
+
55
+ if not paths:
56
+ raise FileNotFoundError("No slice images to read")
57
+ return np.stack([read_slice(p) for p in paths], axis=0)
@@ -0,0 +1,114 @@
1
+ """Defect classification: logistic regression and KMeans (3-D descriptors), ResNet (2-D patches).
2
+
3
+ Quick-start
4
+ -----------
5
+ Logistic (sklearn bundle)::
6
+
7
+ from tomographia.classification import classify_defects
8
+ df = classify_defects(df, method="logistic", bundle="path/to/bundle.joblib")
9
+
10
+ KMeans (unsupervised)::
11
+
12
+ df = classify_defects(df, method="kmeans", n_clusters=4)
13
+
14
+ 2-D patch classification (ResNet, requires the ``vision`` extra)::
15
+
16
+ from tomographia.classification import ResNetPatchClassifier, PatchClassifierTrainer
17
+ model = ResNetPatchClassifier("resnet50", pretrained=True)
18
+ result = PatchClassifierTrainer(model).fit(train_loader, val_loader)
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import importlib
23
+
24
+ import pandas as pd
25
+
26
+ from .logistic import classify_defects_logistic, build_classified_volume, fit_classifier
27
+ from .kmeans import cluster_defects, make_cluster_volume
28
+
29
+ # torch-based members are imported lazily so that the logistic / KMeans path
30
+ # works with the core dependencies only (torch is an optional extra).
31
+ _LAZY = {
32
+ "ARCHITECTURES": "resnet2d",
33
+ "ResNetPatchClassifier": "resnet2d",
34
+ "PatchClassifierTrainer": "patch_training",
35
+ "PatchTrainConfig": "patch_training",
36
+ "PatchTrainResult": "patch_training",
37
+ "predict_logits": "patch_training",
38
+ "predict_proba": "patch_training",
39
+ }
40
+
41
+
42
+ def __getattr__(name: str):
43
+ if name in _LAZY:
44
+ try:
45
+ module = importlib.import_module(f".{_LAZY[name]}", __name__)
46
+ except ImportError as exc:
47
+ raise ImportError(
48
+ f"tomographia.classification.{name} requires torch "
49
+ "and torchvision: pip install 'tomographia[vision]'"
50
+ ) from exc
51
+ value = getattr(module, name)
52
+ globals()[name] = value
53
+ return value
54
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
55
+
56
+
57
+ def __dir__():
58
+ return sorted(set(globals()) | set(_LAZY))
59
+
60
+
61
+ __all__ = [
62
+ "classify_defects",
63
+ "classify_defects_logistic",
64
+ "build_classified_volume",
65
+ "fit_classifier",
66
+ "cluster_defects",
67
+ "make_cluster_volume",
68
+ # 2-D patch classification
69
+ "ResNetPatchClassifier",
70
+ "ARCHITECTURES",
71
+ "PatchClassifierTrainer",
72
+ "PatchTrainConfig",
73
+ "PatchTrainResult",
74
+ "predict_logits",
75
+ "predict_proba",
76
+ ]
77
+
78
+
79
+ def classify_defects(
80
+ df: pd.DataFrame,
81
+ method: str = "logistic",
82
+ bundle=None,
83
+ **kwargs,
84
+ ) -> pd.DataFrame:
85
+ """
86
+ Classify defects using the specified *method*.
87
+
88
+ Parameters
89
+ ----------
90
+ df : descriptor DataFrame from
91
+ ``tomographia.components.compute_descriptors``.
92
+ method : ``"logistic"`` (sklearn bundle) or ``"kmeans"`` (unsupervised).
93
+ bundle : joblib bundle dict / path — required for ``method="logistic"``.
94
+ **kwargs: forwarded verbatim to the underlying function.
95
+
96
+ Returns
97
+ -------
98
+ Copy of *df* with classification columns added.
99
+
100
+ See Also
101
+ --------
102
+ :func:`classify_defects_logistic` — full logistic-path signature.
103
+ :func:`cluster_defects` — full KMeans-path signature.
104
+ """
105
+ if method == "logistic":
106
+ if bundle is None:
107
+ raise ValueError("bundle= is required for method='logistic'")
108
+ return classify_defects_logistic(df, bundle, **kwargs)
109
+ if method == "kmeans":
110
+ result, _, _ = cluster_defects(df, **kwargs)
111
+ return result
112
+ raise ValueError(
113
+ f"Unknown method {method!r}. Choose 'logistic' or 'kmeans'."
114
+ )
@@ -0,0 +1,92 @@
1
+ """KMeans-based unsupervised defect clustering."""
2
+ from __future__ import annotations
3
+
4
+ from typing import List, Optional
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ from sklearn.cluster import KMeans
9
+ from sklearn.preprocessing import StandardScaler
10
+
11
+
12
+ def cluster_defects(
13
+ df: pd.DataFrame,
14
+ features: Optional[List[str]] = None,
15
+ n_clusters: int = 4,
16
+ random_state: int = 42,
17
+ ) -> tuple:
18
+ """
19
+ KMeans clustering of standardised descriptor *features*.
20
+
21
+ Rows with NaN / ±Inf in any feature column are excluded from clustering;
22
+ their ``cluster`` value is NaN in the returned DataFrame.
23
+
24
+ Parameters
25
+ ----------
26
+ df : descriptor DataFrame (output of ``compute_descriptors``).
27
+ features : columns to cluster on; default: the shape features of
28
+ :data:`tomographia.components.CANONICAL_FEATURES`
29
+ (without ``int_std_rel``).
30
+ n_clusters : number of KMeans clusters.
31
+ random_state: RNG seed for reproducibility.
32
+
33
+ Returns
34
+ -------
35
+ (df_with_cluster_col, fitted_KMeans, fitted_StandardScaler)
36
+ """
37
+ if features is None:
38
+ from ..components.pipeline2 import CANONICAL_FEATURES
39
+ features = [f for f in CANONICAL_FEATURES if f != "int_std_rel"]
40
+ missing = [f for f in features if f not in df.columns]
41
+ if missing:
42
+ raise KeyError(f"Missing feature columns {missing}")
43
+ X = df[features].copy().replace([np.inf, -np.inf], np.nan)
44
+ valid = X.notna().all(axis=1)
45
+ X_clean = X.loc[valid]
46
+ if len(X_clean) < n_clusters:
47
+ raise ValueError(f"{len(X_clean)} complete rows for {n_clusters} clusters")
48
+
49
+ scaler = StandardScaler()
50
+ X_scaled = scaler.fit_transform(X_clean)
51
+
52
+ km = KMeans(n_clusters=n_clusters, random_state=random_state, n_init=10)
53
+ cluster_labels = km.fit_predict(X_scaled)
54
+
55
+ col = np.full(len(df), np.nan)
56
+ col[valid.to_numpy()] = cluster_labels.astype(float)
57
+ df = df.copy()
58
+ df["cluster"] = col
59
+ return df, km, scaler
60
+
61
+
62
+ def make_cluster_volume(
63
+ cc: np.ndarray,
64
+ df: pd.DataFrame,
65
+ out_dtype=np.int16,
66
+ ) -> np.ndarray:
67
+ """
68
+ Build a 3-D volume where each voxel holds its cluster id + 1.
69
+
70
+ Encoding: 0 = background, 1..K = cluster ids.
71
+
72
+ Parameters
73
+ ----------
74
+ cc : integer CC label array (e.g. from ``build_cc_mask``).
75
+ df : DataFrame with ``label_id`` and ``cluster`` columns.
76
+ out_dtype: NumPy dtype for the output volume.
77
+ """
78
+ lv = cc.astype(np.int64, copy=False)
79
+ if not lv.flags["C_CONTIGUOUS"]:
80
+ lv = np.ascontiguousarray(lv)
81
+
82
+ valid = df["cluster"].notna()
83
+ keys = df.loc[valid, "label_id"].to_numpy(dtype=np.int64)
84
+ vals = df.loc[valid, "cluster"].to_numpy(dtype=np.int64)
85
+
86
+ if keys.size == 0:
87
+ return np.zeros_like(lv, dtype=out_dtype)
88
+
89
+ lut = np.zeros(int(lv.max()) + 1, dtype=out_dtype)
90
+ ok = (keys > 0) & (keys < len(lut))
91
+ lut[keys[ok]] = (vals[ok] + 1).astype(out_dtype)
92
+ return np.take(lut, lv, mode="clip")
@@ -0,0 +1,386 @@
1
+ """
2
+ Logistic-regression classification of defects (pore vs. crack) from the
3
+ descriptors of :func:`tomographia.components.compute_descriptors`.
4
+
5
+ Bundle format
6
+ -------------
7
+ Produced by :func:`fit_classifier`::
8
+
9
+ {
10
+ "model" : sklearn Pipeline (median imputer → StandardScaler →
11
+ LogisticRegression) with ``predict_proba``,
12
+ "features" : list[str], # feature columns, in order
13
+ "threshold" : float, # P(crack) threshold, F1-optimal on
14
+ # out-of-fold training predictions
15
+ "holdout" : "random" | "volume",
16
+ "holdout_results": dict, # metrics on the held-out split
17
+ "volumes" : list[str], # descriptor tables used for training
18
+ "test_volumes" : list[str], # tables in the held-out split
19
+ "feature_range" : {feature: (p1, p99)} on the training split,
20
+ "nan_counts" : {feature: {volume: n_missing}},
21
+ "n_train", "n_test": int,
22
+ "tomographia_version": str,
23
+ }
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import logging
28
+ from pathlib import Path
29
+ from typing import List, Optional, Sequence, Union
30
+
31
+ import numpy as np
32
+ import pandas as pd
33
+
34
+ from .. import __version__
35
+ from ..components.pipeline2 import CANONICAL_FEATURES
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+ #: Label strings accepted in the training tables, and their class index.
40
+ LABELS = {"pore": 0, "crack": 1}
41
+
42
+
43
+ def _load_bundle(bundle_or_path) -> dict:
44
+ """Accept a dict, a path to a .joblib file, or a directory containing exactly one."""
45
+ if isinstance(bundle_or_path, dict):
46
+ return bundle_or_path
47
+ import joblib
48
+ p = Path(bundle_or_path)
49
+ if p.is_dir():
50
+ hits = sorted(p.glob("*.joblib"))
51
+ if len(hits) != 1:
52
+ raise FileNotFoundError(f"Expected exactly one .joblib file in {p}, found {len(hits)}")
53
+ p = hits[0]
54
+ return joblib.load(str(p))
55
+
56
+
57
+ def _feature_matrix(df: pd.DataFrame, features: Sequence[str]) -> np.ndarray:
58
+ """Feature matrix with ±inf turned into NaN (NaN is imputed by the model)."""
59
+ missing = [f for f in features if f not in df.columns]
60
+ if missing:
61
+ raise KeyError(f"Descriptor table lacks the model features {missing}; compute them with "
62
+ "compute_descriptors (int_std_rel needs grayscale_volume=)")
63
+ X = np.array(df[list(features)].to_numpy(dtype=float), copy=True)
64
+ X[~np.isfinite(X)] = np.nan
65
+ return X
66
+
67
+
68
+ def classify_defects_logistic(
69
+ df: pd.DataFrame,
70
+ bundle: Union[dict, str, Path],
71
+ threshold: Optional[float] = None,
72
+ ) -> pd.DataFrame:
73
+ """
74
+ Classify defects with a bundle from :func:`fit_classifier`.
75
+
76
+ Parameters
77
+ ----------
78
+ df : descriptor DataFrame (output of ``compute_descriptors``).
79
+ bundle : bundle dict, path to a ``.joblib`` file, or a directory
80
+ containing exactly one ``.joblib`` file.
81
+ threshold : override the bundle's threshold.
82
+
83
+ Returns
84
+ -------
85
+ Copy of *df* with ``cls_proba`` (P(crack)), ``cls_pred`` (0 = pore,
86
+ 1 = crack) and ``cls_label`` (``"pore"`` / ``"crack"``).
87
+
88
+ Raises
89
+ ------
90
+ KeyError : a feature used by the model is missing from *df*.
91
+
92
+ Missing (NaN / inf) feature values are replaced by the training median;
93
+ a warning gives their number.
94
+ """
95
+ b = _load_bundle(bundle)
96
+ if "scaler" in b:
97
+ raise ValueError("This bundle was produced by an incompatible version; retrain it "
98
+ "with fit_classifier")
99
+ features = b["features"]
100
+ thr = float(b["threshold"] if threshold is None else threshold)
101
+
102
+ X = _feature_matrix(df, features)
103
+ absent = [f for f, ok in zip(features, np.isfinite(X).any(axis=0)) if not ok and len(X)]
104
+ if absent:
105
+ raise ValueError(f"Model features with no value in the table: {absent} (e.g. "
106
+ "int_std_rel needs compute_descriptors(grayscale_volume=...))")
107
+ n_nan = int(np.isnan(X).any(axis=1).sum())
108
+ if n_nan:
109
+ logger.warning("%d / %d components have missing feature values (imputed with the "
110
+ "training median)", n_nan, len(X))
111
+ out = df.copy()
112
+ if len(X) == 0:
113
+ out["cls_proba"] = pd.Series(dtype=float)
114
+ out["cls_pred"] = pd.Series(dtype=int)
115
+ out["cls_label"] = pd.Series(dtype=object)
116
+ return out
117
+ rng = b.get("feature_range", {})
118
+ for j, f in enumerate(features):
119
+ if f in rng:
120
+ lo, hi = rng[f]
121
+ span = max(hi - lo, 1e-6 * max(abs(lo), abs(hi), 1.0))
122
+ col = X[:, j][~np.isnan(X[:, j])]
123
+ out_frac = float(np.mean((col < lo - span) | (col > hi + span))) if col.size else 0.0
124
+ if out_frac > 0.25:
125
+ logger.warning("%s: %.0f%% of the values lie far outside the training range "
126
+ "[%.3g, %.3g]; check units and preprocessing", f,
127
+ 100 * out_frac, lo, hi)
128
+ proba = b["model"].predict_proba(X)[:, 1]
129
+ pred = (proba >= thr).astype(int)
130
+ out["cls_proba"] = proba
131
+ out["cls_pred"] = pred
132
+ out["cls_label"] = np.where(pred == 1, "crack", "pore")
133
+ return out
134
+
135
+
136
+ def build_classified_volume(
137
+ cc_vol: np.ndarray,
138
+ df: pd.DataFrame,
139
+ label_col: str = "label_id",
140
+ ) -> np.ndarray:
141
+ """
142
+ ``uint8`` volume with 0 = background, 1 = pore, 2 = crack.
143
+
144
+ Parameters
145
+ ----------
146
+ cc_vol : integer label array (e.g. from ``build_cc_mask``).
147
+ df : DataFrame with ``cls_pred`` (0/1) and *label_col* columns.
148
+ Components absent from *df* are written as background.
149
+ label_col : column of *df* holding the component label.
150
+ """
151
+ max_label = int(cc_vol.max()) if cc_vol.size else 0
152
+ lut = np.zeros(max_label + 1, dtype=np.uint8)
153
+ if len(df):
154
+ ids = df[label_col].to_numpy(dtype=np.int64)
155
+ codes = np.where(df["cls_pred"].to_numpy(dtype=int) == 1, 2, 1).astype(np.uint8)
156
+ ok = (ids > 0) & (ids <= max_label)
157
+ lut[ids[ok]] = codes[ok]
158
+ return np.take(lut, cc_vol, mode="clip")
159
+
160
+
161
+ # ---------------------------------------------------------------------------
162
+ # Training
163
+ # ---------------------------------------------------------------------------
164
+
165
+ def _optimal_f1_threshold(y_true: np.ndarray, y_score: np.ndarray) -> float:
166
+ """F1-optimal threshold (predict crack when ``score >= threshold``)."""
167
+ from ..evaluation.metrics import f1_optimal_threshold
168
+ return f1_optimal_threshold(y_true, y_score)
169
+
170
+
171
+ def _eval_metrics(y_true: np.ndarray, y_pred: np.ndarray, y_proba: np.ndarray) -> dict:
172
+ from sklearn.metrics import (
173
+ accuracy_score, f1_score, precision_score, recall_score, roc_auc_score,
174
+ )
175
+ both = len(np.unique(y_true)) == 2
176
+ has_crack, has_pore = bool((y_true == 1).any()), bool((y_true == 0).any())
177
+ nan = float("nan")
178
+ if not both:
179
+ logger.warning("The held-out split holds a single class: class-specific metrics of the "
180
+ "missing class and ROC-AUC are undefined (NaN)")
181
+ return {
182
+ "accuracy": float(accuracy_score(y_true, y_pred)),
183
+ "f1_pore": float(f1_score(y_true, y_pred, pos_label=0, zero_division=0)) if has_pore else nan,
184
+ "f1_crack": float(f1_score(y_true, y_pred, pos_label=1, zero_division=0)) if has_crack else nan,
185
+ "f1_macro": float(f1_score(y_true, y_pred, average="macro", zero_division=0)) if both else nan,
186
+ "precision_crack": float(precision_score(y_true, y_pred, pos_label=1, zero_division=0)),
187
+ "recall_crack": float(recall_score(y_true, y_pred, pos_label=1, zero_division=0)) if has_crack else nan,
188
+ "roc_auc": float(roc_auc_score(y_true, y_proba)) if both else nan,
189
+ "n_pore": int((y_true == 0).sum()),
190
+ "n_crack": int((y_true == 1).sum()),
191
+ }
192
+
193
+
194
+ def _parse_labels(series: pd.Series) -> np.ndarray:
195
+ """Map ``"pore"`` / ``"crack"`` (case-insensitive) to 0 / 1; NaN stays NaN."""
196
+ s = series.astype("string").str.strip().str.lower()
197
+ unknown = sorted(set(s.dropna()) - set(LABELS))
198
+ if unknown:
199
+ raise ValueError(f"Unknown labels {unknown}; expected {sorted(LABELS)} (or empty for "
200
+ "unlabelled rows)")
201
+ return s.map(LABELS).to_numpy(dtype=float)
202
+
203
+
204
+ def _make_model(max_iter: int, random_state: int):
205
+ from sklearn.impute import SimpleImputer
206
+ from sklearn.linear_model import LogisticRegression
207
+ from sklearn.pipeline import make_pipeline
208
+ from sklearn.preprocessing import StandardScaler
209
+
210
+ return make_pipeline(
211
+ SimpleImputer(strategy="median"),
212
+ StandardScaler(),
213
+ LogisticRegression(class_weight="balanced", max_iter=max_iter,
214
+ random_state=random_state),
215
+ )
216
+
217
+
218
+ def fit_classifier(
219
+ descriptors: Sequence[Union[str, Path, pd.DataFrame]],
220
+ label_col: str = "label",
221
+ features: Optional[List[str]] = None,
222
+ test_size: float = 0.2,
223
+ holdout: str = "random",
224
+ max_iter: int = 1000,
225
+ random_state: int = 42,
226
+ save_path: Optional[Union[str, Path]] = None,
227
+ ) -> dict:
228
+ """
229
+ Train a logistic-regression pore / crack classifier and return a bundle.
230
+
231
+ Parameters
232
+ ----------
233
+ descriptors : one descriptor table per volume (CSV path or DataFrame from
234
+ ``compute_descriptors``), with a *label_col* column holding
235
+ the expert labels ``"pore"`` / ``"crack"``. Rows with an
236
+ empty label are ignored. Descriptors are in mm, so volumes
237
+ scanned at different voxel sizes can be pooled.
238
+ label_col : column of expert labels. Must not be ``cls_label``, which
239
+ :func:`classify_defects_logistic` writes (training on it
240
+ would train on model predictions).
241
+ features : feature columns; default
242
+ :data:`tomographia.components.CANONICAL_FEATURES`. Every
243
+ feature must be present; a feature with no finite value
244
+ raises.
245
+ test_size : fraction held out for evaluation.
246
+ holdout : ``"random"``: stratified split of the components;
247
+ ``"volume"``: whole volumes are held out (needs ≥ 2
248
+ volumes), which measures generalisation to new specimens.
249
+ The threshold folds then also keep volumes apart. A
250
+ single held-out split of few volumes is a noisy estimate.
251
+ max_iter : ``LogisticRegression(max_iter=)``.
252
+ random_state: RNG seed.
253
+ save_path : if given, the bundle is written with ``joblib.dump``.
254
+
255
+ Returns
256
+ -------
257
+ Bundle dict (see the module docstring).
258
+
259
+ Notes
260
+ -----
261
+ The model is a median imputer, a standard scaler and a class-balanced
262
+ logistic regression, all fitted on the training split only. The
263
+ decision threshold maximises F1 on 5-fold **out-of-fold** predictions of
264
+ the training split (folds grouped by volume when ``holdout="volume"``);
265
+ the held-out split is used only for the reported metrics. Missing
266
+ values are counted per feature and volume (``nan_counts``): a feature
267
+ missing for a whole volume is imputed with the median and can act as a
268
+ volume marker.
269
+ """
270
+ from sklearn.model_selection import (
271
+ GroupShuffleSplit, StratifiedGroupKFold, StratifiedKFold, cross_val_predict,
272
+ train_test_split,
273
+ )
274
+
275
+ features = list(CANONICAL_FEATURES if features is None else features)
276
+ if holdout not in ("random", "volume"):
277
+ raise ValueError("holdout must be 'random' or 'volume'")
278
+
279
+ tables, names = [], []
280
+ for i, d in enumerate(descriptors):
281
+ if isinstance(d, pd.DataFrame):
282
+ tables.append(d.assign(_volume=i))
283
+ names.append(f"<DataFrame {i}>")
284
+ else:
285
+ tables.append(pd.read_csv(d).assign(_volume=i))
286
+ names.append(str(d))
287
+ if not tables:
288
+ raise ValueError("descriptors is empty")
289
+ all_df = pd.concat(tables, ignore_index=True)
290
+ if label_col in ("cls_label", "cls_pred") and "cls_proba" in all_df.columns:
291
+ raise ValueError(f"{label_col!r} holds model predictions (the table was classified); "
292
+ "pass the column with the expert labels")
293
+ if label_col not in all_df.columns:
294
+ raise KeyError(f"Label column {label_col!r} not found; columns: {list(all_df.columns)}")
295
+
296
+ y = _parse_labels(all_df[label_col])
297
+ keep = ~np.isnan(y)
298
+ if (~keep).any():
299
+ logger.info("Ignoring %d unlabelled rows", int((~keep).sum()))
300
+ all_df, y = all_df.loc[keep].reset_index(drop=True), y[keep].astype(int)
301
+ if len(np.unique(y)) < 2:
302
+ raise ValueError("Training data must contain both 'pore' and 'crack' labels")
303
+
304
+ X = _feature_matrix(all_df, features)
305
+ empty = [f for f, ok in zip(features, np.isfinite(X).any(axis=0)) if not ok]
306
+ if empty:
307
+ raise ValueError(f"Features with no finite value: {empty}")
308
+ nan_counts = {}
309
+ for j, f in enumerate(features):
310
+ per_vol = {names[v]: int(n) for v, n in
311
+ pd.Series(np.isnan(X[:, j])).groupby(all_df["_volume"].to_numpy()).sum().items()
312
+ if n}
313
+ if per_vol:
314
+ nan_counts[f] = per_vol
315
+ logger.warning("%s: missing values imputed with the training median %s", f, per_vol)
316
+
317
+ if holdout == "volume":
318
+ groups = all_df["_volume"].to_numpy()
319
+ if len(np.unique(groups)) < 2:
320
+ raise ValueError("holdout='volume' needs at least two descriptor tables")
321
+ # Draw volume splits until both classes are present in train and test
322
+ # (pore-only specimens are common).
323
+ splitter = GroupShuffleSplit(n_splits=200, test_size=test_size, random_state=random_state)
324
+ splits = list(splitter.split(X, y, groups))
325
+ tr, te = next(((a, b) for a, b in splits
326
+ if len(np.unique(y[a])) == 2 and len(np.unique(y[b])) == 2), splits[0])
327
+ frac = len(np.unique(groups[te])) / len(np.unique(groups))
328
+ if abs(frac - test_size) > 0.15:
329
+ logger.warning("holdout='volume': %d of %d volumes held out (test_size=%.2f is a "
330
+ "fraction of volumes, rounded up)", len(np.unique(groups[te])),
331
+ len(np.unique(groups)), test_size)
332
+ else:
333
+ tr, te = train_test_split(np.arange(len(y)), test_size=test_size, stratify=y,
334
+ random_state=random_state)
335
+ if len(np.unique(y[tr])) < 2:
336
+ raise ValueError("The training split holds a single class")
337
+
338
+ model = _make_model(max_iter, random_state)
339
+ n_folds = int(min(5, np.bincount(y[tr]).min()))
340
+ groups_tr = all_df["_volume"].to_numpy()[tr]
341
+ if holdout == "volume":
342
+ n_folds = min(n_folds, len(np.unique(groups_tr)))
343
+ if holdout == "volume":
344
+ # Fewer folds until every training fold holds both classes
345
+ while n_folds >= 2:
346
+ cv = StratifiedGroupKFold(n_splits=n_folds, shuffle=True, random_state=random_state)
347
+ if all(len(np.unique(y[tr][a])) == 2 for a, _ in cv.split(X[tr], y[tr], groups_tr)):
348
+ break
349
+ n_folds -= 1
350
+ if n_folds >= 2:
351
+ if holdout == "volume":
352
+ oof = cross_val_predict(model, X[tr], y[tr], groups=groups_tr, cv=cv,
353
+ method="predict_proba")[:, 1]
354
+ else:
355
+ cv = StratifiedKFold(n_splits=n_folds, shuffle=True, random_state=random_state)
356
+ oof = cross_val_predict(model, X[tr], y[tr], cv=cv, method="predict_proba")[:, 1]
357
+ else:
358
+ logger.warning("Too few training samples (or volumes) for cross-validation; the "
359
+ "threshold is selected on in-sample predictions")
360
+ oof = model.fit(X[tr], y[tr]).predict_proba(X[tr])[:, 1]
361
+ threshold = _optimal_f1_threshold(y[tr], oof)
362
+
363
+ model.fit(X[tr], y[tr])
364
+ test_proba = model.predict_proba(X[te])[:, 1]
365
+ holdout_results = _eval_metrics(y[te], (test_proba >= threshold).astype(int), test_proba)
366
+
367
+ bundle = {
368
+ "model": model,
369
+ "features": features,
370
+ "threshold": float(threshold),
371
+ "holdout": holdout,
372
+ "holdout_results": holdout_results,
373
+ "volumes": names,
374
+ "test_volumes": sorted({names[v] for v in all_df["_volume"].to_numpy()[te]}),
375
+ "feature_range": {f: (float(np.nanpercentile(X[tr, j], 1)),
376
+ float(np.nanpercentile(X[tr, j], 99)))
377
+ for j, f in enumerate(features)},
378
+ "nan_counts": nan_counts,
379
+ "n_train": int(len(tr)),
380
+ "n_test": int(len(te)),
381
+ "tomographia_version": __version__,
382
+ }
383
+ if save_path is not None:
384
+ import joblib
385
+ joblib.dump(bundle, str(save_path))
386
+ return bundle