0
|
1 #!/usr/bin/env Rscript
|
|
2
|
|
3 suppressPackageStartupMessages(library("adegenet"))
|
|
4 suppressPackageStartupMessages(library("ape"))
|
7
|
5 suppressPackageStartupMessages(library("data.table"))
|
|
6 suppressPackageStartupMessages(library("dplyr"))
|
0
|
7 suppressPackageStartupMessages(library("ggplot2"))
|
|
8 suppressPackageStartupMessages(library("knitr"))
|
4
|
9 suppressPackageStartupMessages(library("optparse"))
|
|
10 suppressPackageStartupMessages(library("poppr"))
|
|
11 suppressPackageStartupMessages(library("RColorBrewer"))
|
7
|
12 suppressPackageStartupMessages(library("RPostgres"))
|
4
|
13 suppressPackageStartupMessages(library("vcfR"))
|
|
14 suppressPackageStartupMessages(library("vegan"))
|
0
|
15
|
|
16 option_list <- list(
|
7
|
17 make_option(c("--database_connection_string"), action="store", dest="database_connection_string", help="Corals (stag) database connection string"),
|
|
18 make_option(c("--input_affy_metadata"), action="store", dest="input_affy_metadata", help="Affymetrix 96 well plate input file"),
|
4
|
19 make_option(c("--input_pop_info"), action="store", dest="input_pop_info", help="Population information input file"),
|
7
|
20 make_option(c("--input_vcf"), action="store", dest="input_vcf", help="VCF input file"),
|
|
21 make_option(c("--output_stag_db_report"), action="store", dest="output_stag_db_report", help="stag db report output file")
|
0
|
22 )
|
|
23
|
|
24 parser <- OptionParser(usage="%prog [options] file", option_list=option_list);
|
|
25 args <- parse_args(parser, positional_arguments=TRUE);
|
|
26 opt <- args$options;
|
|
27
|
|
28 get_file_path = function(file_name) {
|
|
29 file_path = paste("output_plots_dir", file_name, sep="/");
|
|
30 return(file_path);
|
|
31 }
|
|
32
|
8
|
33 get_database_connection <- function(db_conn_string) {
|
|
34 # Instantiate database connection.
|
|
35 # The connection string has this format:
|
|
36 # postgresql://user:password@host/dbname
|
|
37 conn_items <- strsplit(db_conn_string, "://")[[1]];
|
|
38 string_needed <- conn_items[2];
|
|
39 items_needed <- strsplit(string_needed, "@")[[1]];
|
|
40 user_pass_string <- items_needed[1];
|
|
41 host_dbname_string <- items_needed[2];
|
|
42 user_pass_items <- strsplit(user_pass_string, ":")[[1]];
|
|
43 host_dbname_items <- strsplit(host_dbname_string, "/")[[1]];
|
|
44 user <- user_pass_items[1];
|
|
45 pass <- user_pass_items[2];
|
|
46 host <- host_dbname_items[1];
|
|
47 dbname <- host_dbname_items[2];
|
|
48 # FIXME: is there a way to not hard-code the port?
|
|
49 conn <- DBI::dbConnect(RPostgres::Postgres(), host=host, port='5432', dbname=dbname, user=user, password=pass);
|
|
50 return (conn);
|
|
51 }
|
|
52
|
3
|
53 # Read in VCF input file.
|
2
|
54 vcf <- read.vcfR(opt$input_vcf);
|
0
|
55
|
4
|
56 #Missing GT in samples submitted
|
|
57 gt <- extract.gt(vcf, element="GT", as.numeric=FALSE);
|
8
|
58 myMiss <- apply(gt, MARGIN=2, function(x){ sum(is.na(x))});
|
|
59 myMiss <- (myMiss / nrow(vcf)) * 100;
|
|
60 miss <- data.frame(myMiss);
|
7
|
61
|
|
62 hets <- apply(gt, MARGIN=2, function(x) {sum(lengths(regmatches(x, gregexpr("0/1", x))))} );
|
|
63 hets <- (hets / nrow(vcf)) * 100;
|
|
64 ht <- data.frame(hets);
|
|
65
|
|
66 refA <- apply(gt, MARGIN=2, function(x) {sum(lengths(regmatches(x, gregexpr("0/0", x))))} );
|
|
67 refA <- (refA / nrow(vcf)) * 100;
|
|
68 rA <- data.frame(refA);
|
4
|
69
|
7
|
70 altB <- apply(gt, MARGIN=2, function(x) {sum(lengths(regmatches(x, gregexpr("1/1", x))))} );
|
|
71 altB <- (altB / nrow(vcf)) * 100;
|
|
72 aB <- data.frame(altB);
|
|
73
|
|
74 # Convert VCF file into a genind for the Poppr package.
|
|
75 # TODO: probably should not hard-code 2 cores.
|
|
76 gl <- vcfR2genlight(vcf, n.cores=2);
|
8
|
77 gind <- new("genind", (as.matrix(gl)));
|
7
|
78
|
0
|
79 # Add population information to the genind object.
|
9
|
80 poptab <- read.table(opt$input_pop_info, check.names=FALSE, header=F, na.strings=c("", "NA"), stringsAsFactors = FALSE);
|
|
81 colnames(poptab) <- c("row_id", "affy_id", "user_specimen_id", "region");
|
8
|
82 gind@pop <- as.factor(poptab$region);
|
7
|
83
|
|
84 # Convert genind object to a genclone object.
|
8
|
85 obj2 <- as.genclone(gind);
|
7
|
86
|
|
87 # Calculate the bitwise distance between individuals.
|
8
|
88 xdis <- bitwise.dist(obj2);
|
0
|
89
|
9
|
90 # Multilocus genotypes (threshold of 16%).
|
|
91 mlg.filter(obj2, distance=xdis) <- 0.016;
|
8
|
92 m <- mlg.table(obj2, background=TRUE, color=TRUE);
|
0
|
93
|
|
94 # Create table of MLGs.
|
8
|
95 id <- mlg.id(obj2);
|
7
|
96 dt <- data.table(id, keep.rownames=TRUE);
|
9
|
97 setnames(dt, c("id"), c("affy_id"));
|
7
|
98
|
|
99 # Read user's Affymetrix 96 well plate csv file.
|
9
|
100 pinfo <- read.table(opt$input_affy_metadata, header=TRUE, stringsAsFactors=FALSE, sep="\t");
|
|
101 pinfo$user_specimen_id <- as.character(pinfo$user_specimen_id);
|
|
102 pinfo2 <- as.character(pinfo$user_specimen_id);
|
|
103 pi <- data.table(pinfo2);
|
|
104 setnames(pi, c("pinfo2"), c("user_specimen_id"));
|
7
|
105
|
8
|
106 # Connect to database.
|
|
107 conn <- get_database_connection(opt$database_connection_string);
|
7
|
108
|
|
109 # Import the sample table.
|
8
|
110 mD <- tbl(conn, "sample");
|
7
|
111
|
|
112 # Select user_specimen_id and mlg columns.
|
9
|
113 smlg <- mD %>% select(user_specimen_id, coral_mlg_clonal_id, symbio_mlg_clonal_id, affy_id);
|
7
|
114
|
|
115 # Convert to dataframe.
|
|
116 sm <- data.frame(smlg);
|
|
117 sm[sm==""] <- NA;
|
|
118
|
|
119 # Convert missing data into data table.
|
8
|
120 mi <-setDT(miss, keep.rownames=TRUE)[];
|
9
|
121 setnames(mi, c("rn"), c("affy_id"));
|
7
|
122 setnames(mi, c("myMiss"), c("percent_missing_data_coral"));
|
|
123 # Round missing data to two digits.
|
9
|
124 mi$percent_missing_data_coral <- round(mi$percent_missing_data_coral, digits=2);
|
7
|
125
|
|
126 # Convert heterozygosity data into data table.
|
|
127 ht <-setDT(ht, keep.rownames=TRUE)[];
|
9
|
128 setnames(ht, c("rn"), c("affy_id"));
|
7
|
129 setnames(ht, c("hets"), c("percent_mixed_coral"));
|
|
130 # Round missing data to two digits.
|
|
131 ht$percent_mixed<-round(ht$percent_mixed, digits=2);
|
|
132
|
|
133 # Convert refA data into data.table.
|
|
134 rA <-setDT(rA, keep.rownames=TRUE)[];
|
9
|
135 setnames(rA, c("rn"), c("affy_id"));
|
7
|
136 setnames(rA, c("refA"), c("percent_reference_coral"));
|
|
137 # round missing data to two digits.
|
|
138 rA$percent_reference<-round(rA$percent_reference, digits=2);
|
|
139
|
|
140 # Convert altB data into data table.
|
|
141 aB <-setDT(aB, keep.rownames=TRUE)[];
|
9
|
142 setnames(aB, c("rn"), c("affy_id"));
|
7
|
143 setnames(aB, c("altB"), c("percent_alternative_coral"));
|
|
144 # Round missing data to two digits.
|
|
145 aB$percent_alternative<-round(aB$percent_alternative, digits=2);
|
|
146
|
|
147 #convert mlg id to data.table format
|
|
148 dt <- data.table(id, keep.rownames=TRUE);
|
9
|
149 setnames(dt, c("id"), c("affy_id"));
|
7
|
150
|
|
151 # Transform.
|
|
152 df3 <- dt %>%
|
|
153 group_by(row_number()) %>%
|
|
154 dplyr::rename(group='row_number()') %>%
|
|
155 unnest (user_specimen_id) %>%
|
|
156 # Join with mlg table.
|
|
157 left_join(sm %>%
|
9
|
158 select("affy_id","coral_mlg_clonal_id"),
|
|
159 by='affy_id');
|
7
|
160
|
|
161 # If found in database, group members on previous mlg id.
|
|
162 uniques <- unique(df3[c("group", "coral_mlg_clonal_id")]);
|
|
163 uniques <- uniques[!is.na(uniques$coral_mlg_clonal_id),];
|
|
164 na.mlg <- which(is.na(df3$coral_mlg_clonal_id));
|
|
165 na.group <- df3$group[na.mlg];
|
|
166 df3$coral_mlg_clonal_id[na.mlg] <- uniques$coral_mlg_clonal_id[match(na.group, uniques$group)];
|
|
167
|
|
168 # Determine if the sample mlg matched previous genotyped sample.
|
|
169 df4<- df3 %>%
|
|
170 group_by(group) %>%
|
|
171 mutate(DB_match = ifelse(is.na(coral_mlg_clonal_id),"no_match","match"));
|
|
172
|
|
173 # Create new mlg id for samples that did not match those in the database.
|
|
174 none <- unique(df4[c("group", "coral_mlg_clonal_id")]);
|
|
175 none <- none[is.na(none$coral_mlg_clonal_id),];
|
|
176 na.mlg2 <- which(is.na(df4$coral_mlg_clonal_id));
|
|
177 n.g <- df4$group[na.mlg2];
|
|
178 ct <- length(unique(n.g));
|
|
179
|
|
180 # List of new group ids, the sequence starts at the number of
|
|
181 # ids present in df4$coral_mlg_clonal_ids plus 1. Not sure if
|
|
182 # the df4 file contains all ids. If it doesn't then look below
|
|
183 # to change the seq() function.
|
|
184 n.g_ids <- sprintf("HG%04d", seq((sum(!is.na(unique(df4["coral_mlg_clonal_id"]))) + 1), by=1, length=ct));
|
|
185 # This is a key for pairing group with new ids.
|
|
186 rat <- cbind(unique(n.g), n.g_ids);
|
|
187 # this for loop assigns the new id iteratively for all that have NA.
|
|
188 for (i in 1:length(na.mlg2)) {
|
|
189 df4$coral_mlg_clonal_id[na.mlg2[i]] <- n.g_ids[match(df4$group[na.mlg2[i]], unique(n.g))];
|
|
190 }
|
|
191
|
9
|
192 # subset poptab for all samples.
|
|
193 subpop <- poptab[c(2, 3)];
|
|
194
|
7
|
195 # Merge data frames for final table.
|
|
196 report_user <- pi %>%
|
9
|
197 left_join(subpop %>%
|
|
198 select("affy_id", "user_specimen_id"),
|
7
|
199 by='user_specimen_id') %>%
|
9
|
200 left_join(df4 %>%
|
|
201 select("affy_id", "coral_mlg_clonal_id", "DB_match"),
|
|
202 by='affy_id') %>%
|
7
|
203 left_join(mi %>%
|
9
|
204 select("affy_id", "percent_missing_data_coral"),
|
|
205 by='affy_id') %>%
|
7
|
206 left_join(ht %>%
|
9
|
207 select("affy_id", "percent_mixed_coral"),
|
|
208 by='affy_id') %>%
|
7
|
209 left_join(rA %>%
|
9
|
210 select("affy_id", "percent_reference_coral"),
|
|
211 by='affy_id') %>%
|
7
|
212 left_join(aB %>%
|
9
|
213 select("affy_id", "percent_alternative_coral"),
|
|
214 by='affy_id') %>%
|
7
|
215 mutate(DB_match = ifelse(is.na(DB_match), "failed", DB_match))%>%
|
|
216 mutate(coral_mlg_clonal_id=ifelse(is.na(coral_mlg_clonal_id), "failed", coral_mlg_clonal_id))%>%
|
|
217 ungroup() %>%
|
|
218 select(-group);
|
|
219
|
|
220 write.csv(report_user, file=paste(opt$output_stag_db_report), quote=FALSE);
|
0
|
221
|
9
|
222 # Combine sample information for database.
|
|
223 report_db <- pinfo %>%
|
|
224 left_join(report_user %>%
|
|
225 select("user_specimen_id", "affy_id", "coral_mlg_clonal_id", "DB_match",
|
|
226 "percent_missing_data_coral", "percent_mixed_coral", "percent_reference_coral",
|
|
227 "percent_alternative_coral"),
|
|
228 by='user_specimen_id')
|
7
|
229
|
9
|
230 # Create vector indicating number of individuals desired
|
|
231 # made from affy_id collumn of report_user data table.
|
|
232 i <- report_user[[2]];
|
|
233 sub96 <- obj2[i, mlg.reset=FALSE, drop=FALSE];
|
0
|
234
|
4
|
235 # Create a phylogeny of samples based on distance matrices.
|
|
236 cols <- palette(brewer.pal(n=12, name='Set3'));
|
|
237 set.seed(999);
|
|
238 # Start PDF device driver.
|
|
239 dev.new(width=10, height=7);
|
|
240 file_path = get_file_path("nj_phylogeny.pdf");
|
|
241 pdf(file=file_path, width=10, height=7);
|
|
242 # Organize branches by clade.
|
9
|
243 theTree <- sub96 %>%
|
|
244 aboot(dist=provesti.dist, sample=1, tree="nj", cutoff=50, quiet=TRUE) %>%
|
7
|
245 ladderize();
|
9
|
246 theTree$tip.label <- report_user$user_specimen_id[match(theTree$tip.label, report_user$affy_id)];
|
|
247 plot.phylo(theTree, tip.color=cols[sub96$pop], label.offset=0.0125, cex=0.3, font=2, lwd=4, align.tip.label=F, no.margin=T);
|
4
|
248 # Add a scale bar showing 5% difference..
|
9
|
249 add.scale.bar(0, 0.95, length=0.05, cex=0.65, lwd=3);
|
|
250 nodelabels(theTree$node.label, cex=.5, adj=c(1.5, -0.1), frame="n", font=3, xpd=TRUE);
|
|
251 legend("topright", legend=c("Antigua", "Bahamas", "Belize", "Cuba", "Curacao", "Florida", "PuertoRico", "USVI"), text.col=cols, xpd=T, cex=0.8);
|
7
|
252 dev.off();
|
0
|
253
|
9
|
254 # Missing data barplot.
|
|
255 poptab$miss <- report_user$percent_missing_data_coral[match(miss$affy_id, report_user$affy_id)];
|
|
256 test2 <- which(!is.na(poptab$miss));
|
|
257 miss96 <- poptab$miss[test2];
|
|
258 name96 <- poptab$user_specimen_id[test2];
|
|
259 dev.new(width=10, height=7);
|
|
260 file_path = get_file_path("missing_data.pdf");
|
|
261 pdf (file=file_path, width=10, height=7);
|
|
262 par(mar = c(8, 4, 4, 2));
|
|
263 x <- barplot(miss96, las=2, col=cols, ylim=c(0, 3), cex.axis=0.8, space=0.8, ylab="Missingness (%)", xaxt="n");
|
|
264 text(cex=0.6, x=x-0.25, y=-.05, name96, xpd=TRUE, srt=60, adj=1);
|
|
265 dev.off()
|
|
266
|
|
267 # Rarifaction curve.
|
|
268 # Start PDF device driver.
|
|
269 #dev.new(width=10, height=7);
|
|
270 #file_path = get_file_path("geno_rarifaction_curve.pdf");
|
|
271 #pdf(file=file_path, width=10, height=7);
|
|
272 #rarecurve(m, ylab="Number of expected MLGs", sample=min(rowSums(m)), border=NA, fill=NA, font=2, cex=1, col="blue");
|
|
273 #dev.off();
|
|
274
|
|
275 # Genotype accumulation curve, sample is number of
|
|
276 # loci randomly selected for to make the curve.
|
|
277 #dev.new(width=10, height=7);
|
|
278 #file_path = get_file_path("geno_accumulation_curve.pdf");
|
|
279 #pdf(file=file_path, width=10, height=7);
|
|
280 #genotype_curve(gind, sample=5, quiet=TRUE);
|
|
281 #dev.off();
|
|
282
|