causalis 0.2.9.dev347__py3-none-any.whl → 0.3.1.dev2__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.
causalis/_version.py CHANGED
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.2.9.dev347'
22
- __version_tuple__ = version_tuple = (0, 2, 9, 'dev347')
21
+ __version__ = version = '0.3.1.dev2'
22
+ __version_tuple__ = version_tuple = (0, 3, 1, 'dev2')
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -77,6 +77,7 @@ class MultiCausalEstimate(BaseModel):
77
77
  n_treated_by_arm: Optional[np.ndarray] = None
78
78
  treatment_mean: Optional[np.ndarray] = None
79
79
  control_mean: Optional[float] = None
80
+ control_mean_by_arm: Optional[np.ndarray] = None
80
81
  contrast_labels: List[str] = Field(default_factory=list)
81
82
  confounders: List[str] = Field(default_factory=list)
82
83
  time: str = Field(default_factory=lambda: datetime.now().strftime("%Y-%m-%d"))
@@ -157,6 +158,13 @@ class MultiCausalEstimate(BaseModel):
157
158
  treatment_mean = self._as_1d_array(self.treatment_mean, n_effects, name="treatment_mean").astype(float)
158
159
 
159
160
  control_mean = float(self.control_mean) if self.control_mean is not None else None
161
+ control_mean_by_arm = None
162
+ if self.control_mean_by_arm is not None:
163
+ control_mean_by_arm = self._as_1d_array(
164
+ self.control_mean_by_arm,
165
+ n_effects,
166
+ name="control_mean_by_arm",
167
+ ).astype(float)
160
168
 
161
169
  summary_columns: Dict[str, Dict[str, Any]] = {}
162
170
  for i, contrast in enumerate(self._contrast_names(n_effects)):
@@ -173,6 +181,9 @@ class MultiCausalEstimate(BaseModel):
173
181
 
174
182
  n_treated_i = int(n_treated_by_arm[i]) if n_treated_by_arm is not None else int(self.n_treated)
175
183
  treatment_mean_i = _fmt_float(float(treatment_mean[i])) if treatment_mean is not None else None
184
+ control_mean_i = control_mean
185
+ if control_mean_by_arm is not None:
186
+ control_mean_i = float(control_mean_by_arm[i])
176
187
 
177
188
  summary_columns[contrast] = {
178
189
  "estimand": self.estimand,
@@ -185,7 +196,7 @@ class MultiCausalEstimate(BaseModel):
185
196
  "n_treated": n_treated_i,
186
197
  "n_control": int(self.n_control),
187
198
  "treatment_mean": treatment_mean_i,
188
- "control_mean": _fmt_float(control_mean),
199
+ "control_mean": _fmt_float(control_mean_i),
189
200
  "time": self.time,
190
201
  }
191
202
 
@@ -30,6 +30,15 @@ def generate_multitreatment_irm_26(*args, **kwargs):
30
30
  return _generate_multitreatment_irm_26(*args, **kwargs)
31
31
 
32
32
 
