#1 Loading R package
library(TwoSampleMR)
library(RadialMR)
library(data.table)

#2 Selection of genetic instruments
#2.1 Reading full exposure GWAS data
exposuse<-fread(input = "exposure_data.txt",sep="\t",header=T)
#2.2 Extracting significant instruments
exposure_sig<-subset(exposuse,pval<5e-08/5e-06)
#2.3 Removing linkage disequilibrium
exposure_sig_clump<-clump_data(dat=exposure_sig,clump_kb = 10000,clump_r2 = 0.001,clump_p1 = 1,clump_p2 = 1,pop = "EUR")
#2.4 Save the data
write.csv(exposure_sig_clump,file="exposure_sig_clump.csv")
#2.5 Calculating the F value of SNPs in "exposure_sig_clump.csv" and excluding SNPs with F<10 , saving the data as "exposure_sig_clump_F.csv".
#2.6 Reading the exposure data using the "read_expouse_data"function
exposure_final<-read_exposure_data(filename = "exposure_sig_clump_F",sep = ",",snp_col = "SNP",beta_col = "beta",se_col = "se",effect_allele_col = "effect_allele",other_allele_col = "other_allele",pval_col = "p",chr_col = "CHR", pos_col = "POS",clump = FALSE)

#3 Extracting outcome data
#3.1 Reading full outcome GWAS data
outcome<-fread(input = "outcome_data.txt",sep="\t",header=T)
#3.2 Reading Column Names of outcome to define it in the "read_expouse_data"function
head(outcome)
#3.3 Extracting outcome data using the "read_outcome_data"function
outcome_final<-read_outcome_data(filename = "outcome_data.txt",snps = exposure_final$SNP,sep = "\t",snp_col = "rsids",beta_col = "beta",se_col = "sebeta",effect_allele_col = "alt",other_allele_col = "ref",pval_col = "pval")

#4 Harmonize data and save data
Harmonize<-harmonise_data(exposure_dat = exposure_final,outcome_dat = outcome_final)

#5 Identify and remove outliers
#5.1 Formatting column names
Harmonize_format<-format_radial(BXG = Harmonize$beta.exposure,BYG = Harmonize$beta.outcome,seBXG = Harmonize$se.exposure,seBYG = Harmonize$se.outcome,RSID = Harmonize$SNP)
#5.2 Screening for outliers
outliers<-ivw_radial(r_input = Harmonize_format)
#5.3 Viewing outliers
outliers[["outliers"]][["SNP"]]
#5.4 Removing outliers
Radial<-as.data.frame(Harmonize_format,row.names = Harmonize_format$SNP)
exposure_outcome<-Radial[!row.names(Radial)%in%Radial("rsid", "rsid" ,"rsid" ),]#"rsid" means rsid of outlier.

#6 Performing MR
generate_odds_ratios(mr_res = mr(exposure_outcome),method_list = c("mr_ivw","mr_weighted_median","mr_egger_regression"))

#7 Sensitivity analysis
#7.1 Heterogeneity
mr_heterogeneity(exposure_outcome)
#7.2 Pleiotropy
mr_pleiotropy_test(exposure_outcome)
#leave_one_out analysis
mr_leaveoneout_plot(leaveoneout_results=mr_leaveoneout(exposure_outcome))