### Usage example: data generation and model setup Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-lplr.md Sets up learners and generates a DoubleMLData object with a binary instrument using make_lplr_LZZ2020. The data is used for fitting a DoubleMLLPLR model. ```python import numpy as np import doubleml as dml from doubleml.plm.datasets import make_lplr_LZZ2020 from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier np.random.seed(3141) ml_M = RandomForestClassifier(n_estimators=100, max_features=20, max_depth=5, min_samples_leaf=2) ml_t = RandomForestRegressor(n_estimators=100, max_features=20, max_depth=5, min_samples_leaf=2) ml_m = RandomForestRegressor(n_estimators=100, max_features=20, max_depth=5, min_samples_leaf=2) obj_dml_data = make_lplr_LZZ2020(n_obs=500, dim_x=20, treatment="binary") ``` -------------------------------- ### Install DoubleML from source Source: https://github.com/doubleml/doubleml-for-py/blob/main/README.md Clone the repository and install the package in editable mode. ```bash git clone git@github.com:DoubleML/doubleml-for-py.git cd doubleml-for-py pip install --editable . ``` -------------------------------- ### Install dependencies with uv Source: https://github.com/doubleml/doubleml-for-py/blob/main/CONTRIBUTING.md Recommended method to create a virtual environment and install DoubleML in editable mode. ```bash $ uv sync --extra rdd ``` -------------------------------- ### Install pre-commit hooks Source: https://github.com/doubleml/doubleml-for-py/blob/main/CONTRIBUTING.md Install pre-commit hooks to automate code quality checks. ```bash $ uv run pre-commit install # or, without uv: pre-commit install ``` -------------------------------- ### Install dependencies with pip Source: https://github.com/doubleml/doubleml-for-py/blob/main/CONTRIBUTING.md Alternative method to install DoubleML in editable mode using pip. ```bash $ pip install --editable ".[rdd]" --group dev ``` -------------------------------- ### Usage Examples Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml.md Example usage of DoubleMLPLR with sample splitting, fitting, and error handling. ```APIDOC ## Usage Examples ### Description Example usage of DoubleMLPLR with sample splitting, fitting, and error handling. ### Method N/A (Python code) ### Endpoint N/A (Python code) ### Parameters None ### Request Example ```python import numpy as np import doubleml as dml from doubleml.plm.datasets import make_plr_CCDDHNR2018 from sklearn.ensemble import RandomForestRegressor np.random.seed(3141) ml_l = RandomForestRegressor(n_estimators=100, max_depth=5, min_samples_leaf=2) ml_m = RandomForestRegressor(n_estimators=100, max_depth=5, min_samples_leaf=2) obj_dml_data = make_plr_CCDDHNR2018(alpha=0.5, n_obs=500, dim_x=20) dml_plr = dml.DoubleMLPLR(obj_dml_data, ml_l, ml_m, n_folds=3, n_rep=2) dml_plr.fit() print(dml_plr.summary) ci = dml_plr.confint(level=0.95) ``` ### Response #### Success Response Prints summary and returns confidence intervals. #### Response Example N/A ``` -------------------------------- ### Setup development environment with uv Source: https://github.com/doubleml/doubleml-for-py/blob/main/README.md Use uv to clone the repository and sync the environment including the rdd dependency group. ```bash git clone git@github.com:DoubleML/doubleml-for-py.git cd doubleml-for-py uv sync --extra rdd ``` -------------------------------- ### Install DoubleML via pip Source: https://github.com/doubleml/doubleml-for-py/blob/main/README.md Use this command to install the latest version of DoubleML using pip. ```bash pip install -U DoubleML ``` -------------------------------- ### Usage example: fitting and summary Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-lplr.md Fits the DoubleMLLPLR model on the generated data and prints the summary. This is the core fitting step after data preparation. ```python dml_lplr_obj = dml.DoubleMLLPLR(obj_dml_data, ml_M, ml_t, ml_m) dml_lplr_obj.fit() print(dml_lplr_obj.summary) ``` -------------------------------- ### Usage example with different approaches Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-plpr.md Demonstrates how to fit DoubleMLPLPR models using different transformation approaches and print the coefficients and standard errors. ```APIDOC ## Usage example with different approaches ### Description Demonstrates how to fit DoubleMLPLPR models using different transformation approaches and print the coefficients and standard errors. ### Method Fit ### Endpoint DoubleMLPLPR.fit() ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python for approach in ["cre_general", "cre_normal", "fd_exact", "wg_approx"]: model = dml.DoubleMLPLPR(obj_dml_data, ml_l, ml_m, approach=approach) model.fit() print(approach, model.coef, model.se) ``` ### Response #### Success Response (200) - **coef** (array) - Estimated coefficients. - **se** (array) - Standard errors. #### Response Example ```python print(approach, model.coef, model.se) ``` ### Error Handling - **ValueError** - If an invalid approach is provided. ``` -------------------------------- ### Basic usage of DoubleMLPLIV Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-pliv.md Example demonstrating how to initialize and fit a DoubleMLPLIV model using RandomForestRegressor for nuisance estimation. ```python import numpy as np import doubleml as dml from doubleml.plm.datasets import make_pliv_CHS2015 from sklearn.ensemble import RandomForestRegressor np.random.seed(3141) ml_l = RandomForestRegressor(n_estimators=100, max_features=20, max_depth=5, min_samples_leaf=2) ml_m = RandomForestRegressor(n_estimators=100, max_features=20, max_depth=5, min_samples_leaf=2) ml_r = RandomForestRegressor(n_estimators=100, max_features=20, max_depth=5, min_samples_leaf=2) obj_dml_data = make_pliv_CHS2015(n_obs=500, dim_x=20, dim_z=10) dml_pliv_obj = dml.DoubleMLPLIV(obj_dml_data, ml_l, ml_m, ml_r, n_folds=3) dml_pliv_obj.fit() print(dml_pliv_obj.summary) print(dml_pliv_obj.coef, dml_pliv_obj.se) ``` -------------------------------- ### Typical user workflow for PLR Source: https://github.com/doubleml/doubleml-for-py/blob/main/doc/diagrams/architecture.md Python example showing the standard steps to fit a PLR model: define the model, set learners, draw sample splitting, fit, and access results. The results are delegated to DoubleMLFramework via DoubleMLBase. ```python # 1. Define model (data + score) plr = PLR(obj_dml_data, score="partialling out") # 2. Set learners plr.set_learners(ml_l=RandomForestRegressor(), ml_m=RandomForestRegressor()) # 3. Draw sample splitting plr.draw_sample_splitting(n_folds=5, n_rep=1) # 4. Fit plr.fit() # 5. Results (delegated to DoubleMLFramework via DoubleMLBase) print(plr.summary) plr.confint() plr.bootstrap() ``` -------------------------------- ### Error Handling Example Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml.md Example showing error handling for tuning before fit and required ordering of fit before inference methods. ```APIDOC ## Error Handling Example ### Description Example showing error handling for tuning before fit and required ordering of fit before inference methods. ### Method N/A (Python code) ### Endpoint N/A (Python code) ### Parameters None ### Request Example ```python try: dml_plr2 = dml.DoubleMLPLR(obj_dml_data, ml_l, ml_m) dml_plr2.tune(param_grids={"ml_l": {"n_estimators": [10, 50]}}) # missing 'ml_m' key except ValueError as e: print("Invalid param_grids:", e) # Required ordering: fit() must precede inference methods try: dml_plr2.bootstrap() except AttributeError: pass ``` ### Response #### Success Response Prints error message for invalid param_grids and catches AttributeError for bootstrap before fit. #### Response Example N/A ``` -------------------------------- ### Basic DoubleMLIRM Usage Example Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-irm.md A standard workflow for initializing and fitting a DoubleMLIRM model using Random Forest learners. ```python import numpy as np import doubleml as dml from doubleml.irm.datasets import make_irm_data from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier np.random.seed(3141) ml_g = RandomForestRegressor(n_estimators=100, max_features=20, max_depth=5, min_samples_leaf=2) ml_m = RandomForestClassifier(n_estimators=100, max_features=20, max_depth=5, min_samples_leaf=2) obj_dml_data = make_irm_data(theta=0.5, n_obs=500, dim_x=20) dml_irm_obj = dml.DoubleMLIRM(obj_dml_data, ml_g, ml_m) dml_irm_obj.fit() print(dml_irm_obj.summary) print(dml_irm_obj.confint().to_string()) ``` -------------------------------- ### Create a minimum reproducible code snippet Source: https://github.com/doubleml/doubleml-for-py/blob/main/CONTRIBUTING.md Use this template to provide a self-contained example that reproduces the bug you are reporting. ```python import numpy as np import doubleml as dml from doubleml.plm.datasets import make_plr_CCDDHNR2018 from sklearn.ensemble import RandomForestRegressor from sklearn.base import clone np.random.seed(3141) ml_g = RandomForestRegressor(n_estimators=100, max_features=20, max_depth=5, min_samples_leaf=2) ml_m = RandomForestRegressor(n_estimators=100, max_features=20, max_depth=5, min_samples_leaf=2) obj_dml_data = make_plr_CCDDHNR2018(alpha=0.5, n_obs=500, dim_x=20) dml_plr_obj = dml.DoubleMLPLR(obj_dml_data, ml_g, ml_m) dml_plr_obj.fit().summary ``` -------------------------------- ### Usage example: DoubleMLPLR with sample splitting Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml.md Shows how to create a DoubleMLPLR model with n_folds=3 and n_rep=2, fit it, print the summary, and compute confidence intervals. ```python import numpy as np import doubleml as dml from doubleml.plm.datasets import make_plr_CCDDHNR2018 from sklearn.ensemble import RandomForestRegressor np.random.seed(3141) ml_l = RandomForestRegressor(n_estimators=100, max_depth=5, min_samples_leaf=2) ml_m = RandomForestRegressor(n_estimators=100, max_depth=5, min_samples_leaf=2) obj_dml_data = make_plr_CCDDHNR2018(alpha=0.5, n_obs=500, dim_x=20) dml_plr = dml.DoubleMLPLR(obj_dml_data, ml_l, ml_m, n_folds=3, n_rep=2) dml_plr.fit() print(dml_plr.summary) ci = dml_plr.confint(level=0.95) ``` -------------------------------- ### Handle Missing Dependencies Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-rdd.md Provides a check for the optional rdrobust dependency and instructions for installation. ```python try: import rdrobust # noqa except ImportError: print("Install with: pip install DoubleML[rdd]") ``` -------------------------------- ### Initialize DoubleMLData from DataFrames and arrays Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-data.md Examples of creating a DoubleMLData object from a pandas DataFrame and from numpy arrays. ```python import numpy as np import doubleml as dml from doubleml.plm.datasets import make_plr_CCDDHNR2018 import pandas as pd # From DataFrame data = make_plr_CCDDHNR2018(n_obs=200, dim_x=10, return_type="DataFrame") obj_dml_data = dml.DoubleMLData(data, y_col="y", d_cols="d") print(obj_dml_data.x.shape, obj_dml_data.n_obs, obj_dml_data.binary_treats["d"]) # From arrays, with instruments as well (x, y, d) = make_plr_CCDDHNR2018(return_type="array") obj_from_arrays = dml.DoubleMLData.from_arrays(x, y, d, force_all_x_finite="allow-nan") ``` -------------------------------- ### Usage examples for DID, panel, RDD, and SSM data Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/specialized-data.md Shows how to create DoubleMLDIDData, DoubleMLPanelData, DoubleMLRDDData, and DoubleMLSSMData objects using dataset generators. Includes printing panel data attributes and constructing RDD/SSM data from arrays. ```python import doubleml as dml from doubleml.did.datasets import make_did_SZ2020 from doubleml.plm.datasets import make_plpr_CP2025 from doubleml.rdd.datasets import make_simple_rdd_data from doubleml.irm.datasets import make_ssm_data # DID panel data (two periods) df = make_did_SZ2020(n_obs=200, return_type="DataFrame") did_data = dml.DoubleMLDIDData(df, y_col="y", d_cols="d", t_col="t") # Panel data for staggered adoption panel_df = make_plpr_CP2025(num_id=50, num_t=4) panel_data = dml.DoubleMLPanelData( panel_df, y_col="y", d_cols="g", t_col="t", id_col="id", x_cols=[c for c in panel_df.columns if c.startswith("X")] ) print(panel_data.g_values, panel_data.t_values, panel_data.n_ids) # RDD and SSM backends rdd_dict = make_simple_rdd_data(fuzzy=False, n_obs=1000) rdd_data = dml.DoubleMLRDDData.from_arrays(x=rdd_dict["X"], y=rdd_dict["Y"], d=rdd_dict["D"], score=rdd_dict["score"]) ssm_dict = make_ssm_data(n_obs=2000, return_type="array") ssm_data = dml.DoubleMLSSMData.from_arrays(x=ssm_dict["x"], y=ssm_dict["y"], d=ssm_dict["d"], s=ssm_dict["s"]) ``` -------------------------------- ### DoubleMLBLP Usage Example Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/utils.md Example of using DoubleMLBLP for CATE evaluation after fitting a PLR model. Requires a fitted PLR with stored predictions. ```APIDOC ## DoubleMLBLP Usage Example ### Description Example of using DoubleMLBLP to evaluate CATE after fitting a PLR model. Requires a fitted PLR with stored predictions. ### Code Example ```python import numpy as np import pandas as pd import doubleml as dml from doubleml.utils import DoubleMLBLP from doubleml.plm.datasets import make_plr_CCDDHNR2018 from sklearn.ensemble import RandomForestRegressor np.random.seed(3141) ml = RandomForestRegressor(n_estimators=10, max_depth=2) data = make_plr_CCDDHNR2018(n_obs=100, alpha=0.5) model = dml.DoubleMLPLR(data, ml, ml).fit() Y_tilde, D_tilde = model._partial_out() # internal helpers of DoubleMLPLR basis = pd.DataFrame({"X1": data.data["X1"], "X1_sq": data.data["X1"] ** 2}) blp = DoubleMLBLP(orth_signal=Y_tilde, basis=basis) blp.fit(cov_type="HC1") print(blp.summary) print(blp.confint().to_string()) ``` ``` -------------------------------- ### DoubleMLData Usage Examples Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-data.md Examples of creating DoubleMLData objects from a DataFrame and from arrays, including handling of instruments and validation of disjoint column sets. ```APIDOC ## DoubleMLData Usage Examples ### Description Examples of creating DoubleMLData objects from a DataFrame and from arrays, including handling of instruments and validation of disjoint column sets. ### Example 1: From DataFrame ```python import numpy as np import doubleml as dml from doubleml.plm.datasets import make_plr_CCDDHNR2018 import pandas as pd data = make_plr_CCDDHNR2018(n_obs=200, dim_x=10, return_type="DataFrame") obj_dml_data = dml.DoubleMLData(data, y_col="y", d_cols="d") print(obj_dml_data.x.shape, obj_dml_data.n_obs, obj_dml_data.binary_treats["d"]) ``` ### Example 2: From arrays with instruments ```python (x, y, d) = make_plr_CCDDHNR2018(return_type="array") obj_from_arrays = dml.DoubleMLData.from_arrays(x, y, d, force_all_x_finite="allow-nan") ``` ### Example 3: Error handling - disjoint column validation ```python df = pd.DataFrame({"y": [1, 2], "d": [0, 1], "z": [5, 6]}) try: dml.DoubleMLData(df, y_col="y", d_cols="d", x_cols=["z"], z_cols=["z"]) except ValueError as e: print("Sets must be disjoint:", e) # x_cols and z_cols overlap ``` ``` -------------------------------- ### DoubleMLPQ.__init__ Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-irm-effect-models.md Constructor for the DoubleMLPQ class, which estimates potential quantiles. It initializes the model with data, machine learners, and configuration parameters. ```APIDOC ## DoubleMLPQ.__init__ ### Description Constructor for the DoubleMLPQ class, which estimates potential quantiles. It initializes the model with data, machine learners, and configuration parameters. ### Method Constructor ### Signature ```python def __init__( self, obj_dml_data, ml_g, ml_m, treatment=1, quantile=0.5, n_folds=5, n_rep=1, score="PQ", normalize_ipw=True, kde=None, trimming_rule="truncate", trimming_threshold=1e-2, ps_processor_config: Optional[PSProcessorConfig] = None, draw_sample_splitting=True, ): ``` ### Parameters - **obj_dml_data** (object) - Required - Data object for DoubleML. - **ml_g** (object) - Required - Machine learner for the outcome regression. - **ml_m** (object) - Required - Machine learner for the propensity score. - **treatment** (scalar) - Optional - Treatment level (validated by `_check_treatment`). Default: `1`. - **quantile** (float) - Optional - Quantile in `(0, 1)` (validated by `_check_quantile`). Default: `0.5`. - **n_folds** (int) - Optional - Number of folds. Default: `5`. - **n_rep** (int) - Optional - Number of repetitions. Default: `1`. - **score** (str) - Optional - Score type. Default: `"PQ"`. - **normalize_ipw** (bool) - Optional - Normalize IPW. Default: `True`. - **kde** (callable or None) - Optional - Kernel-density estimator `kde(u, weights)`; defaults to `_default_kde`. Default: `None`. - **trimming_rule** (str) - Optional - Trimming rule. Default: `"truncate"`. - **trimming_threshold** (float) - Optional - Trimming threshold. Default: `1e-2`. - **ps_processor_config** (Optional[PSProcessorConfig]) - Optional - Propensity score processor configuration. Default: `None`. - **draw_sample_splitting** (bool) - Optional - Whether to draw sample splitting. Default: `True`. ### Notes Non-linear score (`NonLinearScoreMixin`): the root of the quantile moment condition is found numerically with bracketing (`_solve_ipw_score`). Inherits `DoubleML` methods. ``` -------------------------------- ### Generate API documentation locally Source: https://github.com/doubleml/doubleml-for-py/blob/main/CONTRIBUTING.md Commands to build the API documentation locally using Sphinx. Requires the sphinx and pydata-sphinx-theme development dependencies. ```bash $ cd doc/ $ make html ``` -------------------------------- ### DoubleMLVector.get_params Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-scalar-vector.md Gets parameters for a specified learner. ```APIDOC ## DoubleMLVector.get_params ### Description Gets parameters for a specified learner. ### Method get_params ### Signature ```python get_params(self, learner_name) -> list[dict] ``` ### Parameters - **learner_name** - Required - The name of the learner. ### Returns - **list[dict]** - List of parameter dictionaries. ``` -------------------------------- ### DoubleMLDIDData.t_col property Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/specialized-data.md Property to get or set the time-period column name. ```APIDOC ## DoubleMLDIDData.t_col property ### Description Gets or sets the time-period column name. ### Method Property (getter/setter) ### Endpoint DoubleMLDIDData.t_col ### Parameters #### Setter Parameters - **value** (str) - Required - The new time-period column name. ### Request Example ```python did_data.t_col = 'period' ``` ### Response #### Success Response Returns the current time-period column name (str). #### Response Example ```python 't' ``` ``` -------------------------------- ### Run unit tests Source: https://github.com/doubleml/doubleml-for-py/blob/main/CONTRIBUTING.md Execute the test suite to ensure code quality. ```bash $ uv run pytest . # or, without uv: pytest . ``` -------------------------------- ### Basic DoubleMLIIVM fitting with random forests Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-iivm.md Sets up a DoubleMLIIVM model using random forest learners for g, m, and r, generates data with make_iivm_data, fits the model, and prints the summary. ```python import numpy as np import doubleml as dml from doubleml.irm.datasets import make_iivm_data from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier np.random.seed(3141) ml_g = RandomForestRegressor(n_estimators=100, max_features=20, max_depth=5, min_samples_leaf=2) ml_m = RandomForestClassifier(n_estimators=100, max_features=20, max_depth=5, min_samples_leaf=2) ml_r = RandomForestClassifier(n_estimators=100, max_features=20, max_depth=5, min_samples_leaf=2) obj_dml_data = make_iivm_data(n_obs=500, dim_x=20, theta=1.0) dml_iivm_obj = dml.DoubleMLIIVM(obj_dml_data, ml_g, ml_m, ml_r) dml_iivm_obj.fit() print(dml_iivm_obj.summary) ``` -------------------------------- ### DoubleMLPLR basic usage Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-plr.md Example of initializing and fitting a DoubleMLPLR model using RandomForestRegressor. ```python import numpy as np import doubleml as dml from doubleml.plm.datasets import make_plr_CCDDHNR2018 from sklearn.ensemble import RandomForestRegressor np.random.seed(3141) ml_l = RandomForestRegressor(n_estimators=100, max_features=20, max_depth=5, min_samples_leaf=2) ml_m = RandomForestRegressor(n_estimators=100, max_features=20, max_depth=5, min_samples_leaf=2) obj_dml_data = make_plr_CCDDHNR2018(alpha=0.5, n_obs=500, dim_x=20) dml_plr_obj = dml.DoubleMLPLR(obj_dml_data, ml_l, ml_m) dml_plr_obj.fit() print(dml_plr_obj.summary) print(dml_plr_obj.confint().to_string()) ``` -------------------------------- ### DoubleMLPolicyTree Usage Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/utils.md Example of using DoubleMLPolicyTree to estimate policy trees based on CATE signals. ```python cate_signal = model.coef[0] * np.abs(D_tilde[:, 0]) tree = DoubleMLPolicyTree(orth_signal=cate_signal, features=data.data[["X1"]]) tree.fit() print(tree.predict(data.data[["X1"]])[:5]) ``` -------------------------------- ### PSProcessor.__init__ Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/utils.md Constructor for the PSProcessor class. Initializes the processor with clipping, extreme threshold, and calibration settings. ```APIDOC ## PSProcessor.__init__ ### Description Initializes a PSProcessor instance with the given configuration parameters. ### Method Constructor ### Signature ```python def __init__( self, clipping_threshold: float = 1e-2, extreme_threshold: float = 1e-12, calibration_method: Optional[str] = None, cv_calibration: bool = False, ): ``` ### Parameters - **clipping_threshold** (float) - Optional - Bounds the propensity scores to [clipping_threshold, 1 - clipping_threshold]. Must be in (0, 0.5). - **extreme_threshold** (float) - Optional - Threshold for issuing warnings when scores are close to 0 or 1. Must be in (0, 0.5). - **calibration_method** (Optional[str]) - Optional - Either None or 'isotonic' to enable isotonic calibration. - **cv_calibration** (bool) - Optional - If True, enables cross-validated calibration. Requires a calibration method, otherwise raises ValueError. ### Usage Create an instance directly or via PSProcessor.from_config(). ``` -------------------------------- ### DoubleMLLPQ.__init__ Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-irm-effect-models.md Constructor for the DoubleMLLPQ class, which estimates local potential quantiles. It is identical to DoubleMLPQ except the score is set to "LPQ". ```APIDOC ## DoubleMLLPQ.__init__ ### Description Constructor for the DoubleMLLPQ class, which estimates local potential quantiles. It is identical to DoubleMLPQ except the score is set to "LPQ". ### Method Constructor ### Signature Identical to `DoubleMLPQ.__init__` except `score="LPQ"`. ### Parameters Same as `DoubleMLPQ.__init__`. ### Notes Non-linear score; estimation via `_solve_ipw_score` with a starting bracket guess. ``` -------------------------------- ### Handle disjoint column validation errors Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-data.md Example demonstrating how to catch a ValueError when x_cols and z_cols overlap in DoubleMLData. ```python df = pd.DataFrame({"y": [1, 2], "d": [0, 1], "z": [5, 6]}) try: dml.DoubleMLData(df, y_col="y", d_cols="d", x_cols=["z"], z_cols=["z"]) except ValueError as e: print("Sets must be disjoint:", e) # x_cols and z_cols overlap ``` -------------------------------- ### Implement DoubleMLDIDMulti and aggregation Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-did.md Demonstrates initializing a DoubleMLDIDMulti model with panel data, fitting the model, and performing group and event study aggregations. ```python import numpy as np import doubleml as dml from doubleml.did.datasets import make_did_CS2021 from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier np.random.seed(42) ml_g = RandomForestRegressor(n_estimators=100, max_depth=5, min_samples_leaf=5) ml_m = RandomForestClassifier(n_estimators=100, max_depth=5, min_samples_leaf=5) panel_df = make_did_CS2021(n_obs=500, dgp_type=1, time_type="int") obj_dml_data = dml.DoubleMLPanelData( panel_df, y_col="y", d_cols="g", t_col="t", id_col="id", x_cols=[c for c in panel_df.columns if c.startswith("X")], ) dml_did_multi = dml.DoubleMLDIDMulti(obj_dml_data, ml_g, ml_m, control_group="not_yet_treated") dml_did_multi.fit() print(dml_did_multi.summary) # group aggregation / event study agg_obj = dml_did_multi.aggregate(aggregation="group") print(agg_obj.aggregated_summary) event_study = dml_did_multi.aggregate(aggregation="eventstudy") ``` -------------------------------- ### PSProcessor Propensity Score Clipping Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/utils.md Example of using PSProcessor to adjust propensity scores by clipping them to a specified threshold range. ```python processor = PSProcessor(clipping_threshold=0.01) adj = processor.adjust_ps(propensity_scores=np.array([0.001, 0.2, 0.999]), treatment=np.array([0, 1, 1])) print(adj) # clipped to [0.01, 0.99] ``` -------------------------------- ### DoubleMLFramework.__init__ Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-framework.md Initializes a DoubleMLFramework instance, aggregating coefficients and standard errors over repetitions and setting up sensitivity and bootstrap state. ```APIDOC ## DoubleMLFramework.__init__ ### Description Initializes a DoubleMLFramework instance, aggregating coefficients and standard errors over repetitions and setting up sensitivity and bootstrap state. ### Method Constructor ### Signature ```python def __init__( self, dml_core: DoubleMLCore, treatment_names: Optional[List[str]] = None, ): ``` ### Parameters - **dml_core** (DoubleMLCore) - Required - Underlying core object. - **treatment_names** (Optional[List[str]]) - Optional - Labels for results; length must equal n_thetas. Can be set later via the treatment_names setter. ### Notes - Aggregates coefficients and standard errors over repetitions via _aggregate_coefs_and_ses. - Initializes sensitivity and bootstrap state. ``` -------------------------------- ### Load real datasets and generate PLR/PLIV data Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/datasets.md Shows how to load real datasets like 401K and bonus via `fetch_401K` and `fetch_bonus`, create synthetic PLR data with `make_plr_CCDDHNR2018`, and generate PLIV data with `make_pliv_CHS2015`. Use `return_type='array'` for raw arrays or `DoubleMLData.from_arrays` to construct data object. ```python import numpy as np import doubleml as dml from doubleml.datasets import fetch_401K, fetch_bonus from doubleml.plm.datasets import make_plr_CCDDHNR2018, make_pliv_CHS2015, make_plr_turrell2018 # Real data as DoubleMLData / DataFrame / raw arrays dml_401k = fetch_401K(return_type="DoubleMLData") print(dml_401k.y_col, dml_401k.d_cols, dml_401k.x_cols) (x, y, d) = make_plr_CCDDHNR2018(n_obs=300, dim_x=10, alpha=0.5, return_type="array") data_from_arrays = dml.DoubleMLData.from_arrays(x, y, d) # DGP for IV models pliv_data = make_pliv_CHS2015(n_obs=400, dim_x=100, dim_z=20) print(pliv_data.z_cols) # instrument columns ``` -------------------------------- ### DoubleMLPLR classifier misuse error handling Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-plr.md Example demonstrating how the model handles incorrect usage, such as passing a classifier for a non-binary treatment. ```python from sklearn.ensemble import RandomForestClassifier try: dml.DoubleMLPLR(obj_dml_data, ml_l, RandomForestClassifier()) # non-binary treatment except ValueError as e: print("Classifier misuse detected:", e) ``` -------------------------------- ### Implement Sharp RDD Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-rdd.md Shows how to configure a sharp RDD model by setting fuzzy=False and ml_m=None. ```python data_sharp = make_simple_rdd_data(fuzzy=False) obj_sharp = dml.DoubleMLRDDData.from_arrays( x=data_sharp["X"], y=data_sharp["Y"], d=data_sharp["D"], score=data_sharp["score"] ) rdflex_sharp = dml.rdd.RDFlex(obj_sharp, ml_g, ml_m=None, fuzzy=False) rdflex_sharp.fit() ``` -------------------------------- ### DoubleMLPLR IV-type score and GATE Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-plr.md Example using an IV-type score with an additional nuisance parameter ml_g, bootstrapping, and GATE estimation. ```python ml_g = RandomForestRegressor(n_estimators=100, max_features=20, max_depth=5, min_samples_leaf=2) dml_plr_iv = dml.DoubleMLPLR(obj_dml_data, ml_l, ml_m, ml_g=ml_g, score="IV-type") dml_plr_iv.fit().bootstrap(method="normal", n_rep_boot=500) groups = pd.DataFrame({"female": obj_dml_data.data["X1"] > 0, "male": obj_dml_data.data["X1"] <= 0}) gate_model = dml_plr_iv.gate(groups, cov_type="HC1") print(gate_model.summary) ``` -------------------------------- ### DoubleMLQTE.__init__ Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-irm-effect-models.md Constructor for the DoubleMLQTE class, which estimates quantile treatment effects. It composes per-quantile models for each quantile in `quantiles`. ```APIDOC ## DoubleMLQTE.__init__ ### Description Constructor for the DoubleMLQTE class, which estimates quantile treatment effects. It composes per-quantile models for each quantile in `quantiles`. ### Method Constructor ### Signature ```python def __init__( self, obj_dml_data, ml_g, ml_m=None, quantiles=0.5, n_folds=5, n_rep=1, score="PQ", normalize_ipw=True, kde=None, trimming_rule="truncate", trimming_threshold=1e-2, ps_processor_config: Optional[PSProcessorConfig] = None, draw_sample_splitting=True, ): ``` ### Parameters - **obj_dml_data** (object) - Required - Data object for DoubleML. - **ml_g** (object) - Required - Machine learner for the outcome regression. - **ml_m** (object or None) - Optional - Machine learner for the propensity score. Default: `None`. Must be a classifier for the `'PQ'`/`'LPQ'`/`'CVaR'` scores. - **quantiles** (scalar or array) - Optional - Quantile(s) at which to estimate QTE. Default: `0.5`. - **n_folds** (int) - Optional - Number of folds. Default: `5`. - **n_rep** (int) - Optional - Number of repetitions. Default: `1`. - **score** (str) - Optional - Score type, one of `'PQ'`, `'LPQ'`, `'CVaR'`. Default: `"PQ"`. - **normalize_ipw** (bool) - Optional - Normalize IPW. Default: `True`. - **kde** (callable or None) - Optional - Kernel-density estimator. Default: `None`. - **trimming_rule** (str) - Optional - Trimming rule. Default: `"truncate"`. - **trimming_threshold** (float) - Optional - Trimming threshold. Default: `1e-2`. - **ps_processor_config** (Optional[PSProcessorConfig]) - Optional - Propensity score processor configuration. Default: `None`. - **draw_sample_splitting** (bool) - Optional - Whether to draw sample splitting. Default: `True`. ### Notes Estimates `QTE(τ) = Q₁(τ) − Q₀(τ)` for each quantile in `quantiles`. The class composes per-quantile models; `fit(n_jobs_models=None, n_jobs_cv=None, store_predictions=True, store_models=False, external_predictions=None)` runs quantiles in parallel and combines frameworks via subtraction + `concat`. `external_predictions` raise `NotImplementedError`. ``` -------------------------------- ### IV-type score usage with ml_g Source: https://github.com/doubleml/doubleml-for-py/blob/main/_autodocs/api-reference/double-ml-pliv.md Example showing how to use the IV-type score, which requires an additional learner ml_g for the nuisance function g₀. ```python ml_g = RandomForestRegressor(n_estimators=100, max_depth=5, min_samples_leaf=2) dml_pliv_iv = dml.DoubleMLPLIV(obj_dml_data, ml_l, ml_m, ml_r, ml_g=ml_g, score="IV-type") dml_pliv_iv.fit() print(dml_pliv_iv.pval) ```