exactcis 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.
- exactcis/__init__.py +64 -0
- exactcis/_version.py +3 -0
- exactcis/cli.py +463 -0
- exactcis/core.py +1109 -0
- exactcis/methods/__init__.py +21 -0
- exactcis/methods/blaker.py +301 -0
- exactcis/methods/conditional.py +607 -0
- exactcis/methods/midp.py +300 -0
- exactcis/methods/unconditional.py +599 -0
- exactcis/methods/wald.py +44 -0
- exactcis/utils/__init__.py +7 -0
- exactcis/utils/calculators.py +287 -0
- exactcis/utils/data_models.py +125 -0
- exactcis/utils/optimization.py +488 -0
- exactcis/utils/parallel.py +289 -0
- exactcis/utils/pmf_functions.py +290 -0
- exactcis/utils/root_finding.py +453 -0
- exactcis/utils/stats.py +111 -0
- exactcis/utils/transformers.py +160 -0
- exactcis/utils/validators.py +103 -0
- exactcis-0.1.0.dist-info/METADATA +228 -0
- exactcis-0.1.0.dist-info/RECORD +25 -0
- exactcis-0.1.0.dist-info/WHEEL +4 -0
- exactcis-0.1.0.dist-info/entry_points.txt +2 -0
- exactcis-0.1.0.dist-info/licenses/LICENSE +21 -0
exactcis/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""
|
|
2
|
+
ExactCIs: Exact Confidence Intervals for Odds Ratios
|
|
3
|
+
|
|
4
|
+
This package provides methods to compute confidence intervals for the odds ratio
|
|
5
|
+
of a 2×2 contingency table. It includes various methods such as conditional (Fisher),
|
|
6
|
+
mid-P adjusted, Blaker's exact, Barnard's unconditional exact, and Haldane-Anscombe Wald.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from typing import Dict, Tuple
|
|
10
|
+
|
|
11
|
+
from exactcis.core import validate_counts, calculate_odds_ratio, calculate_relative_risk
|
|
12
|
+
from exactcis.utils.stats import (
|
|
13
|
+
add_haldane_correction,
|
|
14
|
+
calculate_odds_ratio_with_correction,
|
|
15
|
+
calculate_standard_error
|
|
16
|
+
)
|
|
17
|
+
from exactcis.methods.conditional import exact_ci_conditional
|
|
18
|
+
from exactcis.methods.midp import exact_ci_midp
|
|
19
|
+
from exactcis.methods.blaker import exact_ci_blaker
|
|
20
|
+
from exactcis.methods.unconditional import exact_ci_unconditional
|
|
21
|
+
from exactcis.methods.wald import ci_wald_haldane
|
|
22
|
+
|
|
23
|
+
__version__ = "0.1.0"
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"compute_all_cis",
|
|
27
|
+
"exact_ci_conditional",
|
|
28
|
+
"exact_ci_midp",
|
|
29
|
+
"exact_ci_blaker",
|
|
30
|
+
"exact_ci_unconditional",
|
|
31
|
+
"ci_wald_haldane",
|
|
32
|
+
"calculate_odds_ratio",
|
|
33
|
+
"calculate_relative_risk",
|
|
34
|
+
"add_haldane_correction",
|
|
35
|
+
"calculate_odds_ratio_with_correction",
|
|
36
|
+
"calculate_standard_error",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def compute_all_cis(a: int, b: int, c: int, d: int,
|
|
41
|
+
alpha: float = 0.05, grid_size: int = 200
|
|
42
|
+
) -> Dict[str, Tuple[float, float]]:
|
|
43
|
+
"""
|
|
44
|
+
Compute confidence intervals for the odds ratio using all available methods.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
a: Count in cell (1,1)
|
|
48
|
+
b: Count in cell (1,2)
|
|
49
|
+
c: Count in cell (2,1)
|
|
50
|
+
d: Count in cell (2,2)
|
|
51
|
+
alpha: Significance level (default: 0.05)
|
|
52
|
+
grid_size: Number of grid points for optimization in Barnard's method (default: 200)
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
Dictionary mapping method names to confidence intervals (lower_bound, upper_bound)
|
|
56
|
+
"""
|
|
57
|
+
validate_counts(a, b, c, d)
|
|
58
|
+
return {
|
|
59
|
+
"conditional": exact_ci_conditional(a, b, c, d, alpha),
|
|
60
|
+
"midp": exact_ci_midp(a, b, c, d, alpha),
|
|
61
|
+
"blaker": exact_ci_blaker(a, b, c, d, alpha),
|
|
62
|
+
"unconditional": exact_ci_unconditional(a, b, c, d, alpha, grid_size),
|
|
63
|
+
"wald_haldane": ci_wald_haldane(a, b, c, d, alpha),
|
|
64
|
+
}
|
exactcis/_version.py
ADDED
exactcis/cli.py
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Command-line interface for ExactCIs package.
|
|
3
|
+
|
|
4
|
+
This module provides a command-line interface to the confidence interval methods
|
|
5
|
+
implemented in the ExactCIs package, allowing users to compute confidence intervals
|
|
6
|
+
without writing Python code.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import sys
|
|
11
|
+
import csv
|
|
12
|
+
import json
|
|
13
|
+
import traceback
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import List, Optional, Tuple, Dict, Any
|
|
16
|
+
import logging
|
|
17
|
+
|
|
18
|
+
from exactcis.methods import (
|
|
19
|
+
exact_ci_blaker,
|
|
20
|
+
exact_ci_conditional,
|
|
21
|
+
exact_ci_midp,
|
|
22
|
+
exact_ci_unconditional,
|
|
23
|
+
ci_wald_haldane
|
|
24
|
+
)
|
|
25
|
+
from exactcis.core import validate_counts, apply_haldane_correction
|
|
26
|
+
from exactcis.utils.parallel import parallel_compute_ci, get_optimal_workers
|
|
27
|
+
|
|
28
|
+
# Configure logging
|
|
29
|
+
logger = logging.getLogger(__name__)
|
|
30
|
+
|
|
31
|
+
# Map method names to functions
|
|
32
|
+
METHOD_MAP = {
|
|
33
|
+
'blaker': exact_ci_blaker,
|
|
34
|
+
'conditional': exact_ci_conditional,
|
|
35
|
+
'midp': exact_ci_midp,
|
|
36
|
+
'unconditional': exact_ci_unconditional,
|
|
37
|
+
'wald': ci_wald_haldane
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def validate_counts_cli(a: int, b: int, c: int, d: int) -> None:
|
|
42
|
+
"""
|
|
43
|
+
CLI-specific validation for counts that provides user-friendly error messages.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
a: Count in cell (1,1)
|
|
47
|
+
b: Count in cell (1,2)
|
|
48
|
+
c: Count in cell (2,1)
|
|
49
|
+
d: Count in cell (2,2)
|
|
50
|
+
|
|
51
|
+
Raises:
|
|
52
|
+
ValueError: With user-friendly message if validation fails
|
|
53
|
+
"""
|
|
54
|
+
try:
|
|
55
|
+
validate_counts(a, b, c, d)
|
|
56
|
+
except ValueError as e:
|
|
57
|
+
# Convert the error to a more user-friendly message
|
|
58
|
+
if "negative" in str(e):
|
|
59
|
+
raise ValueError("Error: All cell counts must be non-negative.")
|
|
60
|
+
elif "margin" in str(e):
|
|
61
|
+
raise ValueError("Error: Cannot compute CI with empty margins (row or column totals = 0).")
|
|
62
|
+
else:
|
|
63
|
+
raise ValueError(f"Error: {str(e)}")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def parse_args(args: Optional[List[str]] = None) -> argparse.Namespace:
|
|
67
|
+
"""
|
|
68
|
+
Parse command line arguments.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
args: Command line arguments (defaults to sys.argv[1:])
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
argparse.Namespace: Parsed arguments
|
|
75
|
+
"""
|
|
76
|
+
parser = argparse.ArgumentParser(
|
|
77
|
+
description="Calculate exact confidence intervals for odds ratios from 2x2 contingency tables.",
|
|
78
|
+
epilog="Example: exactcis-cli 10 20 15 30 --method blaker --alpha 0.05\n" +
|
|
79
|
+
"Batch mode: exactcis-cli --batch input.csv --output results.csv --method blaker",
|
|
80
|
+
formatter_class=argparse.RawDescriptionHelpFormatter
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
# Single table arguments (mutually exclusive with batch mode)
|
|
84
|
+
single_group = parser.add_argument_group('single table mode')
|
|
85
|
+
single_group.add_argument("a", type=int, nargs='?', help="Cell a count (exposed cases)")
|
|
86
|
+
single_group.add_argument("b", type=int, nargs='?', help="Cell b count (exposed controls)")
|
|
87
|
+
single_group.add_argument("c", type=int, nargs='?', help="Cell c count (unexposed cases)")
|
|
88
|
+
single_group.add_argument("d", type=int, nargs='?', help="Cell d count (unexposed controls)")
|
|
89
|
+
|
|
90
|
+
# Batch processing arguments
|
|
91
|
+
batch_group = parser.add_argument_group('batch processing mode')
|
|
92
|
+
batch_group.add_argument(
|
|
93
|
+
"--batch",
|
|
94
|
+
type=str,
|
|
95
|
+
help="Input CSV file with columns 'a', 'b', 'c', 'd', and optional 'id' column"
|
|
96
|
+
)
|
|
97
|
+
batch_group.add_argument(
|
|
98
|
+
"--output",
|
|
99
|
+
type=str,
|
|
100
|
+
help="Output CSV file for batch results (default: stdout)"
|
|
101
|
+
)
|
|
102
|
+
batch_group.add_argument(
|
|
103
|
+
"--workers",
|
|
104
|
+
type=int,
|
|
105
|
+
help="Number of parallel workers for batch processing (default: auto-detected)"
|
|
106
|
+
)
|
|
107
|
+
batch_group.add_argument(
|
|
108
|
+
"--timeout",
|
|
109
|
+
type=float,
|
|
110
|
+
help="Timeout in seconds for batch processing operations (default: no timeout)"
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
parser.add_argument(
|
|
114
|
+
"--alpha",
|
|
115
|
+
type=float,
|
|
116
|
+
default=0.05,
|
|
117
|
+
help="Significance level (default: 0.05)"
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
parser.add_argument(
|
|
121
|
+
"--method",
|
|
122
|
+
type=str,
|
|
123
|
+
default="blaker",
|
|
124
|
+
choices=METHOD_MAP.keys(),
|
|
125
|
+
help="CI method to use (default: blaker)"
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
parser.add_argument(
|
|
129
|
+
"--grid-size",
|
|
130
|
+
type=int,
|
|
131
|
+
default=20,
|
|
132
|
+
help="Grid size for unconditional method (default: 20, ignored for other methods)"
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
parser.add_argument(
|
|
136
|
+
"--apply-haldane",
|
|
137
|
+
action="store_true",
|
|
138
|
+
help="Apply Haldane's correction (add 0.5 to each cell)"
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
parser.add_argument(
|
|
142
|
+
"--verbose",
|
|
143
|
+
action="store_true",
|
|
144
|
+
help="Print additional information"
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
parser.add_argument(
|
|
148
|
+
"--format",
|
|
149
|
+
type=str,
|
|
150
|
+
choices=['table', 'csv', 'json'],
|
|
151
|
+
default='table',
|
|
152
|
+
help="Output format for batch processing (default: table)"
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
parsed = parser.parse_args(args)
|
|
156
|
+
|
|
157
|
+
# Validate argument combinations
|
|
158
|
+
if parsed.batch:
|
|
159
|
+
if any(x is not None for x in [parsed.a, parsed.b, parsed.c, parsed.d]):
|
|
160
|
+
parser.error("Cannot specify both batch file and individual cell counts")
|
|
161
|
+
else:
|
|
162
|
+
if any(x is None for x in [parsed.a, parsed.b, parsed.c, parsed.d]):
|
|
163
|
+
parser.error("Must specify all four cell counts (a, b, c, d) or use --batch mode")
|
|
164
|
+
|
|
165
|
+
return parsed
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def load_batch_data(filepath: str) -> List[Dict[str, Any]]:
|
|
169
|
+
"""
|
|
170
|
+
Load batch data from CSV file.
|
|
171
|
+
|
|
172
|
+
Args:
|
|
173
|
+
filepath: Path to CSV file
|
|
174
|
+
|
|
175
|
+
Returns:
|
|
176
|
+
List of dictionaries with table data
|
|
177
|
+
"""
|
|
178
|
+
tables = []
|
|
179
|
+
required_columns = {'a', 'b', 'c', 'd'}
|
|
180
|
+
|
|
181
|
+
try:
|
|
182
|
+
with open(filepath, 'r', newline='') as csvfile:
|
|
183
|
+
reader = csv.DictReader(csvfile)
|
|
184
|
+
|
|
185
|
+
if not required_columns.issubset(set(reader.fieldnames)):
|
|
186
|
+
missing = required_columns - set(reader.fieldnames)
|
|
187
|
+
raise ValueError(f"CSV file missing required columns: {missing}")
|
|
188
|
+
|
|
189
|
+
for row_num, row in enumerate(reader, 1):
|
|
190
|
+
try:
|
|
191
|
+
table = {
|
|
192
|
+
'id': row.get('id', f'table_{row_num}'),
|
|
193
|
+
'a': int(row['a']),
|
|
194
|
+
'b': int(row['b']),
|
|
195
|
+
'c': int(row['c']),
|
|
196
|
+
'd': int(row['d'])
|
|
197
|
+
}
|
|
198
|
+
tables.append(table)
|
|
199
|
+
except ValueError as e:
|
|
200
|
+
logger.warning(f"Skipping row {row_num}: invalid data - {e}")
|
|
201
|
+
continue
|
|
202
|
+
|
|
203
|
+
except FileNotFoundError:
|
|
204
|
+
raise ValueError(f"Input file '{filepath}' not found")
|
|
205
|
+
except Exception as e:
|
|
206
|
+
raise ValueError(f"Error reading input file: {e}")
|
|
207
|
+
|
|
208
|
+
if not tables:
|
|
209
|
+
raise ValueError("No valid tables found in input file")
|
|
210
|
+
|
|
211
|
+
logger.info(f"Loaded {len(tables)} tables from {filepath}")
|
|
212
|
+
return tables
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def save_batch_results(results: List[Dict[str, Any]], filepath: Optional[str] = None,
|
|
216
|
+
format_type: str = 'csv') -> None:
|
|
217
|
+
"""
|
|
218
|
+
Save batch results to file or stdout.
|
|
219
|
+
|
|
220
|
+
Args:
|
|
221
|
+
results: List of result dictionaries
|
|
222
|
+
filepath: Output file path (None for stdout)
|
|
223
|
+
format_type: Output format ('csv', 'json', 'table')
|
|
224
|
+
"""
|
|
225
|
+
if format_type == 'json':
|
|
226
|
+
output = json.dumps(results, indent=2)
|
|
227
|
+
if filepath:
|
|
228
|
+
with open(filepath, 'w') as f:
|
|
229
|
+
f.write(output)
|
|
230
|
+
else:
|
|
231
|
+
print(output)
|
|
232
|
+
|
|
233
|
+
elif format_type == 'csv':
|
|
234
|
+
if not results:
|
|
235
|
+
return
|
|
236
|
+
|
|
237
|
+
fieldnames = list(results[0].keys())
|
|
238
|
+
|
|
239
|
+
if filepath:
|
|
240
|
+
with open(filepath, 'w', newline='') as csvfile:
|
|
241
|
+
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
|
242
|
+
writer.writeheader()
|
|
243
|
+
writer.writerows(results)
|
|
244
|
+
else:
|
|
245
|
+
writer = csv.DictWriter(sys.stdout, fieldnames=fieldnames)
|
|
246
|
+
writer.writeheader()
|
|
247
|
+
writer.writerows(results)
|
|
248
|
+
|
|
249
|
+
else: # table format
|
|
250
|
+
for result in results:
|
|
251
|
+
print(f"\nTable {result['id']}:")
|
|
252
|
+
print(f" Input: a={result['a']}, b={result['b']}, c={result['c']}, d={result['d']}")
|
|
253
|
+
print(f" Method: {result['method']}")
|
|
254
|
+
print(f" Odds Ratio: {result['odds_ratio']:.4f}")
|
|
255
|
+
print(f" CI: ({result['lower']:.4f}, {result['upper']:.4f})")
|
|
256
|
+
if 'error' in result:
|
|
257
|
+
print(f" Error: {result['error']}")
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def process_single_table(a: int, b: int, c: int, d: int, method: str, alpha: float,
|
|
261
|
+
grid_size: int, apply_haldane: bool, verbose: bool) -> None:
|
|
262
|
+
"""
|
|
263
|
+
Process a single table (original CLI functionality).
|
|
264
|
+
"""
|
|
265
|
+
try:
|
|
266
|
+
# Apply Haldane's correction if requested
|
|
267
|
+
if apply_haldane:
|
|
268
|
+
original_a, original_b, original_c, original_d = a, b, c, d
|
|
269
|
+
a, b, c, d = apply_haldane_correction(a, b, c, d)
|
|
270
|
+
if verbose:
|
|
271
|
+
print(f"Haldane's correction applied (or attempted):")
|
|
272
|
+
print(f" Original: a={original_a}, b={original_b}, c={original_c}, d={original_d}")
|
|
273
|
+
print(f" Resulting values for calculation: a={a}, b={b}, c={c}, d={d}")
|
|
274
|
+
|
|
275
|
+
# Validate counts
|
|
276
|
+
validate_counts_cli(a, b, c, d)
|
|
277
|
+
|
|
278
|
+
# Get the appropriate CI function
|
|
279
|
+
ci_function = METHOD_MAP[method]
|
|
280
|
+
|
|
281
|
+
# Calculate the odds ratio
|
|
282
|
+
odds_ratio = (a * d) / (b * c) if b * c > 0 else float('inf')
|
|
283
|
+
|
|
284
|
+
# Call the CI function with appropriate arguments
|
|
285
|
+
if method == "unconditional":
|
|
286
|
+
lower, upper = ci_function(a, b, c, d, alpha, grid_size=grid_size)
|
|
287
|
+
else:
|
|
288
|
+
lower, upper = ci_function(a, b, c, d, alpha)
|
|
289
|
+
|
|
290
|
+
# Print results
|
|
291
|
+
print("\nExactCIs Result:")
|
|
292
|
+
print(f"Method: {method.capitalize()}")
|
|
293
|
+
print(f"Input: a={a}, b={b}, c={c}, d={d}")
|
|
294
|
+
if apply_haldane:
|
|
295
|
+
print(f"Haldane's correction was requested.")
|
|
296
|
+
print(f" Values used for calculation: a={a}, b={b}, c={c}, d={d}")
|
|
297
|
+
print(f"Odds Ratio: {odds_ratio:.4f}")
|
|
298
|
+
print(f"{(1-alpha)*100:.1f}% Confidence Interval: ({lower:.4f}, {upper:.4f})")
|
|
299
|
+
|
|
300
|
+
if verbose:
|
|
301
|
+
print(f"\nInterval width: {upper - lower:.4f}")
|
|
302
|
+
print(f"Row totals: {a+b}, {c+d}")
|
|
303
|
+
print(f"Column totals: {a+c}, {b+d}")
|
|
304
|
+
print(f"Total observations: {a+b+c+d}")
|
|
305
|
+
|
|
306
|
+
except ValueError as e:
|
|
307
|
+
print(str(e), file=sys.stderr)
|
|
308
|
+
sys.exit(1)
|
|
309
|
+
except ZeroDivisionError:
|
|
310
|
+
print("Error: Division by zero occurred. Check that your data is appropriate.", file=sys.stderr)
|
|
311
|
+
sys.exit(1)
|
|
312
|
+
except Exception as e:
|
|
313
|
+
print(f"Unexpected error: {str(e)}", file=sys.stderr)
|
|
314
|
+
sys.exit(1)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def process_batch_tables(tables: List[Dict[str, Any]], method: str, alpha: float,
|
|
318
|
+
grid_size: int, apply_haldane: bool, workers: Optional[int] = None,
|
|
319
|
+
timeout: Optional[float] = None) -> List[Dict[str, Any]]:
|
|
320
|
+
"""
|
|
321
|
+
Process multiple tables in parallel.
|
|
322
|
+
|
|
323
|
+
Args:
|
|
324
|
+
tables: List of table dictionaries
|
|
325
|
+
method: CI method to use
|
|
326
|
+
alpha: Significance level
|
|
327
|
+
grid_size: Grid size for unconditional method
|
|
328
|
+
apply_haldane: Whether to apply Haldane's correction
|
|
329
|
+
workers: Number of parallel workers
|
|
330
|
+
timeout: Timeout in seconds for processing operations
|
|
331
|
+
|
|
332
|
+
Returns:
|
|
333
|
+
List of result dictionaries
|
|
334
|
+
"""
|
|
335
|
+
def process_table(table_data: Dict[str, Any]) -> Dict[str, Any]:
|
|
336
|
+
"""Process a single table and return results."""
|
|
337
|
+
table_id = table_data['id']
|
|
338
|
+
a, b, c, d = table_data['a'], table_data['b'], table_data['c'], table_data['d']
|
|
339
|
+
|
|
340
|
+
result = {
|
|
341
|
+
'id': table_id,
|
|
342
|
+
'a': a, 'b': b, 'c': c, 'd': d,
|
|
343
|
+
'method': method,
|
|
344
|
+
'alpha': alpha
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
try:
|
|
348
|
+
# Apply Haldane's correction if requested
|
|
349
|
+
if apply_haldane:
|
|
350
|
+
a, b, c, d = apply_haldane_correction(a, b, c, d)
|
|
351
|
+
result.update({'a_corrected': a, 'b_corrected': b, 'c_corrected': c, 'd_corrected': d})
|
|
352
|
+
|
|
353
|
+
# Validate counts
|
|
354
|
+
validate_counts(a, b, c, d)
|
|
355
|
+
|
|
356
|
+
# Get the appropriate CI function
|
|
357
|
+
ci_function = METHOD_MAP[method]
|
|
358
|
+
|
|
359
|
+
# Calculate the odds ratio
|
|
360
|
+
odds_ratio = (a * d) / (b * c) if b * c > 0 else float('inf')
|
|
361
|
+
|
|
362
|
+
# Call the CI function with appropriate arguments
|
|
363
|
+
if method == "unconditional":
|
|
364
|
+
lower, upper = ci_function(a, b, c, d, alpha, grid_size=grid_size)
|
|
365
|
+
else:
|
|
366
|
+
lower, upper = ci_function(a, b, c, d, alpha)
|
|
367
|
+
|
|
368
|
+
result.update({
|
|
369
|
+
'odds_ratio': odds_ratio,
|
|
370
|
+
'lower': lower,
|
|
371
|
+
'upper': upper,
|
|
372
|
+
'width': upper - lower
|
|
373
|
+
})
|
|
374
|
+
|
|
375
|
+
except Exception as e:
|
|
376
|
+
result['error'] = str(e)
|
|
377
|
+
result.update({
|
|
378
|
+
'odds_ratio': None,
|
|
379
|
+
'lower': None,
|
|
380
|
+
'upper': None,
|
|
381
|
+
'width': None
|
|
382
|
+
})
|
|
383
|
+
logger.warning(f"Error processing table {table_id}: {e}")
|
|
384
|
+
logger.debug(f"Full traceback for table {table_id}:\n{traceback.format_exc()}")
|
|
385
|
+
|
|
386
|
+
return result
|
|
387
|
+
|
|
388
|
+
# Determine number of workers
|
|
389
|
+
if workers is None:
|
|
390
|
+
workers = get_optimal_workers()
|
|
391
|
+
|
|
392
|
+
logger.info(f"Processing {len(tables)} tables with {workers} workers")
|
|
393
|
+
|
|
394
|
+
# Use parallel processing
|
|
395
|
+
from exactcis.utils.parallel import parallel_map
|
|
396
|
+
results = parallel_map(
|
|
397
|
+
process_table,
|
|
398
|
+
tables,
|
|
399
|
+
max_workers=workers,
|
|
400
|
+
force_processes=True,
|
|
401
|
+
timeout=timeout
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
return results
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def main(args: Optional[List[str]] = None) -> None:
|
|
408
|
+
"""
|
|
409
|
+
Main entry point for the CLI.
|
|
410
|
+
|
|
411
|
+
Args:
|
|
412
|
+
args: Command line arguments (defaults to sys.argv[1:])
|
|
413
|
+
"""
|
|
414
|
+
parsed_args = parse_args(args)
|
|
415
|
+
|
|
416
|
+
# Configure logging if verbose
|
|
417
|
+
if parsed_args.verbose:
|
|
418
|
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
|
419
|
+
|
|
420
|
+
alpha = parsed_args.alpha
|
|
421
|
+
method = parsed_args.method
|
|
422
|
+
|
|
423
|
+
if parsed_args.batch:
|
|
424
|
+
# Batch processing mode
|
|
425
|
+
try:
|
|
426
|
+
# Load tables from CSV
|
|
427
|
+
tables = load_batch_data(parsed_args.batch)
|
|
428
|
+
|
|
429
|
+
if parsed_args.verbose:
|
|
430
|
+
print(f"Processing {len(tables)} tables using {method} method...")
|
|
431
|
+
|
|
432
|
+
# Process tables in parallel
|
|
433
|
+
results = process_batch_tables(
|
|
434
|
+
tables=tables,
|
|
435
|
+
method=method,
|
|
436
|
+
alpha=alpha,
|
|
437
|
+
grid_size=parsed_args.grid_size,
|
|
438
|
+
apply_haldane=parsed_args.apply_haldane,
|
|
439
|
+
workers=parsed_args.workers,
|
|
440
|
+
timeout=parsed_args.timeout
|
|
441
|
+
)
|
|
442
|
+
|
|
443
|
+
# Save results
|
|
444
|
+
save_batch_results(results, parsed_args.output, parsed_args.format)
|
|
445
|
+
|
|
446
|
+
if parsed_args.verbose:
|
|
447
|
+
successful = sum(1 for r in results if 'error' not in r)
|
|
448
|
+
print(f"\nProcessed {len(results)} tables successfully: {successful}, errors: {len(results) - successful}")
|
|
449
|
+
|
|
450
|
+
except Exception as e:
|
|
451
|
+
print(f"Batch processing error: {e}", file=sys.stderr)
|
|
452
|
+
sys.exit(1)
|
|
453
|
+
else:
|
|
454
|
+
# Single table processing mode (original functionality)
|
|
455
|
+
process_single_table(
|
|
456
|
+
a=parsed_args.a, b=parsed_args.b, c=parsed_args.c, d=parsed_args.d,
|
|
457
|
+
method=method, alpha=alpha, grid_size=parsed_args.grid_size,
|
|
458
|
+
apply_haldane=parsed_args.apply_haldane, verbose=parsed_args.verbose
|
|
459
|
+
)
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
if __name__ == "__main__":
|
|
463
|
+
main()
|