mosaic-harmonize 0.1.0__tar.gz

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.
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Peigen Chen
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1,245 @@
1
+ Metadata-Version: 2.4
2
+ Name: mosaic-harmonize
3
+ Version: 0.1.0
4
+ Summary: Multi-site Optimal-transport Shift Alignment with Interval Calibration for clinical data harmonization
5
+ Author-email: Peigen Chen <chenpg5@mail.sysu.edu.cn>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/chenpg2/mosaic-harmonize
8
+ Project-URL: Repository, https://github.com/chenpg2/mosaic-harmonize
9
+ Project-URL: Documentation, https://github.com/chenpg2/mosaic-harmonize#readme
10
+ Project-URL: Bug Tracker, https://github.com/chenpg2/mosaic-harmonize/issues
11
+ Keywords: harmonization,optimal-transport,conformal-prediction,multi-center,clinical-data,batch-effect,domain-adaptation
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Intended Audience :: Healthcare Industry
15
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Operating System :: OS Independent
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: numpy>=1.24
27
+ Requires-Dist: pandas>=2.0
28
+ Requires-Dist: scipy>=1.10
29
+ Requires-Dist: scikit-learn>=1.3
30
+ Provides-Extra: boosting
31
+ Requires-Dist: lightgbm>=4.0; extra == "boosting"
32
+ Requires-Dist: anchorboosting>=0.3; extra == "boosting"
33
+ Provides-Extra: conformal
34
+ Requires-Dist: mapie>=1.0; extra == "conformal"
35
+ Provides-Extra: viz
36
+ Requires-Dist: matplotlib>=3.7; extra == "viz"
37
+ Requires-Dist: seaborn>=0.12; extra == "viz"
38
+ Provides-Extra: full
39
+ Requires-Dist: mosaic-harmonize[boosting,conformal,viz]; extra == "full"
40
+ Provides-Extra: dev
41
+ Requires-Dist: pytest>=7.0; extra == "dev"
42
+ Requires-Dist: pytest-cov; extra == "dev"
43
+ Requires-Dist: mosaic-harmonize[full]; extra == "dev"
44
+ Dynamic: license-file
45
+
46
+ # MOSAIC
47
+
48
+ **Multi-site Optimal-transport Shift Alignment with Interval Calibration**
49
+
50
+ [![PyPI](https://img.shields.io/pypi/v/mosaic-harmonize)](https://pypi.org/project/mosaic-harmonize/)
51
+ [![Python](https://img.shields.io/pypi/pyversions/mosaic-harmonize)](https://pypi.org/project/mosaic-harmonize/)
52
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue)](LICENSE)
53
+ <!-- [![DOI](https://img.shields.io/badge/DOI-10.1038%2Fs41746--XXX-blue)](https://doi.org/10.1038/s41746-XXX) -->
54
+
55
+ MOSAIC is a Python package for harmonizing clinical tabular data collected across multiple sites. It combines 1-D optimal transport for distribution alignment, anchor regression for domain-robust prediction, and weighted conformal inference for uncertainty quantification. The three components can be used independently or chained through a single pipeline.
56
+
57
+ The package was developed for multi-center IVF (in vitro fertilization) outcome prediction, but the methods are general and apply to any multi-site clinical or biomedical dataset with batch effects.
58
+
59
+ ## Overview
60
+
61
+ MOSAIC has three tiers, each usable on its own:
62
+
63
+ | Tier | Class | What it does |
64
+ |------|-------|-------------|
65
+ | 1. Harmonization | `OTHarmonizer` | Per-feature quantile-based optimal transport mapping to a reference distribution. Reduces cross-center distribution shift while preserving within-center rank order. |
66
+ | 2. Robust learning | `AnchorEstimator` | Wraps any sklearn estimator with anchor regression (via [anchorboosting](https://github.com/mlondschien/anchorboosting)) or V-REx reweighting. Penalizes predictions that rely on center-specific patterns. |
67
+ | 3. Uncertainty | `ConformalCalibrator` | Split conformal prediction with optional covariate-shift correction (Tibshirani et al., NeurIPS 2019). Produces prediction intervals (regression) or prediction sets (classification) with finite-sample coverage guarantees. |
68
+
69
+ `MOSAICPipeline` chains all three into a single `fit` / `predict` interface.
70
+
71
+ ## Installation
72
+
73
+ Core (OT harmonization + anchor regression + conformal):
74
+
75
+ ```bash
76
+ pip install mosaic-harmonize
77
+ ```
78
+
79
+ With all optional dependencies (LightGBM, anchorboosting, MAPIE, matplotlib):
80
+
81
+ ```bash
82
+ pip install mosaic-harmonize[full]
83
+ ```
84
+
85
+ Individual extras: `boosting`, `conformal`, `viz`. For development: `dev`.
86
+
87
+ Requires Python 3.9+.
88
+
89
+ ## Quick start
90
+
91
+ ### Full pipeline
92
+
93
+ ```python
94
+ from mosaic import MOSAICPipeline
95
+ from lightgbm import LGBMRegressor
96
+
97
+ pipe = MOSAICPipeline(
98
+ harmonizer="ot",
99
+ robust_learner="anchor",
100
+ uncertainty="weighted_conformal",
101
+ base_estimator=LGBMRegressor(),
102
+ )
103
+
104
+ # center_ids: array of site labels, one per row
105
+ pipe.fit(X_train, y_train, center_ids=train_centers)
106
+
107
+ result = pipe.predict(X_test, center_id="new_hospital")
108
+ print(result.prediction) # point predictions
109
+ print(result.lower, result.upper) # 90% prediction intervals
110
+ ```
111
+
112
+ ### Individual components
113
+
114
+ ```python
115
+ from mosaic import OTHarmonizer, AnchorEstimator, ConformalCalibrator
116
+
117
+ # Tier 1: align distributions
118
+ ot = OTHarmonizer(n_quantiles=1000, reference="global")
119
+ X_harmonized = ot.fit_transform(X_train, center_ids=train_centers)
120
+
121
+ # Inspect shift reduction
122
+ print(ot.wasserstein_distances())
123
+ print(ot.feature_shift_report())
124
+
125
+ # Tier 2: train a domain-robust model
126
+ anchor = AnchorEstimator(base_estimator=LGBMRegressor(), task_type="regression")
127
+ anchor.fit(X_harmonized, y_train, anchors=train_centers)
128
+ print(f"Best gamma: {anchor.best_gamma_}")
129
+ print(f"Cross-center stability: {anchor.stability_score_:.3f}")
130
+
131
+ # Tier 3: calibrate with conformal prediction
132
+ cal = ConformalCalibrator(method="weighted", alpha=0.10)
133
+ cal.calibrate(anchor, X_cal, y_cal, X_test=X_test)
134
+ result = cal.predict(X_test)
135
+ print(f"Interval widths: {(result.upper - result.lower).mean():.2f}")
136
+ ```
137
+
138
+ ### Save and load
139
+
140
+ ```python
141
+ pipe.save("model.mosaic")
142
+ pipe = MOSAICPipeline.load("model.mosaic")
143
+ ```
144
+
145
+ ### Register a new center at inference time
146
+
147
+ ```python
148
+ pipe.register_center("hospital_B", X_new_center)
149
+ result = pipe.predict(X_query, center_id="hospital_B")
150
+ ```
151
+
152
+ ## API reference
153
+
154
+ ### OTHarmonizer
155
+
156
+ | Parameter | Type | Default | Description |
157
+ |-----------|------|---------|-------------|
158
+ | `n_quantiles` | int | 1000 | Number of quantile points for the OT map |
159
+ | `features` | list[str] or None | None | Columns to harmonize (None = all numeric) |
160
+ | `reference` | str | "global" | Reference distribution: "global" or a center name |
161
+ | `min_samples` | int | 50 | Minimum non-null samples to build a map |
162
+
163
+ Methods: `fit(X, center_ids)`, `transform(X, center_id=..., center_ids=...)`, `fit_transform(X, center_ids)`, `wasserstein_distances()`, `feature_shift_report()`.
164
+
165
+ ### AnchorEstimator
166
+
167
+ | Parameter | Type | Default | Description |
168
+ |-----------|------|---------|-------------|
169
+ | `base_estimator` | sklearn estimator or None | None | Base learner (None = Ridge/LogisticRegression) |
170
+ | `gammas` | list[float] or None | [1.5, 3.0, 7.0] | Anchor penalty strengths to search |
171
+ | `task_type` | str | "auto" | "auto", "regression", "binary", or "multiclass" |
172
+ | `n_vrex_rounds` | int | 5 | V-REx reweighting iterations (fallback mode) |
173
+
174
+ Methods: `fit(X, y, anchors, X_val=None, y_val=None)`, `predict(X)`, `predict_proba(X)`. Properties: `best_gamma_`, `stability_score_`.
175
+
176
+ ### ConformalCalibrator
177
+
178
+ | Parameter | Type | Default | Description |
179
+ |-----------|------|---------|-------------|
180
+ | `method` | str | "weighted" | "weighted", "standard", or "lac" |
181
+ | `alpha` | float | 0.10 | Miscoverage level (0.10 = 90% target coverage) |
182
+
183
+ Methods: `calibrate(model, X_cal, y_cal, X_test=None)`, `predict(X_test)` returning `ConformalResult`.
184
+
185
+ ### MOSAICPipeline
186
+
187
+ | Parameter | Type | Default | Description |
188
+ |-----------|------|---------|-------------|
189
+ | `harmonizer` | str or None | "ot" | "ot" or None |
190
+ | `robust_learner` | str or None | "anchor" | "anchor" or None |
191
+ | `uncertainty` | str or None | "weighted_conformal" | "weighted_conformal", "standard", "lac", or None |
192
+ | `base_estimator` | sklearn estimator | None | Base learner passed to AnchorEstimator |
193
+
194
+ Methods: `fit(X_train, y_train, center_ids, X_cal=None, y_cal=None)`, `predict(X, center_id=..., center_ids=...)`, `register_center(name, X_new)`, `diagnose(X, center_id)`, `save(path)`, `load(path)`.
195
+
196
+ ## Benchmarks
197
+
198
+ Evaluated on a multi-center IVF dataset (334K rows, 5 centers, 15 prediction targets). Full results in `benchmarks/results/`.
199
+
200
+ ### Ablation (Exp 1): each tier adds value
201
+
202
+ | Target | Baseline R² | +OT | +OT+Anchor | Full MOSAIC |
203
+ |--------|------------|-----|------------|-------------|
204
+ | HCG_Day_E2 | -0.665 | 0.127 | 0.229 | 0.229 |
205
+ | egg_num | 0.210 | 0.205 | 0.352 | 0.352 |
206
+ | HCG_Day_Endo | -0.775 | -0.177 | 0.120 | 0.120 |
207
+
208
+ OT corrects distribution shift (E2: R² from -0.67 to 0.13). Anchor regression adds further gains for regression targets (egg_num: 0.21 to 0.35).
209
+
210
+ ### Cross-center generalization gap (Exp 2)
211
+
212
+ On an external test center unseen during training, MOSAIC reduces the validation-to-test performance gap by 42-76% for high-shift features (HCG_Day_E2: 75%, HCG_Day_P: 52%, HCG_Day_Endo: 72%).
213
+
214
+ ### Conformal coverage (Exp 3)
215
+
216
+ All 11 regression targets achieve 81-93% empirical coverage at the 90% nominal level. Weighted conformal consistently produces narrower intervals than standard split conformal at comparable coverage.
217
+
218
+ ### Comparison with existing methods (Exp 5)
219
+
220
+ | Feature | No harmonization | Z-score | ComBat | MOSAIC (OT) |
221
+ |---------|-----------------|---------|--------|-------------|
222
+ | HCG_Day_E2 (R²) | -0.665 | 0.069 | -0.383 | 0.127 |
223
+ | Clinical_pregnancy (AUC) | 0.838 | 0.837 | 0.837 | 0.839 |
224
+ | total_Gn (R²) | -0.121 | -0.327 | -0.034 | -0.022 |
225
+
226
+ MOSAIC outperforms Z-score and ComBat on high-shift features while maintaining comparable performance on low-shift targets.
227
+
228
+ ## Citation
229
+
230
+ If you use MOSAIC in your research, please cite:
231
+
232
+ ```
233
+ @article{chen2026mosaic,
234
+ title={MOSAIC: Multi-site Optimal-transport Shift Alignment with Interval
235
+ Calibration for Clinical Data Harmonization},
236
+ author={Chen, Peigen},
237
+ journal={npj Digital Medicine},
238
+ year={2026},
239
+ note={Manuscript in preparation}
240
+ }
241
+ ```
242
+
243
+ ## License
244
+
245
+ Apache-2.0. See [LICENSE](LICENSE) for details.
@@ -0,0 +1,200 @@
1
+ # MOSAIC
2
+
3
+ **Multi-site Optimal-transport Shift Alignment with Interval Calibration**
4
+
5
+ [![PyPI](https://img.shields.io/pypi/v/mosaic-harmonize)](https://pypi.org/project/mosaic-harmonize/)
6
+ [![Python](https://img.shields.io/pypi/pyversions/mosaic-harmonize)](https://pypi.org/project/mosaic-harmonize/)
7
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue)](LICENSE)
8
+ <!-- [![DOI](https://img.shields.io/badge/DOI-10.1038%2Fs41746--XXX-blue)](https://doi.org/10.1038/s41746-XXX) -->
9
+
10
+ MOSAIC is a Python package for harmonizing clinical tabular data collected across multiple sites. It combines 1-D optimal transport for distribution alignment, anchor regression for domain-robust prediction, and weighted conformal inference for uncertainty quantification. The three components can be used independently or chained through a single pipeline.
11
+
12
+ The package was developed for multi-center IVF (in vitro fertilization) outcome prediction, but the methods are general and apply to any multi-site clinical or biomedical dataset with batch effects.
13
+
14
+ ## Overview
15
+
16
+ MOSAIC has three tiers, each usable on its own:
17
+
18
+ | Tier | Class | What it does |
19
+ |------|-------|-------------|
20
+ | 1. Harmonization | `OTHarmonizer` | Per-feature quantile-based optimal transport mapping to a reference distribution. Reduces cross-center distribution shift while preserving within-center rank order. |
21
+ | 2. Robust learning | `AnchorEstimator` | Wraps any sklearn estimator with anchor regression (via [anchorboosting](https://github.com/mlondschien/anchorboosting)) or V-REx reweighting. Penalizes predictions that rely on center-specific patterns. |
22
+ | 3. Uncertainty | `ConformalCalibrator` | Split conformal prediction with optional covariate-shift correction (Tibshirani et al., NeurIPS 2019). Produces prediction intervals (regression) or prediction sets (classification) with finite-sample coverage guarantees. |
23
+
24
+ `MOSAICPipeline` chains all three into a single `fit` / `predict` interface.
25
+
26
+ ## Installation
27
+
28
+ Core (OT harmonization + anchor regression + conformal):
29
+
30
+ ```bash
31
+ pip install mosaic-harmonize
32
+ ```
33
+
34
+ With all optional dependencies (LightGBM, anchorboosting, MAPIE, matplotlib):
35
+
36
+ ```bash
37
+ pip install mosaic-harmonize[full]
38
+ ```
39
+
40
+ Individual extras: `boosting`, `conformal`, `viz`. For development: `dev`.
41
+
42
+ Requires Python 3.9+.
43
+
44
+ ## Quick start
45
+
46
+ ### Full pipeline
47
+
48
+ ```python
49
+ from mosaic import MOSAICPipeline
50
+ from lightgbm import LGBMRegressor
51
+
52
+ pipe = MOSAICPipeline(
53
+ harmonizer="ot",
54
+ robust_learner="anchor",
55
+ uncertainty="weighted_conformal",
56
+ base_estimator=LGBMRegressor(),
57
+ )
58
+
59
+ # center_ids: array of site labels, one per row
60
+ pipe.fit(X_train, y_train, center_ids=train_centers)
61
+
62
+ result = pipe.predict(X_test, center_id="new_hospital")
63
+ print(result.prediction) # point predictions
64
+ print(result.lower, result.upper) # 90% prediction intervals
65
+ ```
66
+
67
+ ### Individual components
68
+
69
+ ```python
70
+ from mosaic import OTHarmonizer, AnchorEstimator, ConformalCalibrator
71
+
72
+ # Tier 1: align distributions
73
+ ot = OTHarmonizer(n_quantiles=1000, reference="global")
74
+ X_harmonized = ot.fit_transform(X_train, center_ids=train_centers)
75
+
76
+ # Inspect shift reduction
77
+ print(ot.wasserstein_distances())
78
+ print(ot.feature_shift_report())
79
+
80
+ # Tier 2: train a domain-robust model
81
+ anchor = AnchorEstimator(base_estimator=LGBMRegressor(), task_type="regression")
82
+ anchor.fit(X_harmonized, y_train, anchors=train_centers)
83
+ print(f"Best gamma: {anchor.best_gamma_}")
84
+ print(f"Cross-center stability: {anchor.stability_score_:.3f}")
85
+
86
+ # Tier 3: calibrate with conformal prediction
87
+ cal = ConformalCalibrator(method="weighted", alpha=0.10)
88
+ cal.calibrate(anchor, X_cal, y_cal, X_test=X_test)
89
+ result = cal.predict(X_test)
90
+ print(f"Interval widths: {(result.upper - result.lower).mean():.2f}")
91
+ ```
92
+
93
+ ### Save and load
94
+
95
+ ```python
96
+ pipe.save("model.mosaic")
97
+ pipe = MOSAICPipeline.load("model.mosaic")
98
+ ```
99
+
100
+ ### Register a new center at inference time
101
+
102
+ ```python
103
+ pipe.register_center("hospital_B", X_new_center)
104
+ result = pipe.predict(X_query, center_id="hospital_B")
105
+ ```
106
+
107
+ ## API reference
108
+
109
+ ### OTHarmonizer
110
+
111
+ | Parameter | Type | Default | Description |
112
+ |-----------|------|---------|-------------|
113
+ | `n_quantiles` | int | 1000 | Number of quantile points for the OT map |
114
+ | `features` | list[str] or None | None | Columns to harmonize (None = all numeric) |
115
+ | `reference` | str | "global" | Reference distribution: "global" or a center name |
116
+ | `min_samples` | int | 50 | Minimum non-null samples to build a map |
117
+
118
+ Methods: `fit(X, center_ids)`, `transform(X, center_id=..., center_ids=...)`, `fit_transform(X, center_ids)`, `wasserstein_distances()`, `feature_shift_report()`.
119
+
120
+ ### AnchorEstimator
121
+
122
+ | Parameter | Type | Default | Description |
123
+ |-----------|------|---------|-------------|
124
+ | `base_estimator` | sklearn estimator or None | None | Base learner (None = Ridge/LogisticRegression) |
125
+ | `gammas` | list[float] or None | [1.5, 3.0, 7.0] | Anchor penalty strengths to search |
126
+ | `task_type` | str | "auto" | "auto", "regression", "binary", or "multiclass" |
127
+ | `n_vrex_rounds` | int | 5 | V-REx reweighting iterations (fallback mode) |
128
+
129
+ Methods: `fit(X, y, anchors, X_val=None, y_val=None)`, `predict(X)`, `predict_proba(X)`. Properties: `best_gamma_`, `stability_score_`.
130
+
131
+ ### ConformalCalibrator
132
+
133
+ | Parameter | Type | Default | Description |
134
+ |-----------|------|---------|-------------|
135
+ | `method` | str | "weighted" | "weighted", "standard", or "lac" |
136
+ | `alpha` | float | 0.10 | Miscoverage level (0.10 = 90% target coverage) |
137
+
138
+ Methods: `calibrate(model, X_cal, y_cal, X_test=None)`, `predict(X_test)` returning `ConformalResult`.
139
+
140
+ ### MOSAICPipeline
141
+
142
+ | Parameter | Type | Default | Description |
143
+ |-----------|------|---------|-------------|
144
+ | `harmonizer` | str or None | "ot" | "ot" or None |
145
+ | `robust_learner` | str or None | "anchor" | "anchor" or None |
146
+ | `uncertainty` | str or None | "weighted_conformal" | "weighted_conformal", "standard", "lac", or None |
147
+ | `base_estimator` | sklearn estimator | None | Base learner passed to AnchorEstimator |
148
+
149
+ Methods: `fit(X_train, y_train, center_ids, X_cal=None, y_cal=None)`, `predict(X, center_id=..., center_ids=...)`, `register_center(name, X_new)`, `diagnose(X, center_id)`, `save(path)`, `load(path)`.
150
+
151
+ ## Benchmarks
152
+
153
+ Evaluated on a multi-center IVF dataset (334K rows, 5 centers, 15 prediction targets). Full results in `benchmarks/results/`.
154
+
155
+ ### Ablation (Exp 1): each tier adds value
156
+
157
+ | Target | Baseline R² | +OT | +OT+Anchor | Full MOSAIC |
158
+ |--------|------------|-----|------------|-------------|
159
+ | HCG_Day_E2 | -0.665 | 0.127 | 0.229 | 0.229 |
160
+ | egg_num | 0.210 | 0.205 | 0.352 | 0.352 |
161
+ | HCG_Day_Endo | -0.775 | -0.177 | 0.120 | 0.120 |
162
+
163
+ OT corrects distribution shift (E2: R² from -0.67 to 0.13). Anchor regression adds further gains for regression targets (egg_num: 0.21 to 0.35).
164
+
165
+ ### Cross-center generalization gap (Exp 2)
166
+
167
+ On an external test center unseen during training, MOSAIC reduces the validation-to-test performance gap by 42-76% for high-shift features (HCG_Day_E2: 75%, HCG_Day_P: 52%, HCG_Day_Endo: 72%).
168
+
169
+ ### Conformal coverage (Exp 3)
170
+
171
+ All 11 regression targets achieve 81-93% empirical coverage at the 90% nominal level. Weighted conformal consistently produces narrower intervals than standard split conformal at comparable coverage.
172
+
173
+ ### Comparison with existing methods (Exp 5)
174
+
175
+ | Feature | No harmonization | Z-score | ComBat | MOSAIC (OT) |
176
+ |---------|-----------------|---------|--------|-------------|
177
+ | HCG_Day_E2 (R²) | -0.665 | 0.069 | -0.383 | 0.127 |
178
+ | Clinical_pregnancy (AUC) | 0.838 | 0.837 | 0.837 | 0.839 |
179
+ | total_Gn (R²) | -0.121 | -0.327 | -0.034 | -0.022 |
180
+
181
+ MOSAIC outperforms Z-score and ComBat on high-shift features while maintaining comparable performance on low-shift targets.
182
+
183
+ ## Citation
184
+
185
+ If you use MOSAIC in your research, please cite:
186
+
187
+ ```
188
+ @article{chen2026mosaic,
189
+ title={MOSAIC: Multi-site Optimal-transport Shift Alignment with Interval
190
+ Calibration for Clinical Data Harmonization},
191
+ author={Chen, Peigen},
192
+ journal={npj Digital Medicine},
193
+ year={2026},
194
+ note={Manuscript in preparation}
195
+ }
196
+ ```
197
+
198
+ ## License
199
+
200
+ Apache-2.0. See [LICENSE](LICENSE) for details.