Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathutils.py
More file actions
404 lines (335 loc) · 10.8 KB
/
Copy pathutils.py
File metadata and controls
404 lines (335 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
"""
Common utilities for Python benchmarks.
"""
import json
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
def compute_timing_stats(
timings: List[float],
exclude_first: bool = True,
) -> Dict[str, Any]:
"""
Compute timing statistics from a list of timing measurements.
Parameters
----------
timings : list of float
List of timing measurements in seconds.
exclude_first : bool
Whether to exclude the first measurement from statistics
(may be affected by warm-up effects).
Returns
-------
dict
Dictionary containing:
- raw_timings: All raw timing values
- n_reps: Number of replications (after exclusion)
- first_run_excluded: Whether first run was excluded
- first_run_seconds: The first timing value
- stats: Dictionary with mean, std, median, min, max
"""
if not timings:
return {
"raw_timings": [],
"n_reps": 0,
"first_run_excluded": False,
"first_run_seconds": None,
"stats": {},
}
first_run = timings[0]
analysis_timings = timings[1:] if exclude_first and len(timings) > 1 else timings
if len(analysis_timings) == 0:
analysis_timings = timings # Fall back if only one measurement
return {
"raw_timings": timings,
"n_reps": len(analysis_timings),
"first_run_excluded": exclude_first and len(timings) > 1,
"first_run_seconds": first_run,
"stats": {
"mean": float(np.mean(analysis_timings)),
"std": float(np.std(analysis_timings, ddof=1)) if len(analysis_timings) > 1 else 0.0,
"median": float(np.median(analysis_timings)),
"min": float(np.min(analysis_timings)),
"max": float(np.max(analysis_timings)),
},
}
@dataclass
class BenchmarkResult:
"""Container for benchmark results."""
estimator: str
att: float
se: float
timing_seconds: float
metadata: Dict[str, Any] = field(default_factory=dict)
extra: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for JSON serialization."""
return {
"estimator": self.estimator,
"att": self.att,
"se": self.se,
"timing": {"total_seconds": self.timing_seconds},
"metadata": self.metadata,
**self.extra,
}
def to_json(self, path: Path) -> None:
"""Write results to JSON file."""
with open(path, "w") as f:
json.dump(self.to_dict(), f, indent=2, default=_json_serializer)
def _json_serializer(obj):
"""Custom JSON serializer for numpy types."""
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, (np.integer, np.int64)):
return int(obj)
if isinstance(obj, (np.floating, np.float64)):
return float(obj)
if isinstance(obj, pd.DataFrame):
return obj.to_dict(orient="records")
raise TypeError(f"Object of type {type(obj)} is not JSON serializable")
class Timer:
"""Simple context manager for timing code blocks."""
def __init__(self):
self.start_time: Optional[float] = None
self.end_time: Optional[float] = None
self.elapsed: float = 0.0
def __enter__(self):
self.start_time = time.perf_counter()
return self
def __exit__(self, *args):
self.end_time = time.perf_counter()
self.elapsed = self.end_time - self.start_time
def generate_staggered_data(
n_units: int = 200,
n_periods: int = 8,
n_cohorts: int = 3,
treatment_effect: float = 2.0,
never_treated_frac: float = 0.3,
seed: int = 42,
) -> pd.DataFrame:
"""
Generate synthetic staggered adoption data for benchmarking.
Parameters
----------
n_units : int
Number of units.
n_periods : int
Number of time periods.
n_cohorts : int
Number of treatment cohorts (excluding never-treated).
treatment_effect : float
Base treatment effect.
never_treated_frac : float
Fraction of never-treated units.
seed : int
Random seed.
Returns
-------
pd.DataFrame
Panel data with columns: unit, time, outcome, first_treat, treated.
"""
rng = np.random.default_rng(seed)
# Assign units to cohorts
n_never_treated = int(n_units * never_treated_frac)
n_treated = n_units - n_never_treated
units_per_cohort = n_treated // n_cohorts
# Generate first treatment times (starting from period 3)
first_treat_times = []
for i in range(n_units):
if i < n_never_treated:
first_treat_times.append(0) # Never treated (coded as 0)
else:
cohort = (i - n_never_treated) // units_per_cohort
cohort = min(cohort, n_cohorts - 1)
first_treat_times.append(3 + cohort)
# Generate panel data
data = []
for unit in range(n_units):
unit_fe = rng.normal(0, 2)
first_treat = first_treat_times[unit]
for t in range(1, n_periods + 1):
time_fe = t * 0.5 # Linear time trend
# Treatment indicator
if first_treat == 0:
treated = 0
post = 0
else:
treated = 1
post = 1 if t >= first_treat else 0
# Dynamic treatment effect
if post == 1:
relative_time = t - first_treat
effect = treatment_effect * (1 + 0.1 * relative_time)
else:
effect = 0
outcome = unit_fe + time_fe + effect + rng.normal(0, 0.5)
data.append(
{
"unit": unit,
"time": t,
"outcome": outcome,
"first_treat": first_treat,
"treated": treated,
"post": post,
}
)
return pd.DataFrame(data)
def generate_basic_did_data(
n_units: int = 100,
n_periods: int = 4,
treatment_effect: float = 5.0,
treatment_period: int = 3,
seed: int = 42,
) -> pd.DataFrame:
"""
Generate basic 2x2 DiD data for benchmarking.
Parameters
----------
n_units : int
Number of units.
n_periods : int
Number of time periods.
treatment_effect : float
True treatment effect.
treatment_period : int
First post-treatment period.
seed : int
Random seed.
Returns
-------
pd.DataFrame
Panel data with columns: unit, time, outcome, treated, post.
"""
rng = np.random.default_rng(seed)
n_treated = n_units // 2
data = []
for unit in range(n_units):
unit_fe = rng.normal(0, 2)
treated = 1 if unit < n_treated else 0
for t in range(1, n_periods + 1):
time_fe = t * 0.5
post = 1 if t >= treatment_period else 0
effect = treatment_effect if (treated and post) else 0
outcome = unit_fe + time_fe + effect + rng.normal(0, 1)
data.append(
{
"unit": unit,
"time": t,
"outcome": outcome,
"treated": treated,
"post": post,
}
)
return pd.DataFrame(data)
def generate_sdid_data(
n_control: int = 40,
n_treated: int = 10,
n_pre: int = 15,
n_post: int = 5,
treatment_effect: float = 4.0,
seed: int = 42,
) -> pd.DataFrame:
"""
Generate data suitable for Synthetic DiD benchmarking.
Parameters
----------
n_control : int
Number of control units.
n_treated : int
Number of treated units.
n_pre : int
Number of pre-treatment periods.
n_post : int
Number of post-treatment periods.
treatment_effect : float
True treatment effect.
seed : int
Random seed.
Returns
-------
pd.DataFrame
Panel data with columns: unit, time, outcome, treated, post.
"""
rng = np.random.default_rng(seed)
n_units = n_control + n_treated
n_periods = n_pre + n_post
data = []
for unit in range(n_units):
unit_fe = rng.normal(0, 2)
treated = 1 if unit >= n_control else 0
for t in range(1, n_periods + 1):
time_fe = np.sin(t * 0.3) + t * 0.1 # Non-linear time trend
post = 1 if t > n_pre else 0
effect = treatment_effect if (treated and post) else 0
outcome = unit_fe + time_fe + effect + rng.normal(0, 0.5)
data.append(
{
"unit": unit,
"time": t,
"outcome": outcome,
"treated": treated,
"post": post,
}
)
return pd.DataFrame(data)
def generate_multiperiod_data(
n_units: int = 200,
n_pre: int = 4,
n_post: int = 4,
treatment_effect: float = 3.0,
treatment_fraction: float = 0.5,
seed: int = 42,
) -> pd.DataFrame:
"""
Generate synthetic multi-period event study data for benchmarking.
All treated units receive treatment simultaneously at the same time.
Parameters
----------
n_units : int
Number of units.
n_pre : int
Number of pre-treatment periods.
n_post : int
Number of post-treatment periods.
treatment_effect : float
True treatment effect in post-periods.
treatment_fraction : float
Fraction of units that are treated.
seed : int
Random seed.
Returns
-------
pd.DataFrame
Panel data with columns: unit, time, outcome, treated.
"""
rng = np.random.default_rng(seed)
n_treated = int(n_units * treatment_fraction)
n_periods = n_pre + n_post
data = []
for unit in range(n_units):
unit_fe = rng.normal(0, 2)
treated = 1 if unit < n_treated else 0
for t in range(1, n_periods + 1):
time_fe = t * 0.5
post = 1 if t > n_pre else 0
effect = treatment_effect if (treated and post) else 0
outcome = unit_fe + time_fe + effect + rng.normal(0, 1)
data.append(
{
"unit": unit,
"time": t,
"outcome": outcome,
"treated": treated,
}
)
return pd.DataFrame(data)
def load_benchmark_data(path: Path) -> pd.DataFrame:
"""Load benchmark data from CSV."""
return pd.read_csv(path)
def save_benchmark_data(data: pd.DataFrame, path: Path) -> None:
"""Save benchmark data to CSV."""
path.parent.mkdir(parents=True, exist_ok=True)
data.to_csv(path, index=False)
You can’t perform that action at this time.
