|
| 1 | +import warnings |
| 2 | +from typing import Any, Dict, Optional |
| 3 | + |
| 4 | +import doubleml as dml |
| 5 | +from doubleml.plm.datasets import make_lplr_LZZ2020 |
| 6 | + |
| 7 | +from montecover.base import BaseSimulation |
| 8 | +from montecover.utils import create_learner_from_config |
| 9 | + |
| 10 | + |
| 11 | +class LPLRATECoverageSimulation(BaseSimulation): |
| 12 | + """Simulation class for coverage properties of DoubleMLPLR for ATE estimation.""" |
| 13 | + |
| 14 | + def __init__( |
| 15 | + self, |
| 16 | + config_file: str, |
| 17 | + suppress_warnings: bool = True, |
| 18 | + log_level: str = "INFO", |
| 19 | + log_file: Optional[str] = None, |
| 20 | + use_failed_scores: bool = False, |
| 21 | + ): |
| 22 | + super().__init__( |
| 23 | + config_file=config_file, |
| 24 | + suppress_warnings=suppress_warnings, |
| 25 | + log_level=log_level, |
| 26 | + log_file=log_file, |
| 27 | + ) |
| 28 | + |
| 29 | + # Calculate oracle values |
| 30 | + self._calculate_oracle_values() |
| 31 | + |
| 32 | + self._use_failed_scores = use_failed_scores |
| 33 | + |
| 34 | + def _process_config_parameters(self): |
| 35 | + """Process simulation-specific parameters from config""" |
| 36 | + # Process ML models in parameter grid |
| 37 | + assert "learners" in self.dml_parameters, "No learners specified in the config file" |
| 38 | + |
| 39 | + required_learners = ["ml_m", "ml_M", "ml_t"] |
| 40 | + for learner in self.dml_parameters["learners"]: |
| 41 | + for ml in required_learners: |
| 42 | + assert ml in learner, f"No {ml} specified in the config file" |
| 43 | + |
| 44 | + def _calculate_oracle_values(self): |
| 45 | + """Calculate oracle values for the simulation.""" |
| 46 | + self.logger.info("Calculating oracle values") |
| 47 | + |
| 48 | + self.oracle_values = dict() |
| 49 | + self.oracle_values["theta"] = self.dgp_parameters["theta"] |
| 50 | + |
| 51 | + def run_single_rep(self, dml_data, dml_params) -> Dict[str, Any]: |
| 52 | + """Run a single repetition with the given parameters.""" |
| 53 | + # Extract parameters |
| 54 | + learner_config = dml_params["learners"] |
| 55 | + learner_m_name, ml_m = create_learner_from_config(learner_config["ml_m"]) |
| 56 | + learner_M_name, ml_M = create_learner_from_config(learner_config["ml_M"]) |
| 57 | + learner_t_name, ml_t = create_learner_from_config(learner_config["ml_t"]) |
| 58 | + score = dml_params["score"] |
| 59 | + |
| 60 | + # Model |
| 61 | + dml_model = dml.DoubleMLLPLR( |
| 62 | + obj_dml_data=dml_data, |
| 63 | + ml_m=ml_m, |
| 64 | + ml_M=ml_M, |
| 65 | + ml_t=ml_t, |
| 66 | + score=score, |
| 67 | + error_on_convergence_failure= not self._use_failed_scores,) |
| 68 | + |
| 69 | + try: |
| 70 | + dml_model.fit() |
| 71 | + except RuntimeError as e: |
| 72 | + self.logger.info(f"Exception during fit: {e}") |
| 73 | + return None |
| 74 | + |
| 75 | + result = { |
| 76 | + "coverage": [], |
| 77 | + } |
| 78 | + for level in self.confidence_parameters["level"]: |
| 79 | + level_result = dict() |
| 80 | + level_result["coverage"] = self._compute_coverage( |
| 81 | + thetas=dml_model.coef, |
| 82 | + oracle_thetas=self.oracle_values["theta"], |
| 83 | + confint=dml_model.confint(level=level), |
| 84 | + joint_confint=None, |
| 85 | + ) |
| 86 | + |
| 87 | + # add parameters to the result |
| 88 | + for res in level_result.values(): |
| 89 | + res.update( |
| 90 | + { |
| 91 | + "Learner m": learner_m_name, |
| 92 | + "Learner M": learner_M_name, |
| 93 | + "Learner t": learner_t_name, |
| 94 | + "Score": score, |
| 95 | + "level": level, |
| 96 | + } |
| 97 | + ) |
| 98 | + for key, res in level_result.items(): |
| 99 | + result[key].append(res) |
| 100 | + |
| 101 | + return result |
| 102 | + |
| 103 | + def summarize_results(self): |
| 104 | + """Summarize the simulation results.""" |
| 105 | + self.logger.info("Summarizing simulation results") |
| 106 | + |
| 107 | + # Group by parameter combinations |
| 108 | + groupby_cols = ["Learner m", "Learner M", "Learner t", "Score", "level"] |
| 109 | + aggregation_dict = { |
| 110 | + "Coverage": "mean", |
| 111 | + "CI Length": "mean", |
| 112 | + "Bias": "mean", |
| 113 | + "repetition": "count", |
| 114 | + } |
| 115 | + |
| 116 | + # Aggregate results (possibly multiple result dfs) |
| 117 | + result_summary = dict() |
| 118 | + for result_name, result_df in self.results.items(): |
| 119 | + result_summary[result_name] = result_df.groupby(groupby_cols).agg(aggregation_dict).reset_index() |
| 120 | + self.logger.debug(f"Summarized {result_name} results") |
| 121 | + |
| 122 | + return result_summary |
| 123 | + |
| 124 | + def _generate_dml_data(self, dgp_params) -> dml.DoubleMLData: |
| 125 | + """Generate data for the simulation.""" |
| 126 | + return make_lplr_LZZ2020(**dgp_params) |
0 commit comments