33
+ def generate_multi_dml_cx_26(*args, **kwargs):
34
+ # Lazy import to avoid circular dependency at module import time.
35
+ from causalis.scenarios.multi_unconfoundedness.dgp import (
36
+ generate_multi_dml_cx_26 as _generate_multi_dml_cx_26,
37
+ )
38
+
39
+ return _generate_multi_dml_cx_26(*args, **kwargs)
40
+
41
+
33
42
  __all__ = [
34
43
  "MultiCausalData",
35
44
  "MultiCausalDatasetGenerator",
@@ -37,4 +46,5 @@ __all__ = [
37
46
  "generate_multitreatment_gamma_26",
38
47
  "generate_multitreatment_binary_26",
39
48
  "generate_multitreatment_irm_26",
49
+ "generate_multi_dml_cx_26",
40
50
  ]
@@ -27,7 +27,9 @@ Examples
27
27
  from __future__ import annotations
28
28
 
29
29
  import pandas as pd
30
- from typing import Optional, Union, List, Dict, Any
30
+ from typing import Optional, Union, List, Dict, Any, Callable
31
+
32
+ import numpy as np
31
33
 
32
34
  from causalis.data_contracts.multicausaldata import MultiCausalData
33
35
  from .base import MultiCausalDatasetGenerator
@@ -44,7 +46,9 @@ def generate_multitreatment(
44
46
  target_d_rate: Optional[Union[List[float], Any]] = None,
45
47
  confounder_specs: Optional[List[Dict[str, Any]]] = None,
46
48
  beta_y: Optional[Any] = None,
49
+ g_y: Optional[Callable[[np.ndarray], np.ndarray]] = None,
47
50
  beta_d: Optional[Any] = None,
51
+ g_d: Optional[Any] = None,
48
52
  theta: Optional[Any] = None,
49
53
  random_state: Optional[int] = 42,
50
54
  k: int = 0,
@@ -81,8 +85,12 @@ def generate_multitreatment(
81
85
  Schema for confounder distributions.
82
86
  beta_y : array-like, optional
83
87
  Linear coefficients for outcome model.
88
+ g_y : callable, optional
89
+ Nonlinear baseline outcome function added on the link scale.
84
90
  beta_d : array-like, optional
85
91
  Linear coefficients for treatment model.
92
+ g_d : callable or list of callables, optional
93
+ Nonlinear treatment score function(s) added on the softmax-link scale.
86
94
  theta : float or array-like, optional
87
95
  Constant treatment effects per class (adds to `tau` when both are provided).
88
96
  random_state : int, optional
@@ -139,7 +147,9 @@ def generate_multitreatment(
139
147
  target_d_rate=target_d_rate,
140
148
  confounder_specs=confounder_specs,
141
149
  beta_y=beta_y,
150
+ g_y=g_y,
142
151
  beta_d=beta_d,
152
+ g_d=g_d,
143
153
  theta=theta,
144
154
  seed=random_state,
145
155
  k=int(k),
@@ -0,0 +1,136 @@
1
+ """Shared numeric helpers for multi-treatment IRM models."""
2
+ from __future__ import annotations
3
+
4
+ import warnings
5
+
6
+ import numpy as np
7
+ from sklearn.base import is_classifier
8
+
9
+
10
+ def _is_binary(values: np.ndarray) -> bool:
11
+ """Check if an array contains only binary values (0 and 1)."""
12
+ uniq = np.unique(values)
13
+ if uniq.size == 0:
14
+ return False
15
+ return np.all(np.isin(uniq, np.array([0, 1], dtype=float)))
16
+
17
+
18
+ def _safe_is_classifier(estimator) -> bool:
19
+ """Safely check if an estimator is a classifier."""
20
+ try:
21
+ return is_classifier(estimator)
22
+ except (AttributeError, TypeError):
23
+ return getattr(estimator, "_estimator_type", None) == "classifier"
24
+
25
+
26
+ def _predict_propensity_matrix(model, X: np.ndarray, n_treatments: int) -> np.ndarray:
27
+ """Predict propensity matrix P(D=k|X) with aligned treatment columns."""
28
+ if not _safe_is_classifier(model) or not hasattr(model, "predict_proba"):
29
+ raise ValueError("ml_m must be a probabilistic classifier exposing predict_proba().")
30
+
31
+ proba = np.asarray(model.predict_proba(X), dtype=float)
32
+ if proba.ndim != 2:
33
+ raise ValueError(
34
+ f"ml_m.predict_proba() must return 2D array (n, K). Got shape {proba.shape}."
35
+ )
36
+
37
+ n = X.shape[0]
38
+ classes = getattr(model, "classes_", None)
39
+ if classes is None:
40
+ if proba.shape[1] != n_treatments:
41
+ raise ValueError(
42
+ f"ml_m returned {proba.shape[1]} probability columns, expected {n_treatments}."
43
+ )
44
+ out = proba
45
+ else:
46
+ classes = np.asarray(classes)
47
+ if classes.ndim != 1:
48
+ raise ValueError("ml_m.classes_ must be a 1D array.")
49
+ out = np.zeros((n, n_treatments), dtype=float)
50
+ seen = set()
51
+ for j, cls in enumerate(classes):
52
+ if not np.isfinite(cls):
53
+ raise ValueError("ml_m.classes_ contains non-finite labels.")
54
+ cls_int = int(cls)
55
+ if cls_int != cls:
56
+ raise ValueError("ml_m.classes_ must contain integer treatment labels 0..K-1.")
57
+ if cls_int < 0 or cls_int >= n_treatments:
58
+ raise ValueError(
59
+ f"ml_m.classes_ contains out-of-range label {cls_int}; expected 0..{n_treatments - 1}."
60
+ )
61
+ out[:, cls_int] = proba[:, j]
62
+ seen.add(cls_int)
63
+ missing = [k for k in range(n_treatments) if k not in seen]
64
+ if missing:
65
+ raise RuntimeError(
66
+ "A cross-fitting training fold is missing treatment classes "
67
+ f"{missing}. Reduce n_folds or increase sample size."
68
+ )
69
+
70
+ if np.any((out < -1e-12) | (out > 1.0 + 1e-12)):
71
+ warnings.warn(
72
+ "Propensity model produced values outside [0, 1]. "
73
+ "Values are clipped and renormalized row-wise.",
74
+ RuntimeWarning,
75
+ )
76
+ out = np.clip(out, 0.0, 1.0)
77
+ row_sums = out.sum(axis=1, keepdims=True)
78
+ if np.any(row_sums <= 1e-12):
79
+ raise RuntimeError("Propensity predictions contain rows with zero total probability.")
80
+ if np.any(np.abs(row_sums - 1.0) > 1e-6):
81
+ warnings.warn(
82
+ "Propensity probabilities do not sum to 1. Values are renormalized row-wise.",
83
+ RuntimeWarning,
84
+ )
85
+ out = out / row_sums
86
+ return out
87
+
88
+
89
+ def _normalize_rows_to_simplex(p: np.ndarray) -> np.ndarray:
90
+ """Normalize row-wise probabilities onto the simplex."""
91
+ p = np.asarray(p, dtype=float)
92
+ p = np.maximum(p, 1e-12)
93
+ row_sums = p.sum(axis=1, keepdims=True)
94
+ if np.any(np.isfinite(row_sums) & (row_sums <= 1e-12)):
95
+ raise RuntimeError("Propensity matrix contains rows with zero total probability.")
96
+ safe_sums = np.where(np.isfinite(row_sums) & (row_sums > 1e-12), row_sums, 1.0)
97
+ return p / safe_sums
98
+
99
+
100
+ def _trim_multiclass_propensity(p: np.ndarray, thr: float) -> np.ndarray:
101
+ """Lower-trim multiclass propensity and renormalize rows to sum to 1."""
102
+ p = np.asarray(p, dtype=float)
103
+ if p.ndim != 2:
104
+ raise ValueError(f"Propensity matrix must be 2D (n, K). Got shape {p.shape}.")
105
+ n_treatments = p.shape[1]
106
+ if n_treatments < 2:
107
+ raise ValueError("Need at least 2 treatment columns for multiclass propensity.")
108
+
109
+ thr = float(thr)
110
+ if not np.isfinite(thr) or not (0.0 <= thr < (1.0 / n_treatments)):
111
+ raise ValueError(
112
+ f"trimming_threshold must be finite and in [0, 1/K) for K={n_treatments}; got {thr}."
113
+ )
114
+
115
+ p_simplex = _normalize_rows_to_simplex(p)
116
+ if thr <= 0.0:
117
+ return p_simplex
118
+
119
+ p_trim = np.maximum(p_simplex, thr)
120
+ return _normalize_rows_to_simplex(p_trim)
121
+
122
+
123
+ def _normalize_multiclass_ipw_terms(
124
+ d: np.ndarray,
125
+ m_hat: np.ndarray,
126
+ *,
127
+ normalize_ipw: bool,
128
+ ) -> np.ndarray:
129
+ """Return d_k / m_k with optional Hajek column normalization."""
130
+ d = np.asarray(d, dtype=float)
131
+ m_hat = np.asarray(m_hat, dtype=float)
132
+ h = d / m_hat
133
+ if normalize_ipw:
134
+ h_mean = h.mean(axis=0, keepdims=True)
135
+ h = h / np.where(h_mean != 0.0, h_mean, 1.0)
136
+ return h