|
| 1 | +from typing import Optional, Union, Type, List |
| 2 | + |
| 3 | +import click |
| 4 | +import pandas as pd |
| 5 | +from pandas_genomics import GenotypeDtype |
| 6 | + |
| 7 | +from clarite.modules.analyze import regression |
| 8 | +from clarite.modules.analyze.regression import ( |
| 9 | + builtin_regression_kinds, |
| 10 | + WeightedGLMRegression, |
| 11 | + GLMRegression, |
| 12 | +) |
| 13 | + |
| 14 | + |
| 15 | +def association_study( |
| 16 | + data: pd.DataFrame, |
| 17 | + outcomes: Union[str, List[str]], |
| 18 | + regression_variables: Optional[Union[str, List[str]]] = None, |
| 19 | + covariates: Optional[Union[str, List[str]]] = None, |
| 20 | + regression_kind: Optional[Union[str, Type[regression.Regression]]] = None, |
| 21 | + encoding: str = "additive", |
| 22 | + weighted_encoding_info: Optional[pd.DataFrame] = None, |
| 23 | + **kwargs, |
| 24 | +): |
| 25 | + """ |
| 26 | + Run an association study (EWAS, PhEWAS, GWAS, GxEWAS, etc) |
| 27 | +
|
| 28 | + Individual regression classes selected with `regression_kind` may work slightly differently. |
| 29 | + Results are sorted in order of increasing `pvalue` |
| 30 | +
|
| 31 | + Parameters |
| 32 | + ---------- |
| 33 | + data: pd.DataFrame |
| 34 | + Contains all outcomes, regression_variables, and covariates |
| 35 | + outcomes: str or List[str] |
| 36 | + The exogenous variable (str) or variables (List) to be used as the output of each regression. |
| 37 | + regression_variables: str, List[str], or None |
| 38 | + The endogenous variable (str) or variables (List) to be used invididually as inputs into regression. |
| 39 | + If None, use all variables in `data` that aren't an outcome or a covariate |
| 40 | + covariates: str, List[str], or None (default) |
| 41 | + The variable (str) or variables (List) to be used as covariates in each regression. |
| 42 | + regression_kind: None, str or subclass of Regression |
| 43 | + This can be 'glm', 'weighted_glm', or 'r_survey' for built-in Regression types, |
| 44 | + or a custom subclass of Regression. If None, it is set to 'glm' if a survey design is not specified |
| 45 | + and 'weighted_glm' if it is. |
| 46 | + encoding: str, default "additive" |
| 47 | + Encoding method to use for any genotype data. One of {'additive', 'dominant', 'recessive', 'codominant', or 'weighted'} |
| 48 | + weighted_encoding_info: Optional pd.DataFrame, default None |
| 49 | + If weighted encoding is used, this must be provided. See Pandas-Genomics documentation on weighted encodings. |
| 50 | + kwargs: Keyword arguments specific to the Regression being used |
| 51 | +
|
| 52 | + Returns |
| 53 | + ------- |
| 54 | + df: pd.DataFrame |
| 55 | + Association Study results DataFrame with at least these columns: ['N', 'pvalue', 'error', 'warnings']. |
| 56 | + Indexed by the outcome variable and the variable being assessed in each regression |
| 57 | + """ |
| 58 | + # Copy data to avoid modifying the original, in case it is changed |
| 59 | + data = data.copy(deep=True) |
| 60 | + |
| 61 | + # Encode any genotype data |
| 62 | + has_genotypes = False |
| 63 | + for dt in data.dtypes: |
| 64 | + if GenotypeDtype.is_dtype(dt): |
| 65 | + has_genotypes = True |
| 66 | + break |
| 67 | + if has_genotypes: |
| 68 | + if encoding == "additive": |
| 69 | + data = data.genomics.encode_additive() |
| 70 | + elif encoding == "dominant": |
| 71 | + data = data.genomics.encode_dominant() |
| 72 | + elif encoding == "recessive": |
| 73 | + data = data.genomics.encode_recessive() |
| 74 | + elif encoding == "codominant": |
| 75 | + data = data.genomics.encode_codominant() |
| 76 | + elif encoding == "weighted": |
| 77 | + if weighted_encoding_info is None: |
| 78 | + raise ValueError( |
| 79 | + "'weighted_encoding_info' must be provided when using weighted encoding" |
| 80 | + ) |
| 81 | + else: |
| 82 | + data = data.genomics.encode_weighted(weighted_encoding_info) |
| 83 | + else: |
| 84 | + raise ValueError(f"Genotypes provided with unknown 'encoding': {encoding}") |
| 85 | + |
| 86 | + # Ensure outcome, covariates, and regression variables are lists |
| 87 | + if isinstance(outcomes, str): |
| 88 | + outcomes = [ |
| 89 | + outcomes, |
| 90 | + ] |
| 91 | + if isinstance(covariates, str): |
| 92 | + covariates = [ |
| 93 | + covariates, |
| 94 | + ] |
| 95 | + elif covariates is None: |
| 96 | + covariates = [] |
| 97 | + if isinstance(regression_variables, str): |
| 98 | + regression_variables = [ |
| 99 | + regression_variables, |
| 100 | + ] |
| 101 | + elif regression_variables is None: |
| 102 | + regression_variables = list(set(data.columns) - set(outcomes) - set(covariates)) |
| 103 | + |
| 104 | + # Delete the survey_design_spec kwarg if it is None |
| 105 | + # This would be fine, but kwarg parsing for different clases means possibly passing it to an init that isn't expecting it |
| 106 | + if "survey_design_spec" in kwargs: |
| 107 | + if kwargs["survey_design_spec"] is None: |
| 108 | + del kwargs["survey_design_spec"] |
| 109 | + |
| 110 | + # Parse regression kind |
| 111 | + if regression_kind is None: |
| 112 | + # Match the original api, which is glm or weighted_glm based on whether a design is passes |
| 113 | + if "survey_design_spec" in kwargs: |
| 114 | + regression_cls = WeightedGLMRegression |
| 115 | + else: |
| 116 | + regression_cls = GLMRegression |
| 117 | + elif isinstance(regression_kind, str): |
| 118 | + regression_cls = builtin_regression_kinds.get(regression_kind, None) |
| 119 | + if regression_cls is None: |
| 120 | + raise ValueError( |
| 121 | + f"Unknown regression kind '{regression_kind}, known values are {','.join(builtin_regression_kinds.keys())}" |
| 122 | + ) |
| 123 | + elif regression_kind in regression_kind.mro(): |
| 124 | + regression_cls = regression_kind |
| 125 | + else: |
| 126 | + raise ValueError( |
| 127 | + f"Incorrect regression kind type ({type(regression_kind)}). " |
| 128 | + f"A valid string or a subclass of Regression is required." |
| 129 | + ) |
| 130 | + |
| 131 | + # Run each regression |
| 132 | + results = [] |
| 133 | + for outcome in outcomes: |
| 134 | + regression = regression_cls( |
| 135 | + data=data, |
| 136 | + outcome_variable=outcome, |
| 137 | + regression_variables=regression_variables, |
| 138 | + covariates=covariates, |
| 139 | + **kwargs, |
| 140 | + ) |
| 141 | + print(regression) |
| 142 | + |
| 143 | + # Run and get results |
| 144 | + regression.run() |
| 145 | + result = regression.get_results() |
| 146 | + |
| 147 | + # Process Results |
| 148 | + click.echo(f"Completed Association Study for {outcome}\n", color="green") |
| 149 | + results.append(result) |
| 150 | + |
| 151 | + if len(outcomes) == 1: |
| 152 | + result = results[0] |
| 153 | + else: |
| 154 | + result = pd.concat(results) |
| 155 | + |
| 156 | + # Sort across multiple outcomes |
| 157 | + if result.index.names == ["Variable", "Outcome", "Category"]: |
| 158 | + result = result.sort_values(["pvalue", "Beta_pvalue"]) |
| 159 | + elif result.index.names == ["Variable", "Outcome"]: |
| 160 | + result = result.sort_values(["pvalue"]) |
| 161 | + |
| 162 | + click.echo("Completed association study", color="green") |
| 163 | + return result |
0 commit comments