causarray 0.0.1__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,163 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
161
+
162
+
163
+ test*
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Du Jinhong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.4
2
+ Name: causarray
3
+ Version: 0.0.1
4
+ Summary: causarray is a Python module for A Python package for simultaneous causal inference with an array of outcomes.
5
+ Author-email: Jin-Hong Du <jinhongd@andrew.cmu.com>, Maya Shen <myshen@andrew.cmu.edu>, Hansruedi Mathys <mathysh@pitt.edu>, Kathryn Roeder <jinhongd@andrew.cmu.com>
6
+ Maintainer-email: Jin-Hong Du <jinhongd@andrew.cmu.com>
7
+ License: MIT License
8
+ License-File: LICENSE
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.8
13
+ Requires-Dist: joblib
14
+ Requires-Dist: matplotlib
15
+ Requires-Dist: numba
16
+ Requires-Dist: numpy
17
+ Requires-Dist: pandas
18
+ Requires-Dist: pip
19
+ Requires-Dist: scikit-learn
20
+ Requires-Dist: scipy
21
+ Requires-Dist: sklearn-ensemble-cv
22
+ Requires-Dist: statsmodels
23
+ Requires-Dist: tqdm
24
+ Description-Content-Type: text/markdown
25
+
26
+ # causarray
27
+
28
+ Advances in single-cell sequencing and CRISPR technologies have enabled detailed case-control comparisons and experimental perturbations at single-cell resolution. However, uncovering causal relationships in observational genomic data remains challenging due to selection bias and inadequate adjustment for unmeasured confounders, particularly in heterogeneous datasets. To address these challenges, we introduce `causarray` [Du25], a doubly robust causal inference framework for analyzing array-based genomic data at both bulk-cell and single-cell levels. `causarray` integrates a generalized confounder adjustment method to account for unmeasured confounders and employs semiparametric inference with flexible machine learning techniques to ensure robust statistical estimation of treatment effects.
29
+
30
+
31
+ # Requirements
32
+
33
+ The dependencies for running `causarray` method are listed in `environment.yml` and can be installed by running
34
+
35
+ ```cmd
36
+ PIP_NO_DEPS=1 conda env create -f environment.yml
37
+ ```
38
+
39
+
40
+
41
+
42
+ <!--
43
+ # Development
44
+
45
+ ## Build
46
+ ```cmd
47
+ git tag 0.0.0
48
+ git tag --delete 1.0.0
49
+ python -m pip install .
50
+ ```
51
+
52
+ ## Testing
53
+ ```cmd
54
+ python -m pytest tests/test_gcate.py
55
+ python -m pytest tests/test_DR_learner.py
56
+ ```
57
+
58
+ ## Documentation
59
+
60
+ ```cmd
61
+ mkdir docs
62
+ sphinx-quickstart
63
+ cd docs
64
+ make html # sphinx-build source build
65
+ ```
66
+ -->
67
+
68
+
69
+ # References
70
+ [Du25] Jin-Hong Du, Maya Shen, Hansruedi Mathys, and Kathryn Roeder (2025). Causal differential expression analysis under unmeasured confounders with causarray. bioRxiv, 2025-01.
@@ -0,0 +1,45 @@
1
+ # causarray
2
+
3
+ Advances in single-cell sequencing and CRISPR technologies have enabled detailed case-control comparisons and experimental perturbations at single-cell resolution. However, uncovering causal relationships in observational genomic data remains challenging due to selection bias and inadequate adjustment for unmeasured confounders, particularly in heterogeneous datasets. To address these challenges, we introduce `causarray` [Du25], a doubly robust causal inference framework for analyzing array-based genomic data at both bulk-cell and single-cell levels. `causarray` integrates a generalized confounder adjustment method to account for unmeasured confounders and employs semiparametric inference with flexible machine learning techniques to ensure robust statistical estimation of treatment effects.
4
+
5
+
6
+ # Requirements
7
+
8
+ The dependencies for running `causarray` method are listed in `environment.yml` and can be installed by running
9
+
10
+ ```cmd
11
+ PIP_NO_DEPS=1 conda env create -f environment.yml
12
+ ```
13
+
14
+
15
+
16
+
17
+ <!--
18
+ # Development
19
+
20
+ ## Build
21
+ ```cmd
22
+ git tag 0.0.0
23
+ git tag --delete 1.0.0
24
+ python -m pip install .
25
+ ```
26
+
27
+ ## Testing
28
+ ```cmd
29
+ python -m pytest tests/test_gcate.py
30
+ python -m pytest tests/test_DR_learner.py
31
+ ```
32
+
33
+ ## Documentation
34
+
35
+ ```cmd
36
+ mkdir docs
37
+ sphinx-quickstart
38
+ cd docs
39
+ make html # sphinx-build source build
40
+ ```
41
+ -->
42
+
43
+
44
+ # References
45
+ [Du25] Jin-Hong Du, Maya Shen, Hansruedi Mathys, and Kathryn Roeder (2025). Causal differential expression analysis under unmeasured confounders with causarray. bioRxiv, 2025-01.
@@ -0,0 +1,269 @@
1
+ import numpy as np
2
+ from sklearn.linear_model import LogisticRegression
3
+ from sklearn.ensemble import RandomForestClassifier
4
+ from causarray.gcate_glm import fit_glm
5
+ from causarray.utils import *
6
+ from causarray.utils import _filter_params
7
+ import pprint
8
+
9
+ from sklearn.model_selection import KFold, ShuffleSplit
10
+
11
+ def _get_func_ps(ps_model, **kwargs):
12
+ if ps_model=='random_forest_cv':
13
+ params_ps = _filter_params(fit_rf, kwargs)
14
+ func_ps = lambda X, Y, X_test:fit_rf_ind_ps(X, Y[:,None], X_test=X_test, **params_ps)[:,0]
15
+ elif ps_model=='logistic':
16
+ clf_ps = LogisticRegression
17
+ kwargs = {**{'fit_intercept':False, 'C':1e0, 'class_weight':'balanced', 'random_state':0}, **kwargs}
18
+ params_ps = _filter_params(clf_ps().get_params(), kwargs)
19
+ func_ps = lambda X, Y, X_test: clf_ps(**params_ps).fit(X, Y).predict_proba(X_test)[:,1]
20
+ elif ps_model=='ensemble':
21
+ params_ps_rf = _filter_params(fit_rf, kwargs)
22
+ clf_ps = LogisticRegression
23
+ kwargs = {**{'fit_intercept':False, 'C':1e0, 'class_weight':'balanced', 'random_state':0}, **kwargs}
24
+ params_ps_lr = _filter_params(clf_ps().get_params(), kwargs)
25
+ params_ps = {'params_ps_rf':params_ps_rf, 'params_ps_lr':params_ps_lr}
26
+ func_ps = lambda X, Y, X_test:(fit_rf_ind(X, Y[:,None], X_test=X_test, **params_ps_rf)[:,0] + clf_ps(**params_ps_lr).fit(X, Y).predict_proba(X_test)[:,1])/2
27
+ else:
28
+ raise ValueError('Invalid propensity score model.')
29
+
30
+ return func_ps, params_ps
31
+
32
+
33
+ def cross_fitting(
34
+ Y, A, X, X_A, family='poisson', K=1, glm_alpha=1e-4,
35
+ ps_model='logistic',
36
+ pi_hat=None, Y_hat=None, verbose=False, **kwargs):
37
+ '''
38
+ Cross-fitting for causal estimands.
39
+
40
+ Parameters
41
+ ----------
42
+ Y : array
43
+ Outcomes.
44
+ A : array
45
+ Binary treatment indicator.
46
+ X : array
47
+ Covariates.
48
+ X_A : array
49
+ Covariates for the propensity score model.
50
+ family : str, optional
51
+ The family of the generalized linear model. The default is 'poisson'.
52
+ K : int, optional
53
+ The number of folds for cross-validation. The default is 1.
54
+ glm_alpha : float, optional
55
+ The regularization parameter for the generalized linear model. The default is 1e-4.
56
+ ps_model : str, optional
57
+ The propensity score model. The default is 'logistic'.
58
+ pi_hat : array, optional
59
+ Propensity score of shape (n, a). The default is None.
60
+ Y_hat : array, optional
61
+ Estimated potential outcome of shape (n, p, a, 2). The default is None.
62
+ **kwargs : dict
63
+ Additional arguments to pass to the model.
64
+
65
+ Returns
66
+ -------
67
+ Y_hat : array
68
+ Estimated potential outcome under control.
69
+ pi_hat : array
70
+ Estimated propensity score.
71
+ '''
72
+ func_ps, params_ps = _get_func_ps(ps_model, **kwargs)
73
+ params_glm = _filter_params(fit_glm, kwargs)
74
+
75
+ if verbose:
76
+ pprint.pprint(params_ps)
77
+ pprint.pprint(params_glm)
78
+
79
+ if K>1:
80
+ # Initialize KFold cross-validator
81
+ kf = KFold(n_splits=K, random_state=0, shuffle=True)
82
+ folds = kf.split(X)
83
+ else:
84
+ folds = [(np.arange(X.shape[0]), np.arange(X.shape[0]))]
85
+
86
+ # Initialize lists to store results
87
+ fit_pi = True if pi_hat is None else False
88
+ pi_hat = np.zeros_like(A, dtype=float) if fit_pi else pi_hat
89
+ Y_hat = np.zeros((Y.shape[0],Y.shape[1],A.shape[1],2), dtype=float)
90
+
91
+ # Perform cross-fitting
92
+ for train_index, test_index in folds:
93
+ # Split data
94
+ X_train, X_test = X[train_index], X[test_index]
95
+ XA_train, XA_test = X_A[train_index], X_A[test_index]
96
+ A_train, A_test = A[train_index], A[test_index]
97
+ Y_train, Y_test = Y[train_index], Y[test_index]
98
+
99
+ if fit_pi:
100
+ i_ctrl = (np.sum(A_train, axis=1) == 0.)
101
+
102
+ pi = np.zeros_like(A_test, dtype=float)
103
+ for j in range(A.shape[1]):
104
+ i_case = (A_train[:,j] == 1.)
105
+ i_cells = i_ctrl | i_case
106
+
107
+ if ps_model=='logistic' and XA_train.shape[1]==1 and np.all(XA_train==1):
108
+ prob = np.sum(i_case)/np.sum(i_cells)
109
+ pi[A_train[:,j] == 1., j] = prob
110
+ pi[A_train[:,j] == 0., j] = 1 - prob
111
+ else:
112
+ pi[:,j] = func_ps(XA_train[i_cells], A_train[i_cells][:,j], XA_test)
113
+
114
+ # Fit GLM on training data and predict on test data
115
+ res = fit_glm(Y_train, X_train, A_train, family=family, alpha=glm_alpha,
116
+ impute=X_test, **params_glm)
117
+
118
+ # Store results
119
+ if fit_pi:
120
+ pi_hat[test_index] = pi
121
+
122
+ Y_hat[test_index,:,:,0] = res[1][0]
123
+ Y_hat[test_index,:,:,1] = res[1][1]
124
+
125
+ pi_hat = np.clip(pi_hat, 0.01, 0.99)
126
+ Y_hat = np.clip(Y_hat, None, 1e5)
127
+ return Y_hat, pi_hat
128
+
129
+
130
+
131
+
132
+
133
+ def AIPW_mean(Y, A, mu, pi, positive=False):
134
+ '''
135
+ Augmented inverse probability weighted estimator (AIPW)
136
+
137
+ Parameters
138
+ ----------
139
+ Y : array
140
+ Outcomes of shape (n, p).
141
+ A : array
142
+ Binary treatment indicator of shape (n, a, 2).
143
+ mu : array
144
+ Conditional outcome distribution estimate of shape (n, p, a, 2).
145
+ pi : array
146
+ Propensity score of shape (n, a, 2).
147
+ positive : bool, optional
148
+ Whether to restrict the pseudo-outcome to be positive.
149
+
150
+ Returns
151
+ -------
152
+ tau : array
153
+ A point estimate of the expected potential outcome of shape (p, a, 2).
154
+ pseudo_y : array
155
+ Pseudo-outcome of shape (n, p, a, 2).
156
+ '''
157
+
158
+ weight = A / pi
159
+ weight = weight[:, None, ...]
160
+ Y = Y[:, :, None, None]
161
+
162
+ pseudo_y = weight * (Y - mu) + mu
163
+
164
+ if positive:
165
+ pseudo_y = np.clip(pseudo_y, 0, None)
166
+
167
+ tau = np.mean(pseudo_y, axis=0)
168
+
169
+ return tau, pseudo_y
170
+
171
+
172
+
173
+
174
+
175
+
176
+
177
+
178
+
179
+
180
+ from joblib import Parallel, delayed
181
+ from tqdm import tqdm
182
+ from sklearn_ensemble_cv import reset_random_seeds, Ensemble, ECV
183
+ from sklearn.tree import DecisionTreeRegressor
184
+
185
+ def fit_rf(X, y, X_test=None, sample_weight=None, M=100, M_max=1000,
186
+ # fixed parameters for bagging regressor
187
+ kwargs_ensemble={'verbose':1},
188
+ # fixed parameters for decision tree
189
+ kwargs_regr={'min_samples_leaf': 3}, # 'min_samples_split': 10, 'max_features':'sqrt'
190
+ # grid search parameters
191
+ grid_regr = {'max_depth': [11]},
192
+ grid_ensemble = {'random_state': 0}, #'max_samples':np.linspace(0.25, 1., 4)
193
+ ):
194
+
195
+ # Validate integer parameters
196
+ M = int(M)
197
+ M_max = int(M_max)
198
+ # for kwargs in [kwargs_regr, kwargs_ensemble, grid_regr, grid_ensemble]:
199
+ # for param in kwargs:
200
+ # if param in ['max_depth', 'random_state', 'max_leaf_nodes'] and isinstance(kwargs[param], float):
201
+ # kwargs[param] = int(kwargs[param])
202
+
203
+ # Make sure y is 2D
204
+ y = y.reshape(-1, 1) if y.ndim == 1 else y
205
+
206
+ # Run ECV
207
+ res_ecv, info_ecv = ECV(
208
+ X, y, DecisionTreeRegressor, grid_regr, grid_ensemble,
209
+ kwargs_regr, kwargs_ensemble,
210
+ M=M, M0=M, M_max=M_max, return_df=True
211
+ )
212
+
213
+ # Replace the in-sample best parameter for 'n_estimators' with extrapolated best parameter
214
+ info_ecv['best_params_ensemble']['n_estimators'] = info_ecv['best_n_estimators_extrapolate']
215
+
216
+ # Fit the ensemble with the best CV parameters
217
+ regr = Ensemble(
218
+ estimator=DecisionTreeRegressor(**info_ecv['best_params_regr']),
219
+ **info_ecv['best_params_ensemble']).fit(X, y, sample_weight=sample_weight)
220
+
221
+ # Predict
222
+ if X_test is None:
223
+ X_test = X
224
+ return regr.predict(X_test).reshape(-1, y.shape[1])
225
+
226
+
227
+
228
+ def fit_rf_ind(X, Y, *args, **kwargs):
229
+ Y_hat = Parallel(n_jobs=-1)(delayed(fit_rf)(X, Y[:,j], *args, **kwargs)
230
+ for j in tqdm(range(Y.shape[1])))
231
+ Y_pred = np.concatenate(Y_hat, axis=-1)
232
+ return Y_pred
233
+
234
+
235
+ def fit_rf_ind_ps(X, Y, *args, **kwargs):
236
+ i_ctrl = (np.sum(Y, axis=1) == 0.)
237
+
238
+ if 'X_test' not in kwargs:
239
+ kwargs['X_test'] = X
240
+
241
+ def _fit(X, y, i_ctrl, *args, **kwargs):
242
+ i_case = (y == 1.)
243
+ i_cells = i_ctrl | i_case
244
+ sample_weight = np.ones(y.shape[0])
245
+ class_weight = len(y) / (2 * np.bincount(y.astype(int)))
246
+ for a in range(2):
247
+ sample_weight[y == a] = class_weight[a]
248
+ return fit_rf(X[i_cells], y[i_cells], sample_weight=sample_weight[i_cells], *args, **kwargs)
249
+
250
+ Y_hat = Parallel(n_jobs=-1)(delayed(_fit)(X, Y[:,j], i_ctrl, *args, **kwargs)
251
+ for j in tqdm(range(Y.shape[1])))
252
+ Y_pred = np.concatenate(Y_hat, axis=-1)
253
+
254
+ return Y_pred
255
+
256
+
257
+ def fit_rf_ind_outcome(W, Y, A, *args, **kwargs):
258
+ d = W.shape[1]
259
+ a = A.shape[1]
260
+ X = np.c_[W, A]
261
+ X_test = np.tile(np.c_[W, np.zeros_like(A)][:,None,:], (1,1+a,1))
262
+ for j in range(a):
263
+ X_test[:,1+j,d+j] = 1
264
+ X_test = X_test.reshape(-1, X_test.shape[-1])
265
+ Y_pred = fit_rf_ind(X, Y, X_test=X_test)
266
+ Y_pred = Y_pred.reshape(X.shape[0],1+a,Y.shape[1])
267
+ Yhat_1 = Y_pred[:,1:,:].transpose(0,2,1)
268
+ Yhat_0 = np.tile(Y_pred[:,0,:][:,:,None], (1,1,a))
269
+ return Yhat_0, Yhat_1