Sure! Let's convert the mr_presso function from R to Python step by step. We'll break down the R code into manageable chunks, explain each part, and then provide the Python equivalent. This approach ensures accuracy and clarity throughout the translation process.
1. Function Definition and Initial Setup
R Code:
mr_presso <- function(BetaOutcome, BetaExposure, SdOutcome, SdExposure, data, OUTLIERtest = FALSE, DISTORTIONtest = FALSE, SignifThreshold = 0.05, NbDistribution = 1000, seed = NULL){
if(!is.null(seed))
set.seed(seed)
if(SignifThreshold > 1)
stop("The significance threshold cannot be greater than 1")
if(length(BetaExposure) != length(SdExposure))
stop("BetaExposure and SdExposure must have the same number of elements")
if(class(data)[1] != "data.frame")
stop("data must be an object of class data.frame, try to rerun MR-PRESSO by conversing data to a data.frame \'data = as.data.frame(data)\'")
# ... rest of the code ...
}
Explanation:
-
Function Definition: The mr_presso function takes multiple arguments related to genetic instruments and performs MR-PRESSO analysis.
-
Seed Setting: If a seed is provided, it sets the random seed for reproducibility.
-
Input Validation:
- Checks if the significance threshold is greater than 1.
- Ensures that
BetaExposure and SdExposure have the same length.
- Validates that
data is a data frame.
Python Equivalent:
We'll start by defining the function and implementing the initial setup and input validations.
import pandas as pd
import numpy as np
import warnings
def mr_presso(BetaOutcome, BetaExposure, SdOutcome, SdExposure, data,
OUTLIERtest=False, DISTORTIONtest=False,
SignifThreshold=0.05, NbDistribution=1000, seed=None):
# Set seed for reproducibility
if seed is not None:
np.random.seed(seed)
# Input validations
if SignifThreshold > 1:
raise ValueError("The significance threshold cannot be greater than 1")
if len(BetaExposure) != len(SdExposure):
raise ValueError("BetaExposure and SdExposure must have the same number of elements")
if not isinstance(data, pd.DataFrame):
raise TypeError("data must be a pandas DataFrame. Try converting data to a DataFrame using 'data = pd.DataFrame(data)'")
# ... rest of the code ...
2. Defining Helper Functions
R Code:
# Functions
"%^%" <- function(x, n) with(eigen(x), vectors %*% (values^n * t(vectors)))
getRSS_LOO <- function(BetaOutcome, BetaExposure, data, returnIV){
dataW <- data[, c(BetaOutcome, BetaExposure)] * sqrt(data[, "Weights"])
X <- as.matrix(dataW[ , BetaExposure])
Y <- as.matrix(dataW[ , BetaOutcome])
CausalEstimate_LOO <- sapply(1:nrow(dataW), function(i) {
(t(X[-i, ]) %*% X[-i, ])%^%(-1) %*% t(X[-i, ]) %*% Y[-i, ]
})
if(length(BetaExposure) == 1)
RSS <- sum((Y - CausalEstimate_LOO * X)^2, na.rm = TRUE)
else
RSS <- sum((Y - rowSums(t(CausalEstimate_LOO) * X))^2, na.rm = TRUE)
if(returnIV)
RSS <- list(RSS, CausalEstimate_LOO)
return(RSS)
}
getRandomData <- function(BetaOutcome, BetaExposure, SdOutcome, SdExposure, data){
mod_IVW <- lapply(1:nrow(data), function(i) lm(as.formula(paste0(BetaOutcome, " ~ -1 + ", paste(BetaExposure, collapse=" + "))), weights = Weights, data = data[-i, ]))
dataRandom <- cbind(eval(parse(text = paste0("cbind(", paste0("rnorm(nrow(data), data[, \'", BetaExposure, "\'], data[ ,\'", SdExposure, "\'])", collapse = ", "), ", sapply(1:nrow(data), function(i) rnorm(1, predict(mod_IVW[[i]], newdata = data[i, ]), data[i ,\'", SdOutcome,"\'])))"))), data$Weights)
colnames(dataRandom) <- c(BetaExposure, BetaOutcome, "Weights")
return(dataRandom)
}
Explanation:
Python Equivalent:
We'll define equivalent helper functions in Python. Note that Python doesn't support custom operators like R, so we'll define them as regular functions.
from numpy.linalg import eig, inv
import statsmodels.api as sm
from statsmodels.formula.api import ols
def matrix_power(x, n):
eigenvalues, vectors = np.linalg.eigh(x)
return vectors @ np.diag(eigenvalues**n) @ vectors.T
def get_RSS_LOO(BetaOutcome, BetaExposure, data, returnIV):
dataW = data.loc[:, [BetaOutcome] + BetaExposure].copy()
dataW[BetaOutcome] = dataW[BetaOutcome] * np.sqrt(data['Weights'])
for exposure in BetaExposure:
dataW[exposure] = dataW[exposure] * np.sqrt(data['Weights'])
X = dataW[BetaExposure].values
Y = dataW[BetaOutcome].values.reshape(-1, 1)
n = X.shape[0]
p = X.shape[1]
CausalEstimate_LOO = []
for i in range(n):
X_i = np.delete(X, i, axis=0)
Y_i = np.delete(Y, i, axis=0)
try:
XtX_inv = matrix_power(X_i.T @ X_i, -1)
beta = XtX_inv @ X_i.T @ Y_i
CausalEstimate_LOO.append(beta.flatten())
except np.linalg.LinAlgError:
CausalEstimate_LOO.append(np.full(p, np.nan))
CausalEstimate_LOO = np.array(CausalEstimate_LOO)
if len(BetaExposure) == 1:
RSS = np.nansum((Y.flatten() - CausalEstimate_LOO.flatten() * X[:, 0])**2)
else:
RSS = np.nansum((Y.flatten() - (CausalEstimate_LOO @ X.T))**2)
if returnIV:
return [RSS, CausalEstimate_LOO]
return RSS
def get_random_data(BetaOutcome, BetaExposure, SdOutcome, SdExposure, data):
n = data.shape[0]
mod_IVW = []
formula = f"{BetaOutcome} ~ {' + '.join(BetaExposure)} -1"
for i in range(n):
data_subset = data.drop(index=i)
model = ols(formula, data=data_subset, weights= data_subset['Weights']).fit()
mod_IVW.append(model)
exposures = [np.random.normal(loc=data[exposure], scale=data[sd]) for exposure, sd in zip(BetaExposure, SdExposure)]
exposures = np.vstack(exposures).T # Shape: (n, number of exposures)
outcomes = []
for i in range(n):
pred = mod_IVW[i].predict(data.iloc[[i]])
outcomes.append(np.random.normal(loc=pred.iloc[0], scale=data.at[i, SdOutcome]))
outcomes = np.array(outcomes).reshape(-1, 1)
data_random = np.hstack([exposures, outcomes, data['Weights'].values.reshape(-1, 1)])
columns = BetaExposure + [BetaOutcome, "Weights"]
data_random_df = pd.DataFrame(data_random, columns=columns)
return data_random_df
Notes:
-
Matrix Power Function (matrix_power):
- Python's
numpy doesn't allow matrix exponentiation with negative powers directly. We use eigen decomposition to achieve this.
-
get_RSS_LOO Function:
- Uses NumPy for matrix operations.
- Handles potential singular matrices with a try-except block.
-
get_random_data Function:
- Utilizes
statsmodels for linear regression (ols).
- Generates random exposures and outcomes based on the specified standard deviations.
- Constructs a new DataFrame similar to the R function.
3. Data Transformation and Preliminary Checks
R Code:
# 0- Transforming the data + checking number of observations
data <- data[, c(BetaOutcome, BetaExposure, SdOutcome, SdExposure)]
data <- data[rowSums(is.na(data)) == 0, ]
data[, c(BetaOutcome, BetaExposure)] <- data[, c(BetaOutcome, BetaExposure)] * sign(data[, BetaExposure[1]])
data$Weights <- 1/data[, SdOutcome]^2
if(nrow(data) <= length(BetaExposure) + 2)
stop("Not enough intrumental variables")
if(nrow(data) >= NbDistribution)
stop("Not enough elements to compute empirical P-values, increase NbDistribution")
Explanation:
-
Data Selection: Selects relevant columns based on the provided parameters.
-
NA Removal: Removes rows with any missing values.
-
Sign Adjustment: Ensures that the BetaOutcome and BetaExposure are signed consistently based on the first BetaExposure.
-
Weights Calculation: Computes weights as the inverse square of SdOutcome.
-
Preliminary Checks:
- Ensures there are enough instrumental variables.
- Checks if the number of observations is sufficient for the specified number of distributions.
Python Equivalent:
# Select relevant columns
selected_columns = [BetaOutcome] + BetaExposure + [SdOutcome] + SdExposure
data = data[selected_columns].dropna().copy()
# Adjust signs based on the first BetaExposure
sign_factor = np.sign(data[BetaExposure[0]])
data[BetaOutcome] = data[BetaOutcome] * sign_factor
for exposure in BetaExposure:
data[exposure] = data[exposure] * sign_factor
# Calculate Weights
data['Weights'] = 1 / (data[SdOutcome] ** 2)
# Preliminary checks
if data.shape[0] <= len(BetaExposure) + 2:
raise ValueError("Not enough instrumental variables")
if data.shape[0] >= NbDistribution:
raise ValueError("Not enough elements to compute empirical P-values, increase NbDistribution")
Notes:
-
Column Selection and NA Removal:
- We select the relevant columns and drop any rows with missing values.
-
Sign Adjustment:
- Multiplies
BetaOutcome and all BetaExposure by the sign of the first BetaExposure to standardize the direction.
-
Weights Calculation:
- Follows the same logic as the R function.
-
Preliminary Checks:
- Ensures sufficient instrumental variables and observations.
4. Computing Observed RSS
R Code:
# 1- Computing the observed residual sum of squares (RSS)
RSSobs <- getRSS_LOO(BetaOutcome = BetaOutcome, BetaExposure = BetaExposure, data = data, returnIV = OUTLIERtest)
Explanation:
- Observed RSS Calculation: Calls the
getRSS_LOO function to compute the observed residual sum of squares. If OUTLIERtest is TRUE, it also retrieves the causal estimates.
Python Equivalent:
# Compute the observed RSS
RSSobs = get_RSS_LOO(BetaOutcome=BetaOutcome,
BetaExposure=BetaExposure,
data=data,
returnIV=OUTLIERtest)
5. Generating Random Data and Computing Expected RSS
R Code:
# 2- Computing the distribtion of expected residual sum of squares (RSS)
randomData <- replicate(NbDistribution, getRandomData(BetaOutcome = BetaOutcome, BetaExposure = BetaExposure, SdOutcome = SdOutcome, SdExposure = SdExposure, data = data), simplify = FALSE)
RSSexp <- sapply(randomData, getRSS_LOO, BetaOutcome = BetaOutcome, BetaExposure = BetaExposure, returnIV = OUTLIERtest)
Explanation:
-
Random Data Generation: Generates NbDistribution random datasets using the getRandomData function.
-
Expected RSS Calculation: Computes the RSS for each random dataset to form the distribution of expected RSS.
Python Equivalent:
# Generate random datasets
random_data_list = []
for _ in range(NbDistribution):
random_data = get_random_data(BetaOutcome=BetaOutcome,
BetaExposure=BetaExposure,
SdOutcome=SdOutcome,
SdExposure=SdExposure,
data=data)
random_data_list.append(random_data)
# Compute RSS for each random dataset
if OUTLIERtest:
RSSexp = np.array([get_RSS_LOO(BetaOutcome=BetaOutcome,
BetaExposure=BetaExposure,
data=rd,
returnIV=OUTLIERtest) for rd in random_data_list])
else:
RSSexp = np.array([get_RSS_LOO(BetaOutcome=BetaOutcome,
BetaExposure=BetaExposure,
data=rd,
returnIV=OUTLIERtest) for rd in random_data_list])
# Convert RSSexp to appropriate shape if OUTLIERtest is True
if OUTLIERtest:
RSSexp_values = RSSexp[:, 0]
else:
RSSexp_values = RSSexp
Notes:
-
Random Data Generation:
- Uses a loop to generate each random dataset.
-
RSS Calculation:
- Computes RSS for each random dataset.
- Handles the case when
OUTLIERtest is True by extracting the first element (RSS value) from the returned list.
6. Computing Global Test
R Code:
if(OUTLIERtest)
GlobalTest <- list(RSSobs = RSSobs[[1]], Pvalue = sum(RSSexp[1, ] > RSSobs[[1]])/NbDistribution)
else
GlobalTest <- list(RSSobs = RSSobs[[1]], Pvalue = sum(RSSexp > RSSobs[[1]])/NbDistribution)
Explanation:
- Global Test Construction:
- If
OUTLIERtest is TRUE, RSSobs is a list containing RSS and causal estimates. It computes the p-value based on the distribution of RSS.
- If
OUTLIERtest is FALSE, it directly computes the p-value.
Python Equivalent:
# Compute P-value for the Global Test
if OUTLIERtest:
GlobalTest = {
'RSSobs': RSSobs[0],
'Pvalue': np.sum(RSSexp_values > RSSobs[0]) / NbDistribution
}
else:
GlobalTest = {
'RSSobs': RSSobs,
'Pvalue': np.sum(RSSexp_values > RSSobs) / NbDistribution
}
Notes:
-
P-value Calculation:
- Counts how many times the expected RSS exceeds the observed RSS and divides by the number of distributions to get the empirical p-value.
-
GlobalTest Structure:
- Maintains consistency with the R list structure by using a Python dictionary.
7. Computing Single IV Outlier Test
R Code:
# 3- Computing the single IV outlier test
if(GlobalTest$Pvalue < SignifThreshold & OUTLIERtest){
OutlierTest <- do.call("rbind", lapply(1:nrow(data), function(SNV){
randomSNP <- do.call("rbind", lapply(randomData, function(mat) mat[SNV, ]))
if(length(BetaExposure) == 1){
Dif <- data[SNV, BetaOutcome] - data[SNV, BetaExposure] * RSSobs[[2]][SNV]
Exp <- randomSNP[, BetaOutcome] - randomSNP[, BetaExposure] * RSSobs[[2]][SNV]
} else {
Dif <- data[SNV, BetaOutcome] - sum(data[SNV, BetaExposure] * RSSobs[[2]][, SNV])
Exp <- randomSNP[, BetaOutcome] - rowSums(randomSNP[, BetaExposure] * RSSobs[[2]][, SNV])
}
pval <- sum(Exp^2 > Dif^2)/length(randomData)
pval <- cbind.data.frame(RSSobs = Dif^2, Pvalue = pval)
return(pval)
}))
row.names(OutlierTest) <- row.names(data)
OutlierTest$Pvalue <- apply(cbind(OutlierTest$Pvalue*nrow(data), 1), 1, min) # Bonferroni correction
} else{
OUTLIERtest <- FALSE
}
Explanation:
-
Conditional Execution: Performs outlier tests only if the global p-value is below the significance threshold and OUTLIERtest is TRUE.
-
Outlier Detection:
- Iterates over each SNP (Single Nucleotide Polymorphism).
- For each SNP, calculates the difference (
Dif) between the observed and expected outcomes.
- Computes the p-value based on how often the squared differences exceed the random expectations.
-
Bonferroni Correction: Adjusts the p-values to account for multiple testing.
Python Equivalent:
if GlobalTest['Pvalue'] < SignifThreshold and OUTLIERtest:
OutlierTest_list = []
for snv in range(data.shape[0]):
# Extract the SNV from all random datasets
random_snp = np.array([rd.loc[snv, BetaOutcome] for rd in random_data_list])
if len(BetaExposure) == 1:
Dif = data.loc[snv, BetaOutcome] - data.loc[snv, BetaExposure[0]] * RSSobs[1][snv]
Exp = random_snp - data.loc[snv, BetaExposure[0]] * RSSobs[1][snv]
else:
Dif = data.loc[snv, BetaOutcome] - np.dot(data.loc[snv, BetaExposure].values, RSSobs[1][:, snv])
Exp = random_snp - np.dot(random_data_list[:, BetaExposure].values, RSSobs[1][:, snv])
pval = np.sum(Exp**2 > Dif**2) / NbDistribution
OutlierTest_list.append({'RSSobs': Dif**2, 'Pvalue': pval})
OutlierTest = pd.DataFrame(OutlierTest_list, index=data.index)
# Bonferroni correction
OutlierTest['Pvalue'] = np.minimum(OutlierTest['Pvalue'] * data.shape[0], 1)
else:
OUTLIERtest = False
OutlierTest = None
Notes:
-
Iteration Over SNPs:
- Loop through each SNP index.
-
Calculating Differences and Expectations:
- For each SNP, compute
Dif and Exp based on whether there's a single exposure or multiple exposures.
-
P-value Calculation:
- Similar to the global test, but applied to each SNP.
-
Bonferroni Correction:
- Multiplies each p-value by the number of tests (
nrow(data)) and caps it at 1.
-
Handling OUTLIERtest Flag:
- If the condition isn't met,
OutlierTest is set to None.
Potential Adjustment:
In the above Python code, there's a part where we attempt to access random_data_list[:, BetaExposure].values, which is incorrect because random_data_list is a list of DataFrames. We need to handle multiple exposures appropriately. Here's the corrected version:
import pandas as pd
if GlobalTest['Pvalue'] < SignifThreshold and OUTLIERtest:
OutlierTest_list = []
for snv in range(data.shape[0]):
# Extract the SNV from all random datasets
random_snp_outcomes = np.array([rd.loc[snv, BetaOutcome] for rd in random_data_list])
if len(BetaExposure) == 1:
exposure = BetaExposure[0]
causal_estimate = RSSobs[1][snv] if OUTLIERtest else None
Dif = data.loc[snv, BetaOutcome] - data.loc[snv, exposure] * RSSobs[1][snv]
Exp = random_snp_outcomes - data.loc[snv, exposure] * RSSobs[1][snv]
else:
exposures = data.loc[snv, BetaExposure].values
causal_estimates = RSSobs[1][:, snv]
Dif = data.loc[snv, BetaOutcome] - np.dot(exposures, causal_estimates)
Exp = random_snp_outcomes - np.dot([rd.loc[snv, BetaExposure].values for rd in random_data_list], causal_estimates)
pval = np.sum(Exp**2 > Dif**2) / NbDistribution
OutlierTest_list.append({'RSSobs': Dif**2, 'Pvalue': pval})
OutlierTest = pd.DataFrame(OutlierTest_list, index=data.index)
# Bonferroni correction
OutlierTest['Pvalue'] = OutlierTest['Pvalue'].apply(lambda x: min(x * data.shape[0], 1))
else:
OUTLIERtest = False
OutlierTest = None
8. Computing Distortion Test
R Code:
# 4- Computing the test of the distortion of the causal estimate
mod_all <- lm(as.formula(paste0(BetaOutcome, " ~ -1 + ", paste(BetaExposure, collapse = "+"))), weights = Weights, data = data)
if(DISTORTIONtest & OUTLIERtest){
getRandomBias <- function(BetaOutcome, BetaExposure, SdOutcome, SdExposure, data, refOutlier){
indices <- c(refOutlier, replicate(nrow(data)-length(refOutlier), sample(setdiff(1:nrow(data), refOutlier))[1]))
mod_random <- lm(as.formula(paste0(BetaOutcome, " ~ -1 + ", paste(BetaExposure, collapse = "+"))), weights = Weights, data = data[indices[1:(length(indices) - length(refOutlier))], ])
return(mod_random$coefficients[BetaExposure])
}
refOutlier <- which(OutlierTest$Pvalue <= SignifThreshold)
if(length(refOutlier) > 0){
if(length(refOutlier) < nrow(data)){
BiasExp <- replicate(NbDistribution, getRandomBias(BetaOutcome = BetaOutcome, BetaExposure = BetaExposure, data = data, refOutlier = refOutlier), simplify = FALSE)
BiasExp <- do.call("rbind", BiasExp)
mod_noOutliers <- lm(as.formula(paste0(BetaOutcome, " ~ -1 + ", paste(BetaExposure, collapse=" + "))), weights = Weights, data = data[-refOutlier, ])
BiasObs <- (mod_all$coefficients[BetaExposure] - mod_noOutliers$coefficients[BetaExposure]) / abs(mod_noOutliers$coefficients[BetaExposure])
BiasExp <- (mod_all$coefficients[BetaExposure] - BiasExp) / abs(BiasExp)
BiasTest <- list(`Outliers Indices` = refOutlier, `Distortion Coefficient` = 100*BiasObs, Pvalue = sum(abs(BiasExp) > abs(BiasObs))/NbDistribution)
} else {
BiasTest <- list(`Outliers Indices` = "All SNPs considered as outliers", `Distortion Coefficient` = NA, Pvalue = NA)
}
} else{
BiasTest <- list(`Outliers Indices` = "No significant outliers", `Distortion Coefficient` = NA, `Pvalue` = NA)
}
}
Explanation:
Python Equivalent:
# Fit the main model
formula = f"{BetaOutcome} ~ {' + '.join(BetaExposure)} -1"
mod_all = ols(formula, data=data, weights=data['Weights']).fit()
if DISTORTIONtest and OUTLIERtest and OutlierTest is not None:
# Identify reference outliers
refOutlier = OutlierTest[OutlierTest['Pvalue'] <= SignifThreshold].index.tolist()
def get_random_bias(BetaOutcome, BetaExposure, data, refOutlier):
n = data.shape[0]
non_outliers = list(set(range(n)) - set(refOutlier))
if len(non_outliers) == 0:
sampled_indices = refOutlier.copy()
else:
sampled_indices = refOutlier.copy()
sampled = np.random.choice(non_outliers, n - len(refOutlier), replace=True)
sampled_indices += sampled.tolist()
data_subset = data.iloc[sampled_indices[:-len(refOutlier)]] if len(refOutlier) > 0 else data.copy()
model_random = ols(formula, data=data_subset, weights=data_subset['Weights']).fit()
return model_random.params[BetaExposure].values
if len(refOutlier) > 0:
if len(refOutlier) < data.shape[0]:
BiasExp_list = []
for _ in range(NbDistribution):
bias = get_random_bias(BetaOutcome, BetaExposure, data, refOutlier)
BiasExp_list.append(bias)
BiasExp = np.array(BiasExp_list)
# Fit model without outliers
data_no_outliers = data.drop(index=refOutlier)
mod_noOutliers = ols(formula, data=data_no_outliers, weights=data_no_outliers['Weights']).fit()
# Compute observed bias
BiasObs = (mod_all.params[BetaExposure] - mod_noOutliers.params[BetaExposure]) / np.abs(mod_noOutliers.params[BetaExposure])
# Compute expected bias
BiasExp = (mod_all.params[BetaExposure].values - BiasExp) / np.abs(BiasExp)
BiasTest = {
'Outliers Indices': refOutlier,
'Distortion Coefficient': 100 * BiasObs.values,
'Pvalue': np.mean(np.abs(BiasExp) > np.abs(BiasObs.values), axis=0)
}
else:
BiasTest = {
'Outliers Indices': "All SNPs considered as outliers",
'Distortion Coefficient': np.nan,
'Pvalue': np.nan
}
else:
BiasTest = {
'Outliers Indices': "No significant outliers",
'Distortion Coefficient': np.nan,
'Pvalue': np.nan
}
else:
BiasTest = None
Notes:
-
Model Fitting:
- Uses
statsmodels to fit the linear models without intercept (-1 in R formula).
-
Identifying Outliers:
- Extracts indices of SNPs with p-values below the significance threshold.
-
Random Bias Function (get_random_bias):
- Replaces outliers with randomly selected non-outliers.
- Fits the model on the modified dataset.
-
Bias Calculation:
- Computes the observed distortion and compares it with the distribution of expected distortions to obtain the p-value.
-
Handling Edge Cases:
- If all SNPs are outliers, sets distortion metrics to
NaN.
-
Handling BiasTest:
- Stores the results in a dictionary for consistency.
9. Formatting the Results
R Code:
# 5- Formatting the results
GlobalTest$Pvalue <- ifelse(GlobalTest$Pvalue == 0, paste0("<", 1/NbDistribution), GlobalTest$Pvalue)
if(OUTLIERtest){
OutlierTest$Pvalue <- replace(OutlierTest$Pvalue, OutlierTest$Pvalue == 0, paste0("<", nrow(data)/NbDistribution))
if(DISTORTIONtest){
BiasTest$Pvalue <- ifelse(BiasTest$Pvalue == 0, paste0("<", 1/NbDistribution), BiasTest$Pvalue)
res <- list(`Global Test` = GlobalTest, `Outlier Test` = OutlierTest, `Distortion Test` = BiasTest)
} else {
res <- list(`Global Test` = GlobalTest, `Outlier Test` = OutlierTest)
}
if(nrow(data)/NbDistribution > SignifThreshold)
warning(paste0("Outlier test unstable. The significance threshold of ", SignifThreshold, " for the outlier test is not achievable with only ", NbDistribution, " to compute the null distribution. The current precision is <", nrow(data)/NbDistribution, ". Increase NbDistribution."))
} else {
res <- list(`Global Test` = GlobalTest)
}
OriginalMR <- cbind.data.frame(BetaExposure, "Raw", summary(mod_all)$coefficients)
colnames(OriginalMR) <- c("Exposure", "MR Analysis", "Causal Estimate", "Sd", "T-stat", "P-value")
if(exists("mod_noOutliers")){
OutlierCorrectedMR <- cbind.data.frame(BetaExposure, "Outlier-corrected", summary(mod_noOutliers)$coefficients, row.names = NULL)
} else {
warning("No outlier were identified, therefore the results for the outlier-corrected MR are set to NA")
OutlierCorrectedMR <- cbind.data.frame(BetaExposure, "Outlier-corrected", t(rep(NA, 4)), row.names = NULL)
}
colnames(OutlierCorrectedMR) <- colnames(OriginalMR)
MR <- rbind.data.frame(OriginalMR, OutlierCorrectedMR)
row.names(MR) <- NULL
res <- list(`Main MR results` = MR, `MR-PRESSO results` = res)
return(res)
Explanation:
-
P-value Adjustments:
- Replaces
0 p-values with a lower bound based on NbDistribution.
-
Result Compilation:
- Compiles Global Test, Outlier Test, and Distortion Test into a results dictionary.
- Issues a warning if the outlier test is unstable.
-
MR Results Formatting:
- Creates a DataFrame for the main MR results, including raw and outlier-corrected estimates.
-
Final Output:
- Returns a dictionary containing both the main MR results and MR-PRESSO specific results.
Python Equivalent:
# Adjust p-values
GlobalTest['Pvalue'] = GlobalTest['Pvalue'].apply(lambda x: f"<{1/NbDistribution}" if x == 0 else x)
if OUTLIERtest and OutlierTest is not None:
OutlierTest['Pvalue'] = OutlierTest['Pvalue'].apply(lambda x: f"<{data.shape[0]/NbDistribution}" if x == 0 else x)
if DISTORTIONtest:
BiasTest['Pvalue'] = BiasTest['Pvalue'].apply(lambda x: f"<{1/NbDistribution}" if x == 0 else x)
res = {
'Global Test': GlobalTest,
'Outlier Test': OutlierTest,
'Distortion Test': BiasTest
}
else:
res = {
'Global Test': GlobalTest,
'Outlier Test': OutlierTest
}
# Warning for unstable outlier test
if data.shape[0] / NbDistribution > SignifThreshold:
warnings.warn(f"Outlier test unstable. The significance threshold of {SignifThreshold} for the outlier test is not achievable with only {NbDistribution} to compute the null distribution. The current precision is <{data.shape[0]/NbDistribution}. Increase NbDistribution.")
else:
res = {
'Global Test': GlobalTest
}
# Formatting MR Results
# Original MR
coeff_all = mod_all.params[BetaExposure]
std_err_all = mod_all.bse[BetaExposure]
t_stats_all = mod_all.tvalues[BetaExposure]
p_values_all = mod_all.pvalues[BetaExposure]
OriginalMR = pd.DataFrame({
'Exposure': BetaExposure,
'MR Analysis': 'Raw',
'Causal Estimate': coeff_all,
'Sd': std_err_all,
'T-stat': t_stats_all,
'P-value': p_values_all
}).reset_index(drop=True)
# Outlier-corrected MR
if 'mod_noOutliers' in locals():
coeff_no_outliers = mod_noOutliers.params[BetaExposure]
std_err_no_outliers = mod_noOutliers.bse[BetaExposure]
t_stats_no_outliers = mod_noOutliers.tvalues[BetaExposure]
p_values_no_outliers = mod_noOutliers.pvalues[BetaExposure]
OutlierCorrectedMR = pd.DataFrame({
'Exposure': BetaExposure,
'MR Analysis': 'Outlier-corrected',
'Causal Estimate': coeff_no_outliers,
'Sd': std_err_no_outliers,
'T-stat': t_stats_no_outliers,
'P-value': p_values_no_outliers
}).reset_index(drop=True)
else:
warnings.warn("No outlier were identified, therefore the results for the outlier-corrected MR are set to NA")
OutlierCorrectedMR = pd.DataFrame({
'Exposure': BetaExposure,
'MR Analysis': 'Outlier-corrected',
'Causal Estimate': [np.nan]*len(BetaExposure),
'Sd': [np.nan]*len(BetaExposure),
'T-stat': [np.nan]*len(BetaExposure),
'P-value': [np.nan]*len(BetaExposure)
})
# Combine MR Results
MR = pd.concat([OriginalMR, OutlierCorrectedMR], ignore_index=True)
# Final Results
final_res = {
'Main MR results': MR,
'MR-PRESSO results': res
}
return final_res
Notes:
-
P-value Adjustments:
- Uses lambda functions to replace
0 p-values with a string indicating they are below the threshold.
-
Result Compilation:
- Aggregates the Global Test, Outlier Test, and Distortion Test into a nested dictionary.
-
MR Results Formatting:
- Extracts coefficients, standard errors, t-statistics, and p-values from the fitted models.
- Creates separate DataFrames for raw and outlier-corrected MR analyses.
- Handles cases where no outliers are detected by populating with
NaN and issuing a warning.
-
Final Output:
- Returns a dictionary containing both the main MR results and the MR-PRESSO specific results, mirroring the R function structure.
Final Python Function
Putting it all together, here's the complete Python translation of the mr_presso function:
import pandas as pd
import numpy as np
import warnings
from numpy.linalg import eigh, inv
import statsmodels.api as sm
from statsmodels.formula.api import ols
def matrix_power(x, n):
eigenvalues, vectors = eigh(x)
return vectors @ np.diag(eigenvalues**n) @ vectors.T
def get_RSS_LOO(BetaOutcome, BetaExposure, data, returnIV):
dataW = data.loc[:, [BetaOutcome] + BetaExposure].copy()
dataW[BetaOutcome] = dataW[BetaOutcome] * np.sqrt(data['Weights'])
for exposure in BetaExposure:
dataW[exposure] = dataW[exposure] * np.sqrt(data['Weights'])
X = dataW[BetaExposure].values
Y = dataW[BetaOutcome].values.reshape(-1, 1)
n = X.shape[0]
p = X.shape[1]
CausalEstimate_LOO = []
for i in range(n):
X_i = np.delete(X, i, axis=0)
Y_i = np.delete(Y, i, axis=0)
try:
XtX_inv = matrix_power(X_i.T @ X_i, -1)
beta = XtX_inv @ X_i.T @ Y_i
CausalEstimate_LOO.append(beta.flatten())
except np.linalg.LinAlgError:
CausalEstimate_LOO.append(np.full(p, np.nan))
CausalEstimate_LOO = np.array(CausalEstimate_LOO)
if len(BetaExposure) == 1:
RSS = np.nansum((Y.flatten() - CausalEstimate_LOO.flatten() * X[:, 0])**2)
else:
RSS = np.nansum((Y.flatten() - (CausalEstimate_LOO @ X.T))**2)
if returnIV:
return [RSS, CausalEstimate_LOO]
return RSS
def get_random_data(BetaOutcome, BetaExposure, SdOutcome, SdExposure, data):
n = data.shape[0]
mod_IVW = []
formula = f"{BetaOutcome} ~ {' + '.join(BetaExposure)} -1"
for i in range(n):
data_subset = data.drop(index=i)
model = ols(formula, data=data_subset, weights=data_subset['Weights']).fit()
mod_IVW.append(model)
exposures = [np.random.normal(loc=data[exposure], scale=data[sd]) for exposure, sd in zip(BetaExposure, SdExposure)]
exposures = np.vstack(exposures).T # Shape: (n, number of exposures)
outcomes = []
for i in range(n):
pred = mod_IVW[i].predict(data.iloc[[i]])
outcomes.append(np.random.normal(loc=pred.iloc[0], scale=data.at[i, SdOutcome]))
outcomes = np.array(outcomes).reshape(-1, 1)
data_random = np.hstack([exposures, outcomes, data['Weights'].values.reshape(-1, 1)])
columns = BetaExposure + [BetaOutcome, "Weights"]
data_random_df = pd.DataFrame(data_random, columns=columns)
return data_random_df
def mr_presso(BetaOutcome, BetaExposure, SdOutcome, SdExposure, data,
OUTLIERtest=False, DISTORTIONtest=False,
SignifThreshold=0.05, NbDistribution=1000, seed=None):
# Set seed for reproducibility
if seed is not None:
np.random.seed(seed)
# Input validations
if SignifThreshold > 1:
raise ValueError("The significance threshold cannot be greater than 1")
if len(BetaExposure) != len(SdExposure):
raise ValueError("BetaExposure and SdExposure must have the same number of elements")
if not isinstance(data, pd.DataFrame):
raise TypeError("data must be a pandas DataFrame. Try converting data to a DataFrame using 'data = pd.DataFrame(data)'")
# Select relevant columns
selected_columns = [BetaOutcome] + BetaExposure + [SdOutcome] + SdExposure
data = data[selected_columns].dropna().copy()
# Adjust signs based on the first BetaExposure
sign_factor = np.sign(data[BetaExposure[0]])
data[BetaOutcome] = data[BetaOutcome] * sign_factor
for exposure in BetaExposure:
data[exposure] = data[exposure] * sign_factor
# Calculate Weights
data['Weights'] = 1 / (data[SdOutcome] ** 2)
# Preliminary checks
if data.shape[0] <= len(BetaExposure) + 2:
raise ValueError("Not enough instrumental variables")
if data.shape[0] >= NbDistribution:
raise ValueError("Not enough elements to compute empirical P-values, increase NbDistribution")
# Compute the observed RSS
RSSobs = get_RSS_LOO(BetaOutcome=BetaOutcome,
BetaExposure=BetaExposure,
data=data,
returnIV=OUTLIERtest)
# Generate random datasets
random_data_list = []
for _ in range(NbDistribution):
random_data = get_random_data(BetaOutcome=BetaOutcome,
BetaExposure=BetaExposure,
SdOutcome=SdOutcome,
SdExposure=SdExposure,
data=data)
random_data_list.append(random_data)
# Compute RSS for each random dataset
if OUTLIERtest:
RSSexp = np.array([get_RSS_LOO(BetaOutcome=BetaOutcome,
BetaExposure=BetaExposure,
data=rd,
returnIV=OUTLIERtest) for rd in random_data_list])
RSSexp_values = RSSexp[:, 0]
else:
RSSexp = np.array([get_RSS_LOO(BetaOutcome=BetaOutcome,
BetaExposure=BetaExposure,
data=rd,
returnIV=OUTLIERtest) for rd in random_data_list])
RSSexp_values = RSSexp
# Compute P-value for the Global Test
if OUTLIERtest:
GlobalTest = {
'RSSobs': RSSobs[0],
'Pvalue': np.sum(RSSexp_values > RSSobs[0]) / NbDistribution
}
else:
GlobalTest = {
'RSSobs': RSSobs,
'Pvalue': np.sum(RSSexp_values > RSSobs) / NbDistribution
}
# Compute Outlier Test
if GlobalTest['Pvalue'] < SignifThreshold and OUTLIERtest:
OutlierTest_list = []
for snv in range(data.shape[0]):
# Extract the SNV from all random datasets
random_snp_outcomes = np.array([rd.loc[snv, BetaOutcome] for rd in random_data_list])
if len(BetaExposure) == 1:
exposure = BetaExposure[0]
Dif = data.loc[snv, BetaOutcome] - data.loc[snv, exposure] * RSSobs[1][snv]
Exp = random_snp_outcomes - data.loc[snv, exposure] * RSSobs[1][snv]
else:
exposures = data.loc[snv, BetaExposure].values
causal_estimates = RSSobs[1][:, snv]
Dif = data.loc[snv, BetaOutcome] - np.dot(exposures, causal_estimates)
Exp = [rd.loc[snv, BetaOutcome] - np.dot(rd.loc[snv, BetaExposure].values, causal_estimates) for rd in random_data_list]
Exp = np.array(Exp)
pval = np.sum(Exp**2 > Dif**2) / NbDistribution
OutlierTest_list.append({'RSSobs': Dif**2, 'Pvalue': pval})
OutlierTest = pd.DataFrame(OutlierTest_list, index=data.index)
# Bonferroni correction
OutlierTest['Pvalue'] = OutlierTest['Pvalue'].apply(lambda x: min(x * data.shape[0], 1))
else:
GlobalTest['RSSobs'] = RSSobs if not OUTLIERtest else RSSobs[0]
OUTLIERtest = False
OutlierTest = None
# Fit the main model
formula = f"{BetaOutcome} ~ {' + '.join(BetaExposure)} -1"
mod_all = ols(formula, data=data, weights=data['Weights']).fit()
# Compute Distortion Test
if DISTORTIONtest and OUTLIERtest and OutlierTest is not None:
# Identify reference outliers
refOutlier = OutlierTest[OutlierTest['Pvalue'] <= SignifThreshold].index.tolist()
def get_random_bias(BetaOutcome, BetaExposure, data, refOutlier):
n = data.shape[0]
non_outliers = list(set(range(n)) - set(refOutlier))
if len(non_outliers) == 0:
sampled_indices = refOutlier.copy()
else:
sampled_indices = refOutlier.copy()
sampled = np.random.choice(non_outliers, n - len(refOutlier), replace=True)
sampled_indices += sampled.tolist()
data_subset = data.iloc[sampled_indices[:n - len(refOutlier)]] if len(refOutlier) > 0 else data.copy()
model_random = ols(formula, data=data_subset, weights=data_subset['Weights']).fit()
return model_random.params[BetaExposure].values
if len(refOutlier) > 0:
if len(refOutlier) < data.shape[0]:
BiasExp_list = []
for _ in range(NbDistribution):
bias = get_random_bias(BetaOutcome, BetaExposure, data, refOutlier)
BiasExp_list.append(bias)
BiasExp = np.array(BiasExp_list)
# Fit model without outliers
data_no_outliers = data.drop(index=refOutlier)
mod_noOutliers = ols(formula, data=data_no_outliers, weights=data_no_outliers['Weights']).fit()
# Compute observed bias
BiasObs = (mod_all.params[BetaExposure] - mod_noOutliers.params[BetaExposure]) / np.abs(mod_noOutliers.params[BetaExposure])
# Compute expected bias
BiasExp = (mod_all.params[BetaExposure].values - BiasExp) / np.abs(BiasExp)
BiasTest = {
'Outliers Indices': refOutlier,
'Distortion Coefficient': 100 * BiasObs.values,
'Pvalue': np.mean(np.abs(BiasExp) > np.abs(BiasObs.values), axis=0)
}
else:
BiasTest = {
'Outliers Indices': "All SNPs considered as outliers",
'Distortion Coefficient': np.nan,
'Pvalue': np.nan
}
else:
BiasTest = {
'Outliers Indices': "No significant outliers",
'Distortion Coefficient': np.nan,
'Pvalue': np.nan
}
else:
BiasTest = None
# Adjust p-values
GlobalTest['Pvalue'] = GlobalTest['Pvalue'].apply(lambda x: f"<{1/NbDistribution}" if isinstance(x, float) and x == 0 else x)
if OUTLIERtest and OutlierTest is not None:
OutlierTest['Pvalue'] = OutlierTest['Pvalue'].apply(lambda x: f"<{data.shape[0]/NbDistribution}" if isinstance(x, float) and x == 0 else x)
if BiasTest is not None:
if isinstance(BiasTest['Pvalue'], np.ndarray):
BiasTest['Pvalue'] = [f"<{1/NbDistribution}" if p == 0 else p for p in BiasTest['Pvalue']]
else:
BiasTest['Pvalue'] = f"<{1/NbDistribution}" if BiasTest['Pvalue'] == 0 else BiasTest['Pvalue']
res = {
'Global Test': GlobalTest,
'Outlier Test': OutlierTest,
'Distortion Test': BiasTest
}
else:
res = {
'Global Test': GlobalTest,
'Outlier Test': OutlierTest
}
# Warning for unstable outlier test
if data.shape[0] / NbDistribution > SignifThreshold:
warnings.warn(f"Outlier test unstable. The significance threshold of {SignifThreshold} for the outlier test is not achievable with only {NbDistribution} to compute the null distribution. The current precision is <{data.shape[0]/NbDistribution}. Increase NbDistribution.")
else:
res = {
'Global Test': GlobalTest
}
# Formatting MR Results
# Original MR
coeff_all = mod_all.params[BetaExposure]
std_err_all = mod_all.bse[BetaExposure]
t_stats_all = mod_all.tvalues[BetaExposure]
p_values_all = mod_all.pvalues[BetaExposure]
OriginalMR = pd.DataFrame({
'Exposure': BetaExposure,
'MR Analysis': 'Raw',
'Causal Estimate': coeff_all,
'Sd': std_err_all,
'T-stat': t_stats_all,
'P-value': p_values_all
}).reset_index(drop=True)
# Outlier-corrected MR
if 'mod_noOutliers' in locals():
coeff_no_outliers = mod_noOutliers.params[BetaExposure]
std_err_no_outliers = mod_noOutliers.bse[BetaExposure]
t_stats_no_outliers = mod_noOutliers.tvalues[BetaExposure]
p_values_no_outliers = mod_noOutliers.pvalues[BetaExposure]
OutlierCorrectedMR = pd.DataFrame({
'Exposure': BetaExposure,
'MR Analysis': 'Outlier-corrected',
'Causal Estimate': coeff_no_outliers,
'Sd': std_err_no_outliers,
'T-stat': t_stats_no_outliers,
'P-value': p_values_no_outliers
}).reset_index(drop=True)
else:
warnings.warn("No outlier were identified, therefore the results for the outlier-corrected MR are set to NA")
OutlierCorrectedMR = pd.DataFrame({
'Exposure': BetaExposure,
'MR Analysis': 'Outlier-corrected',
'Causal Estimate': [np.nan]*len(BetaExposure),
'Sd': [np.nan]*len(BetaExposure),
'T-stat': [np.nan]*len(BetaExposure),
'P-value': [np.nan]*len(BetaExposure)
})
# Combine MR Results
MR = pd.concat([OriginalMR, OutlierCorrectedMR], ignore_index=True)
# Final Results
final_res = {
'Main MR results': MR,
'MR-PRESSO results': res
}
return final_res
Usage Example
Here's how you might use the translated mr_presso function in Python:
# Example usage
import pandas as pd
# Sample data
data = pd.DataFrame({
'BetaOutcome': [0.2, 0.5, 0.3, 0.4],
'BetaExposure': [0.1, 0.2, 0.15, 0.25],
'SdOutcome': [0.05, 0.1, 0.07, 0.08],
'SdExposure': [0.02, 0.03, 0.025, 0.035]
})
result = mr_presso(
BetaOutcome='BetaOutcome',
BetaExposure=['BetaExposure'],
SdOutcome='SdOutcome',
SdExposure=['SdExposure'],
data=data,
OUTLIERtest=True,
DISTORTIONtest=True,
SignifThreshold=0.05,
NbDistribution=1000,
seed=42
)
print(result['Main MR results'])
print(result['MR-PRESSO results'])
Notes:
-
Ensure all dependencies (pandas, numpy, statsmodels) are installed in your Python environment.
-
The sample data provided is minimal; for actual analyses, you'll need a dataset with appropriate genetic instruments.
This step-by-step translation ensures that each component of the original R function is accurately represented in Python. Depending on the complexity of your data and specific requirements, further optimizations and error handling might be necessary.