forked from Palmer-Lab-UCSD/breedHS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbreedhs.R
More file actions
2199 lines (1856 loc) · 82.3 KB
/
Copy pathbreedhs.R
File metadata and controls
2199 lines (1856 loc) · 82.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## CORE UTILITY FUNCTIONS FOR PALMER LAB HS RATS BREEDER SELECTION CODE
## written by Dr. Ben Johnson ([email protected])
library(tools)
source("kinship.R")
source("find_mates.R")
source("hsw_utils.R")
source("wfu_utils.R")
encode.sex <- function(ped) {
ped[,4] = as.character(ped[,4])
ped[ped[,4]=="F",4] = 0 # Female = 0
ped[ped[,4]=="M",4] = 1 # Male = 1
ped[,4] = as.numeric(ped[,4])
ped = data.matrix(ped)
return(ped)
}
# identify pedigree errors
find.ped.errors <- function(first_gen, # the desired starting generation
last_gen, # the desired last generation
data_dir, # the directory housing pedigree files
file_stem, # the stem name shared by all pedigree files
write_file=TRUE,
return_ids=TRUE,
print_ids=TRUE)
{
# empty element to hold the eventual pedigree
ped <- c()
# empty elements to hold vectors of missing parents
missing_parents <- c()
missing_gens <- c()
missing_parents_files <- c()
missing_kin_files <- c()
empty_parents <- list()
kin_no_parents <- list()
kin_dup_parents <- list()
missing_sex <- c()
first_nchar <- nchar(first_gen)
last_nchar <- nchar(last_gen)
## loop across generations
for (i in first_gen:last_gen){
# save the file name for the previous generation
if (i > first_gen){
prev.file <- file.name
}
# get the file name for the current generation
file.name <- file.path(data_dir, paste0(file_stem, i, '.csv'))
if (!file.exists(file.name)) {
gen_nchar <- nchar(i)
n_zeros <- last_nchar - gen_nchar
i_str <- paste0(rep('0', n_zeros), i)
file.name <- file.path(data_dir, paste0(file_stem, i_str, '.csv'))
}
if (!file.exists(file.name)) {
cat('Cannot find a pedigree file for generation', i, 'at', file.name, '\n')
}
## read in the pedigree for a given generation
ped.tmp = read.table(file=file.name, sep=',', header=T,
as.is=TRUE, na.strings=c('','?','NA'))
## format desired data columns
ped.ids <- ped.tmp[,1]
ped.cols <- c('sire', 'dam', 'sex')
ped.tmp <- cbind(ped.ids, ped.tmp[ped.cols])
colnames(ped.tmp) <- c('id', ped.cols)
# check if any IDs are missing sex values
if (sum(is.na(ped.tmp[,4]))>0) {
missing_sex_idx <- which(is.na(ped.tmp[,4]))
gen_missing_sex <- ped.tmp[,1][missing_sex_idx]
names(gen_missing_sex) <- i
missing_sex <- c(missing_sex, gen_missing_sex)
}
# remove parental data from the first generation
if (i == first_gen){
ped.tmp[,c(2,3)] <- 0}
if (i != first_gen){
## check that parents are in the previous generation
tmp_missing <- check.ped(ped.tmp , ped.prev)
if (length(tmp_missing) > 0) {
missing_parents <- c(missing_parents, tmp_missing)
missing_gens <- c(missing_gens, rep(i,length(tmp_missing)))
missing_parents_files <- c(missing_parents_files, rep(prev.file, length(tmp_missing)))
missing_kin_files <- c(missing_kin_files, rep(file.name, length(tmp_missing)))
# get IDs of offspring whose parents are missing
has_missing_dam <- ped.tmp[,3] %in% tmp_missing
has_missing_sire <- ped.tmp[,2] %in% tmp_missing
offspring_idx <- which(has_missing_dam | has_missing_sire)
if (length(offspring_idx) > 0) {
kin_missing_parents <- data.frame(
id = ped.tmp[offspring_idx, 1],
gen = i,
parent_gen = i-1,
missing_dam = NA,
missing_sire = NA,
stringsAsFactors = FALSE)
# fill in which parents are missing for each offspring
kin_missing_parents$missing_dam[has_missing_dam[offspring_idx]] <-
ped.tmp[offspring_idx[has_missing_dam[offspring_idx]], 3]
kin_missing_parents$missing_sire[has_missing_sire[offspring_idx]] <-
ped.tmp[offspring_idx[has_missing_sire[offspring_idx]], 2]
kin_no_parents[[i]] <- kin_missing_parents
}
cat('Generation', paste0(i, ':'), length(tmp_missing), 'parent IDs were not found in generation', i-1, '\n')
if (print_ids) {
cat('\t', sort(tmp_missing), '\n')
}
} # end of if(length(tmp)>0)
## check for missing values
parent_nans <- ped.tmp[(is.na(ped.tmp$dam)) | (is.na(ped.tmp$sire)),]
if(nrow(parent_nans) > 0) {
parent_nans$generation <- i
parent_nans <- parent_nans[,c('generation','id','dam','sire','sex')]
empty_parents[[i]] <- parent_nans
}
# get IDs of offspring whose parents share the same ID
dup_parent_idx <- which(ped.tmp[,2]==ped.tmp[,3])
ids_w_dup_parents <- ped.tmp[,1][dup_parent_idx]
dup_dams <- ped.tmp[,3][dup_parent_idx]
dup_sires <- ped.tmp[,2][dup_parent_idx]
if (length(dup_parent_idx) > 0) {
dup_parents <- data.frame(
id = ids_w_dup_parents,
gen = i,
parent_gen = i-1,
dam = dup_dams,
sire = dup_sires)
kin_dup_parents <- c(kin_dup_parents, list(dup_parents))
cat('Generation', paste0(i, ':'), 'Dam and sire share the same ID for', nrow(dup_parents), 'samples', '\n')
if (print_ids) {
cat('\t', paste0(ids_w_dup_parents, ' (', dup_dams, ')'), '\n')
}
}
} # end of if(!i==first_gen)
ped.prev <- ped.tmp
ped <- rbind(ped,ped.tmp)
} # end of first_gen:last_gen loop
empty_parents <- do.call(rbind, empty_parents)
kin_no_parents <- do.call(rbind, kin_no_parents)
kin_dup_parents <- do.call(rbind, kin_dup_parents)
if ((is.null(missing_parents)) & (length(empty_parents == 0)) & (length(kin_dup_parents) == 0)){
cat('No errors found in the pedigree \n')
} else {
## write missing parents to a file for investigation
if (write_file) {
datestamp <- format(Sys.time(),'%Y%m%d')
errs_dir <- file.path(data_dir, paste0('ped_errors_',datestamp))
dir.create(errs_dir, showWarnings=F)
cat('See file(s) for details: \n')
if (!is.null(missing_parents)) {
missing_df <- data.frame(
id = missing_parents,
gen = missing_gens-1,
kin_gen = missing_gens,
ped = missing_parents_files,
kin_ped = missing_kin_files)
outstr1 <- paste0(file_stem, '_',
rep('0',(last_nchar-first_nchar)),
first_gen, '_', last_gen,
'_ped_error_missing_parents_', datestamp, '.csv')
outfile1 <- file.path(errs_dir, outstr1)
write.csv(missing_df, outfile1, row.names=F, quote=F)
cat(outfile1, '\n')
outstr2 <- paste0(file_stem, '_',
rep('0',(last_nchar-first_nchar)),
first_gen, '_', last_gen,
'_ped_error_kin_w_missing_parents_', datestamp, '.csv')
outfile2 <- file.path(errs_dir, outstr2)
write.csv(kin_no_parents, outfile2, row.names=F, quote=F)
cat(outfile2, '\n')
}
if (length(empty_parents != 0)) {
outstr3 <- paste0(file_stem, '_',
rep('0',(last_nchar-first_nchar)),
first_gen, '_', last_gen,
'_ped_error_parent_NAs_', datestamp, '.csv')
outfile3 <- file.path(errs_dir, outstr3)
write.csv(empty_parents, outfile3, row.names=F, quote=F)
cat(outfile3, '\n')
}
if (length(kin_dup_parents) != 0) {
outstr4 <- paste0(file_stem, '_',
rep('0',(last_nchar-first_nchar)),
first_gen, '_', last_gen,
'_ped_error_parents_same_ids_', datestamp, '.csv')
outfile4 <- file.path(errs_dir, outstr4)
write.csv(kin_dup_parents, outfile4, row.names=F, quote=F)
cat(outfile4, '\n')
}
if (length(missing_parents) != 0) {
outstr5 <- paste0(file_stem, '_',
rep('0',(last_nchar-first_nchar)),
first_gen, '_', last_gen,
'_ped_error_missing_sex_', datestamp, '.csv')
outfile5 <- file.path(errs_dir, outstr5)
write.csv(missing_parents, outfile5, row.names=T, quote=F)
cat(outfile5, '\n')
}
}
if (return_ids) {
return(list(unfound_parents = missing_parents,
empty_parents = empty_parents,
offspring_without_parents = kin_no_parents,
dup_parent_ids = kin_dup_parents))
}
}
}
# format multiple pedigree files (from one population) into a single pedigree
format.pedigree <- function(first_gen, # the desired starting generation
last_gen, # the desired last generation
data_dir, # the directory housing pedigree files
file_stem, # the stem name shared by all pedigree files
print_errors = TRUE)
{
# empty element to hold the eventual pedigree
ped <- c()
first_nchar <- nchar(first_gen)
last_nchar <- nchar(last_gen)
## loop across generations
for (i in first_gen:last_gen){
# get the file name for the current generation
file.name <- file.path(data_dir, paste0(file_stem, i, ".csv"))
if (!file.exists(file.name)) {
gen_nchar <- nchar(i)
n_zeros <- last_nchar - gen_nchar
i_str <- paste0(rep('0', n_zeros), i)
file.name <- file.path(data_dir, paste0(file_stem, i_str, ".csv"))
}
if (!file.exists(file.name)) {
cat('Cannot find a pedigree file for generation', i, 'at', file.name, '\n')
}
## read in the pedigree for a given generation
ped.tmp = read.table(file=file.name, sep=",", header=T,
as.is=TRUE, na.strings="?")
## format desired data columns
ped.ids <- ped.tmp[,1]
ped.cols <- c('sire', 'dam', 'sex')
ped.tmp <- cbind(ped.ids, ped.tmp[ped.cols])
colnames(ped.tmp) <- c('id', ped.cols)
# remove parental data from the first generation
if (i == first_gen){
ped.tmp[,c(2,3)] <- 0}
if (i != first_gen){
## drop rows with NA values for parents
# ped.tmp <- ped.tmp[complete.cases(ped.tmp),]
if (print_errors){
# check that parents are in the previous generation
tmp <- check.ped(ped.tmp , ped.prev)
if (length(tmp) > 0){
cat('Generation', paste0(i, ':'), length(tmp), 'parent IDs were not found in generation', i-1, '\n')
cat('\t', sort(tmp), '\n')
}
}
}
ped.prev <- ped.tmp
ped <- rbind(ped,ped.tmp)
} # end of generation loop
## change sex coding from alphabetical to numeric, where F:0, M:1
ped.tmp <- encode.sex(ped.tmp)
ped <- encode.sex(ped)
out <- list(ped.tmp = ped.tmp, ped = ped)
return(out)
}
# combine pedigrees
get.ped.comb <- function(prev_pedigree, breed_results){
first.os <- max(prev_pedigree[,1]) + 1000
next_pedigree <- cbind(first.os:(first.os+(dim(breed_results)[1]-1)),
breed_results[,1:2], rep(1,dim(breed_results)[1]))
prev_pedigree <- as.data.frame(prev_pedigree, )
next_pedigree <- as.data.frame(next_pedigree, )
names(next_pedigree)[1:4] <- c("ID","Father","Mother","Sex")
names(prev_pedigree) <- c("ID","Father","Mother","Sex")
ped.comb <- rbind(prev_pedigree, next_pedigree)
out <- list(ped.comb=ped.comb, ped.prev=prev_pedigree, ped.next=next_pedigree)
return(out)
}
# wrapper function to conduct all breedail breeder selection
select.breeders <- function(first_gen, # first generation of the pedigree
last_gen, # final generation of the pedigree
data_dir, # directory housing pedigree files
out_dir, # the output directory in which to save results
file_stem, # stem name for pedigree files
one_per_sibship = TRUE, # whether one (T) or multiple breeders per sibship
verbose = FALSE) # set TRUE for troubleshooting
{
MAX_ROUNDS <- 10 # Maximum number of rounds to attempt
# format pedigree files into one pedigree
ped.out <- format.pedigree(first_gen, last_gen, data_dir, file_stem, print_errors=F)
ped.tmp <- ped.out$ped.tmp
ped <- ped.out$ped
## build the covariance matrix
k <- kinship(ped)
## get dimensions from kinship matrix
N <- dim(k)[1]
no <- dim(ped.tmp)[1]
idx <- (N-no+1):N
k.prev <- k[idx,idx]
ped.prev <- ped[idx,]
# first mate pairing
if (one_per_sibship){
sibs <- 'one_per_sibship'
first.breeders <- find.mates.res(ped.prev,k.prev, verbose = verbose)
} else {
sibs <- 'multi_per_sibship'
first.breeders <- find.mates(ped.prev,k.prev, verbose = verbose)
}
if (verbose) {
cat('first.breeders: \n')
print(str(first.breeders))
}
# note: breedail pedigree columns are ordered sire/dam
# but find.mates outputs are ordered dam/sire
colnames(first.breeders) <- c('dam', 'sire', 'kinship')
round.1 <- rep(1, nrow(first.breeders))
round <- round.1
ped.comb.out <- get.ped.comb(ped.prev, first.breeders)
ped.comb <- ped.comb.out$ped.comb
ped.prev <- ped.comb.out$ped.prev
ped.next <- ped.comb.out$ped.next
## update kinship matrix ##
k.comb <- kinship.update(ped.prev, k.prev, ped.next)
pos.prev <- 1:dim(ped.prev)[1]
pos.next <- dim(ped.prev)[1]+(1:dim(ped.next)[1])
not.avail.idx <- ped.prev[,1] %in% c(ped.next[,2],ped.next[,3])
not.avail.pos <- c(1:dim(ped.prev)[1])[not.avail.idx]
# second mate pairing (now using default max_pairs)
new.mates <- find.mates.given.pop(ped.comb, k.comb, pos.prev, pos.next, not.avail.pos, verbose = verbose)
if (verbose) {
cat('new.mates: \n')
print(str(new.mates))
}
# Initialize storage for all rounds
all.mates <- list()
round.numbers <- list()
all.mates[[1]] <- first.breeders
round.numbers[[1]] <- round.1
if (!is.null(new.mates)) {
all.mates[[2]] <- new.mates[,1:3]
round.numbers[[2]] <- rep(2, nrow(new.mates))
}
# Try additional rounds (3 onwards)
for (i in 3:MAX_ROUNDS) {
tryCatch({
# Get combined pedigree for all previous rounds
all.breeders <- do.call(rbind, all.mates[1:(i-1)])
ped.comb.out <- get.ped.comb(ped.prev, all.breeders)
ped.comb <- ped.comb.out$ped.comb
ped.prev <- ped.comb.out$ped.prev
ped.next <- ped.comb.out$ped.next
## update kinship matrix
k.comb <- kinship.update(ped.prev, k.prev, ped.next)
pos.prev <- 1:dim(ped.prev)[1]
pos.next <- dim(ped.prev)[1]+(1:dim(ped.next)[1])
not.avail.idx <- ped.prev[,1] %in% c(ped.next[,2],ped.next[,3])
not.avail.pos <- c(1:dim(ped.prev)[1])[not.avail.idx]
# next round of mate pairing
new.mates <- find.mates.given.pop(ped.comb, k.comb,
pos.prev, pos.next, not.avail.pos, verbose = verbose)
if (!is.null(new.mates) && nrow(new.mates) > 0) {
all.mates[[i]] <- new.mates[,1:3]
round.numbers[[i]] <- rep(i, nrow(new.mates))
} else {
break
}
}, error = function(e) {
cat(sprintf("Round %d: %s\n", i, conditionMessage(e)))
})
# If no new mates were found or an error occurred, stop trying new rounds
if (is.null(all.mates[[i]])) {
break
}
}
# Process all successful rounds
all.breeders <- do.call(rbind, all.mates)
round <- unlist(round.numbers)
all.breeders <- as.data.frame(cbind(round, all.breeders))
all.breeders <- all.breeders[order(all.breeders$kinship),]
timestamp <- format(Sys.time(),'%Y%m%d')
outfile <- file.path(out_dir, paste0('breedpairs_F', last_gen, '_n', length(all.mates),
'_', sibs, '_', timestamp, '.csv'))
write.csv(all.breeders, outfile, quote=F, row.names=F)
cat('Successfully paired', nrow(all.breeders), 'breeder pairs \n')
cat('Pairing file written to', outfile, '\n')
return(list(pairs = all.breeders, file = outfile))
}
# simulate breeding between mate pairs
mate.breeders <- function(breedpairs, # matrix output by select.breeders, or path to file
n_pairs=NULL, # number of pairs to breed, default is all pairs
n_sibs, # number of offspring per pair
outfile=NULL) # file to save new gen pedigree
{
if (class(breedpairs)[1]=='matrix'){
breedpairs <- as.data.frame(breedpairs)
} else if (class(breedpairs)[1]=='character'){
breedpairs <- read.table(breedpairs, sep='\t', header=T)
}
if (!is.null(n_pairs)){
sample_idx <- sort(sample(1:nrow(breedpairs), n_pairs))
dam <- breedpairs$dam[sample_idx]
dam <- rep(dam, each=n_sibs)
sire <- breedpairs$sire[sample_idx]
sire <- rep(sire, each=n_sibs)
} else {
dam <- rep(breedpairs$dam, each=n_sibs)
sire <- rep(breedpairs$sire, each=n_sibs)
}
sex <- rep(c('F','M'), length.out=length(dam))
first_id <- max(c(breedpairs$dam, breedpairs$sire)) + 1
last_id <- max(c(breedpairs$dam, breedpairs$sire)) + length(dam)
id <- seq.int(first_id,last_id)
new_gen <- data.frame(id, sex, dam, sire)
if (!is.null(outfile)){
write.csv(new_gen, outfile, row.names=F, quote=F)
}
return(new_gen)
}
# format the desired columns from a pedigree dataframe
format.ped.cols <- function(df){
## Format desired data columns
ped.ids <- df[,1]
ped.cols <- c('sire', 'dam', 'sex')
ped <- cbind(ped.ids, df[ped.cols])
colnames(ped) <- c('id', ped.cols)
return(ped)
}
# get breeding pairs for a breeder exchange between two colonies
# population 1 must be the original founder of pop 2
exchange.breeders <- function(
dir_1, # directory of ped files for population 1
stem_1, # file name stem for pop 1 pedigree files
first_gen_1, # number of the first generation analyzed from pop 1
last_gen_1, # number of the final (exchange) generation from pop 1
dir_2, # directory of ped files for population 2
stem_2, # file name stem for pop 2 pedigree files
first_gen_2, # number of the first generation analyzed from pop 2
last_gen_2, # number of the final (exchange) generation from pop 2
out_dir, # directory in which to store output files
out_stem, # file name stem of output files
one_per_sibship=TRUE) # boolean: one or multiple breeders per sibship
{
ped1_all <- format.pedigree(first_gen_1, last_gen_1-1, dir_1, stem_1, print_errors = F)$ped
ped2_all <- format.pedigree(first_gen_2, last_gen_2-1, dir_2, stem_2, print_errors = F)$ped
ped1_now <- format.pedigree(first_gen_1, last_gen_1, dir_1, stem_1, print_errors = F)$ped.tmp
ped2_now <- format.pedigree(first_gen_2, last_gen_2, dir_2, stem_2, print_errors = F)$ped.tmp
# remove duplicates from hsw
ped2_all <- ped2_all[!ped2_all[,1] %in% ped1_all[,1],]
merged_ped <- rbind(ped1_all, ped2_all)
merged_ped <- merged_ped[order(merged_ped[,1]),]
# artificially create a final generation by merging potential breeders
# from either population
m1 <- ped1_now[ped1_now[,4]==1,]
f1 <- ped1_now[ped1_now[,4]==0,]
m2 <- ped2_now[ped2_now[,4]==1,]
f2 <- ped2_now[ped2_now[,4]==0,]
m1f2_now <- rbind(m1, f2) # wfu M, hsw F final gen
m2f1_now <- rbind(m2, f1) # hsw M, wfu F final gen
ped1 <- rbind(merged_ped, m1f2_now)
ped2 <- rbind(merged_ped, m2f1_now)
# estimate kinship and get dimensions from kinship matrix
k1 <- kinship(ped1)
k2 <- kinship(ped2)
N1 <- dim(k1)[1] # total number of rats in the pop1 pedigree
no1 <- dim(m1f2_now)[1] # number of rats in final generation
idx1 <- (N1-no1+1):N1 # index positions for final gen rats
k.prev1 <- k1[idx1,idx1] # kinship matrix of previous generations
ped.prev1 <- ped1[idx1,] # pedigree of just final gen
N2 <- dim(k2)[1]
no2 <- dim(m2f1_now)[1]
idx2 <- (N2-no2+1):N2
k.prev2 <- k2[idx2,idx2]
ped.prev2 <- ped2[idx2,]
# first mate pairing
if (one_per_sibship){
round1.breeders1 <- find.mates.res(ped.prev1,k.prev1, verbose = verbose)
round1.breeders2 <- find.mates.res(ped.prev2,k.prev2, verbose = verbose)
} else {
round1.breeders1 <- find.mates(ped.prev1,k.prev1, verbose = verbose)
round1.breeders2 <- find.mates(ped.prev2,k.prev2, verbose = verbose)
}
round1.idx1 <- rep(1, nrow(round1.breeders1))
round1.idx2 <- rep(1, nrow(round1.breeders2))
all.breeders1 <- cbind(round1.idx1, round1.breeders1)
all.breeders2 <- cbind(round1.idx2, round1.breeders2)
colnames(all.breeders1) <- c('round', 'sire', 'dam', 'kinship')
colnames(all.breeders2) <- c('round', 'sire', 'dam', 'kinship')
# update pedigrees
first.os1 <- max(ped.prev1[,1])+9999
ped.next1 <- cbind(first.os1:(first.os1+(dim(round1.breeders1)[1]-1)),
round1.breeders1[,1:2], rep(1,dim(round1.breeders1)[1]))
ped.prev1 <- as.data.frame(ped.prev1, )
ped.next1 <- as.data.frame(ped.next1, )
ped.cols <- c('ID', 'Father', 'Mother', 'Sex')
names(ped.next1) <- ped.cols
names(ped.prev1) <- ped.cols
ped.comb1 <- rbind(ped.prev1, ped.next1)
first.os2 <- max(ped.prev2[,1])+1000
ped.next2 <- cbind(first.os2:(first.os2+(dim(round1.breeders2)[1]-1)),
round1.breeders2[,1:2], rep(1,dim(round1.breeders2)[1]))
ped.prev2 <- as.data.frame(ped.prev2, )
ped.next2 <- as.data.frame(ped.next2, )
names(ped.next2)[1:4] <- ped.cols
names(ped.prev2) <- ped.cols
ped.comb2 <- rbind(ped.prev2, ped.next2)
# update kinship matrices
k.comb1 <- kinship.update(ped.prev1 , k.prev1, ped.next1)
pos.prev1 <- 1:dim(ped.prev1)[1]
pos.next1 <- dim(ped.prev1)[1]+(1:dim(ped.next1)[1])
not.avail.idx1 <- ped.prev1[,1] %in% c(ped.next1[,2],ped.next1[,3])
not.avail.pos1 <- c(1:dim(ped.prev1)[1])[not.avail.idx1]
k.comb2 <- kinship.update(ped.prev2 , k.prev2, ped.next2)
pos.prev2 <- 1:dim(ped.prev2)[1]
pos.next2 <- dim(ped.prev2)[1]+(1:dim(ped.next2)[1])
not.avail.idx2 <- ped.prev2[,1] %in% c(ped.next2[,2],ped.next2[,3])
not.avail.pos2 <- c(1:dim(ped.prev2)[1])[not.avail.idx2]
# second mate pairing
round2.breeders1 <- find.mates.given.pop(ped.comb1, k.comb1,
pos.prev1, pos.next1, not.avail.pos1, verbose = verbose)
round2.breeders2 <- find.mates.given.pop(ped.comb2, k.comb2,
pos.prev2, pos.next2, not.avail.pos2, verbose = verbose)
if (!is.null(round2.breeders1)){
round2.idx1 <- rep(2, nrow(round2.breeders1))
round2.breeders1 <- cbind(round2.idx1, round2.breeders1[,1:3])
all.breeders1 <- rbind(all.breeders1, round2.breeders1)
}
if (!is.null(round2.breeders2)){
round2.idx2 <- rep(2, nrow(round2.breeders2))
round2.breeders2 <- cbind(round2.idx2, round2.breeders2[,1:3])
all.breeders2 <- rbind(all.breeders2, round2.breeders2)
}
# update pedigrees
breed.rslts1 <- rbind(round1.breeders1 , round2.breeders1[,2:4])
ped.next1 <- cbind(first.os1:(first.os1+(dim(breed.rslts1)[1]-1)),
breed.rslts1[,1:2], rep(1,dim(breed.rslts1)[1]))
ped.prev1 <- as.data.frame(ped.prev1, )
ped.next1 <- as.data.frame(ped.next1, )
names(ped.next1)[1:4] <- ped.cols
names(ped.prev1) <- ped.cols
ped.comb1 <- rbind(ped.prev1, ped.next1)
breed.rslts2 <- rbind(round1.breeders2 , round2.breeders2[,2:4])
ped.next2= cbind(first.os2:(first.os2+(dim(breed.rslts2)[1]-1)),
breed.rslts2[,1:2], rep(1,dim(breed.rslts2)[1]))
ped.prev2 <- as.data.frame(ped.prev2, )
ped.next2 <- as.data.frame(ped.next2, )
names(ped.next2)[1:4] <- ped.cols
names(ped.prev2) <- ped.cols
ped.comb2 <- rbind(ped.prev2, ped.next2)
# update kinship matrices
k.comb1 <- kinship.update(ped.prev1 , k.prev1, ped.next1)
pos.prev1 <- 1:dim(ped.prev1)[1]
pos.next1 <- dim(ped.prev1)[1]+(1:dim(ped.next1)[1])
not.avail.idx1 <- ped.prev1[,1] %in% c(ped.next1[,2],ped.next1[,3])
not.avail.pos1 <- c(1:dim(ped.prev1)[1])[not.avail.idx1]
k.comb2 <- kinship.update(ped.prev2 , k.prev2, ped.next2)
pos.prev2 <- 1:dim(ped.prev2)[1]
pos.next2 <- dim(ped.prev2)[1]+(1:dim(ped.next2)[1])
not.avail.idx2 <- ped.prev2[,1] %in% c(ped.next2[,2],ped.next2[,3])
not.avail.pos2 <- c(1:dim(ped.prev2)[1])[not.avail.idx2]
# third mate pairing
round3.breeders1 <- find.mates.given.pop(ped.comb1, k.comb1,
pos.prev1, pos.next1, not.avail.pos1, verbose = verbose)
round3.breeders2 <- find.mates.given.pop(ped.comb2, k.comb2,
pos.prev2, pos.next2, not.avail.pos2, verbose = verbose)
if (!is.null(round3.breeders1)){
round3.idx1 <- rep(3, nrow(round3.breeders1))
round3.breeders1 <- cbind(round3.idx1, round3.breeders1[,1:3])
all.breeders3 <- rbind(all.breeders1, round3.breeders1)
}
if (!is.null(round3.breeders2)){
round3.idx2 <- rep(3, nrow(round3.breeders2))
round3.breeders2 <- cbind(round3.idx2, round3.breeders2[,1:3])
all.breeders2 <- rbind(all.breeders2, round3.breeders2)
}
# update pedigrees
breed.rslts1 <- rbind(round1.breeders1 , round2.breeders1[,2:4], round3.breeders1[,2:4])
ped.next1 <- cbind(first.os1:(first.os1+(dim(breed.rslts1)[1]-1)),
breed.rslts1[,1:2], rep(1,dim(breed.rslts1)[1]))
ped.prev1 <- as.data.frame(ped.prev1, )
ped.next1 <- as.data.frame(ped.next1, )
names(ped.next1)[1:4] <- ped.cols
names(ped.prev1) <- ped.cols
ped.comb1 <- rbind(ped.prev1, ped.next1)
breed.rslts2 <- rbind(round1.breeders2 , round2.breeders2[,2:4], round3.breeders2[,2:4])
ped.next2= cbind(first.os2:(first.os2+(dim(breed.rslts2)[1]-1)),
breed.rslts2[,1:2], rep(1,dim(breed.rslts2)[1]))
ped.prev2 <- as.data.frame(ped.prev2, )
ped.next2 <- as.data.frame(ped.next2, )
names(ped.next2)[1:4] <- ped.cols
names(ped.prev2) <- ped.cols
ped.comb2 <- rbind(ped.prev2, ped.next2)
# update kinship matrices
k.comb1 <- kinship.update(ped.prev1 , k.prev1, ped.next1)
pos.prev1 <- 1:dim(ped.prev1)[1]
pos.next1 <- dim(ped.prev1)[1]+(1:dim(ped.next1)[1])
not.avail.idx1 <- ped.prev1[,1] %in% c(ped.next1[,2],ped.next1[,3])
not.avail.pos1 <- c(1:dim(ped.prev1)[1])[not.avail.idx1]
k.comb2 <- kinship.update(ped.prev2 , k.prev2, ped.next2)
pos.prev2 <- 1:dim(ped.prev2)[1]
pos.next2 <- dim(ped.prev2)[1]+(1:dim(ped.next2)[1])
not.avail.idx2 <- ped.prev2[,1] %in% c(ped.next2[,2],ped.next2[,3])
not.avail.pos2 <- c(1:dim(ped.prev2)[1])[not.avail.idx2]
# fourth mate pairing
round4.breeders1 <- find.mates.given.pop(ped.comb1, k.comb1,
pos.prev1, pos.next1, not.avail.pos1, verbose = verbose)
round4.breeders2 <- find.mates.given.pop(ped.comb2, k.comb2,
pos.prev2, pos.next2, not.avail.pos2, verbose = verbose)
if (!is.null(round4.breeders1)){
round4.idx1 <- rep(4, nrow(round4.breeders1))
round4.breeders1 <- cbind(round4.idx1, round4.breeders1[,1:3])
all.breeders1 <- rbind(all.breeders1, round4.breeders1)
}
if (!is.null(round4.breeders2)){
round4.idx2 <- rep(4, nrow(round4.breeders2))
round4.breeders2 <- cbind(round4.idx2, round4.breeders2[,1:3])
all.breeders2 <- rbind(all.breeders2, round4.breeders2)
}
if (one_per_sibship){
write.table(all.breeders1, file.path(out_dir, paste0(out_stem, '_M1F2_breedpairs_one_per_sibship.txt')),
sep='\t', row.names=F, quote=F)
write.table(all.breeders2, file.path(out_dir, paste0(out_stem, '_M2F1_breedpairs_one_per_shibship.txt')),
sep='\t', row.names=F, quote=F)
} else {
write.table(all.breeders1, file.path(out_dir, paste0(out_stem, '_M1F2_breedpairs_multi_per_sibship.txt')),
sep='\t', row.names=F, quote=F)
write.table(all.breeders2, file.path(out_dir, paste0(out_stem, '_M2F1_breedpairs_multi_per_sibship.txt')),
sep='\t', row.names=F, quote=F)
}
return(list(M1F2 = all.breeders1, M2F1 = all.breeders2))
}
# create a named vector of all generations (from a single population) involved in sample exchanges
name.exchanges <- function(sent, # vector of generations sent to the other population
received) # vector of generations that received from the other population
{
all_exchanges <- as.character(sort(unique(as.numeric(c(sent, received)))))
events <- c()
for (event in all_exchanges) {
if ((event %in% sent) & !(event %in% received)) {
event_type <- 'sent'
if (as.numeric(event) == min(as.numeric(all_exchanges))){
event_type <- 'sent founders'
}
}
else if (!(event %in% sent) & (event %in% received)) {
event_type <- 'received'
if (as.numeric(event) == min(as.numeric(all_exchanges))){
event_type <- 'received founders'
}
}
else if ((event %in% sent) & (event %in% received)) {
event_type <- 'exchanged'
}
events <- c(events, event_type)
}
names(all_exchanges) <- events
return(all_exchanges)
}
# format multiple pedigree files (from one population) to prep them
# for merging with pedigree files from another population
format.pedigree.for.merge <- function(
first_gen, # the desired starting generation
last_gen, # the desired last generation
data_dir, # the directory housing pedigree files
file_stem) # the stem name shared by all pedigree files
{
# empty element to hold the eventual pedigree
ped <- c()
first_nchar <- nchar(first_gen)
last_nchar <- nchar(last_gen)
## loop across generations
for (i in first_gen:last_gen){
# get the file name for the current generation
file.name <- file.path(data_dir, paste0(file_stem, i, ".csv"))
if (!file.exists(file.name)) {
gen_nchar <- nchar(i)
n_zeros <- last_nchar - gen_nchar
i_str <- paste0(rep('0', n_zeros), i)
file.name <- file.path(data_dir, paste0(file_stem, i_str, ".csv"))
}
if (!file.exists(file.name)) {
cat('Cannot find a pedigree file for generation', i, 'at', file.name, '\n')
}
## read in the pedigree for a given generation
ped.tmp = read.table(file=file.name, sep=",", header=T,
as.is=TRUE, na.strings="?")
## format desired data columns
ped.ids <- ped.tmp[,1]
ped.cols <- c('sire', 'dam', 'sex', 'generation')
ped.tmp <- cbind(ped.ids, ped.tmp[ped.cols])
colnames(ped.tmp) <- c('id', ped.cols)
# order by ID
ped.tmp <- as.data.frame(ped.tmp)
ped.tmp <- as.matrix(ped.tmp[order(ped.tmp[,1]),])
# remove parental data from the first generation
if (i == first_gen){
ped.tmp[,c(2,3)] <- 0}
ped <- rbind(ped,ped.tmp)
} # end of generation loop
# change sex coding from alphabetical to numeric, where F:0, M:1
ped <- encode.sex(ped)
ped <- as.data.frame(ped)
# split pedigree by generations
for (col in colnames(ped)) {
ped[[col]] <- as.numeric(ped[[col]])
}
ped$generation <- as.numeric(ped$generation)
ped_gens <- split(ped, ped$generation)
out <- ped_gens
return(out)
}
# merge the pedigrees of two exchanging populations into a single pedigree
# with a new set of IDs for all individuals
# LEGACY VERSION - not currently used but kept here in case it is somehow needed later
merge.pedigrees1 <- function(
ped_map, # pedigree map: path to csv with per-population gen numbers for all shared generations
ex_wfu_hsw, # exchange history from wfu to hsw: path to csv w/ cols wfu_from, hsw_to
ex_hsw_wfu, # exchange history from hsw to wfu: path csv w/ cols hsw_from, wfu_to
dir_wfu, # path to wfu pedigrees
stem_wfu, # filename stem for wfu pedigrees
first_gen_wfu, # number of the first generation to include from the wfu pedigree
last_gen_wfu, # number of the final generation to include from the wfu pedigree
dir_hsw, # path to hsw pedigrees
stem_hsw, # filename stem for hsw pedigrees
first_gen_hsw, # number of the first generation to include from the hsw pedigree
last_gen_hsw, # number of the final generation to include from the hsw pedigree
merge_into, # set the merge direction: 'wfu' = from hsw into wfu, 'hsw' = from wfu into hsw
as_df=TRUE, # set the output type: T = dataframe, F = list of per-gen dataframes
out_dir, # the path and base file stem for all output pedigree files
out_stem, # the stem name for all merged pedigree files to be saved
verbose=FALSE) # set TRUE for troubleshooting
{
if (verbose) cat('TROUBLESHOOTING PEDIGREE MERGE \n\n')
# read in generation data and classify pedigree generations for each population
ped_map <- read.csv(ped_map)
ex_wfu_hsw <- read.csv(ex_wfu_hsw)
ex_hsw_wfu <- read.csv(ex_hsw_wfu)
wfu_all_gens <- as.character(ex_wfu_hsw[,1])
hsw_all_gens <- as.character(ex_hsw_wfu[,1])
wfu_shared_gens <- as.character(ped_map[,1])
hsw_shared_gens <- as.character(ped_map[,2])
wfu_separate_gens <- setdiff(wfu_all_gens, wfu_shared_gens)
hsw_separate_gens <- setdiff(hsw_all_gens, hsw_shared_gens)
wfu_sent <- ex_wfu_hsw[complete.cases(ex_wfu_hsw),]
hsw_sent <- ex_hsw_wfu[complete.cases(ex_hsw_wfu),]
wfu_received <- as.character(hsw_sent[,2])
hsw_received <- as.character(wfu_sent[,2])
wfu_sent <- as.character(wfu_sent[,1])
hsw_sent <- as.character(hsw_sent[,1])
if (verbose) {
cat('\t', 'wfu_sent:', wfu_sent, '\n')
cat('\t', 'wfu_received:', wfu_received, '\n')
cat('\t', 'hsw_sent:', hsw_sent, '\n')
cat('\t', 'hsw_received:', hsw_received, '\n\n')
}
# construct named vectors of exchanges
wfu_exchanges <- name.exchanges(wfu_sent, wfu_received)
hsw_exchanges <- name.exchanges(hsw_sent, hsw_received)
last_wfu_exchange <- as.numeric(wfu_exchanges[length(wfu_exchanges)])
last_hsw_exchange <- as.numeric(hsw_exchanges[length(hsw_exchanges)])
if (verbose) {
cat('\t', 'wfu_exchanges:', wfu_exchanges, '\n')
cat('\t', 'last_wfu_exchange:', last_wfu_exchange, '\n')
cat('\t', 'hsw_exchanges:', hsw_exchanges, '\n\n')
cat('\t', 'last_hsw_exchange:', last_hsw_exchange, '\n')
}
# format pedigrees for each population
wfu_ped <- format.pedigree.for.merge(first_gen_wfu, last_gen_wfu, dir_wfu, stem_wfu)
hsw_ped <- format.pedigree.for.merge(first_gen_hsw, last_gen_hsw, dir_hsw, stem_hsw)
# set up generations to merge: any that recieved samples from the other population,
# plus the generation prior to each receiving generation
# merge by 'perspective' of the receiving population: merge the sending pop into the receiving pop
if (merge_into == 'wfu') {
receiving_pop <- 'wfu'
sending_pop <- 'hsw'
receiving_ped <- wfu_ped
sending_ped <- hsw_ped
receiving_exchanges <- wfu_exchanges
sending_exchanges <- hsw_exchanges
receiving_all_gens <- wfu_all_gens
receiving_history <- ex_hsw_wfu
last_receiving_gen <- last_gen_wfu
last_receiving_exchange <- last_wfu_exchange
last_sending_gen <- last_gen_hsw
last_sending_exchange <- last_hsw_exchange
} else if (merge_into == 'hsw') {
receiving_pop <- 'hsw'
sending_pop <- 'wfu'
receiving_ped <- hsw_ped
sending_ped <- wfu_ped
receiving_exchanges <- hsw_exchanges
sending_exchanges <- wfu_exchanges
receiving_all_gens <- hsw_all_gens
receiving_history <- ex_wfu_hsw
last_receiving_gen <- last_gen_hsw
last_receiving_exchange <- last_hsw_exchange
last_sending_gen <- last_gen_wfu
last_sending_exchange <- last_wfu_exchange
}
received_gens <- receiving_exchanges[names(receiving_exchanges) %in% c('received','exchanged')]
received_prior_gens <- as.character(as.numeric(received_gens) - 1)
receiving_gens_to_merge <- sort(c(received_gens, received_prior_gens))
sent_gens <- as.character(receiving_history[receiving_history[,2] %in% received_gens, 1])
sent_prior_gens <- as.character(as.numeric(sent_gens) - 1)
# if the current generation is an exchange generation, remove it from eligibility for merging
# (exchanged animals should be incorporated into the "official" pedigree for the receiving population)
# using either hsw_into_wfu_raw() or wfu_into_hsw_raw()
if (last_receiving_exchange == last_receiving_gen) {
receiving_gens_to_merge <- receiving_gens_to_merge[-length(receiving_gens_to_merge)]
}
if (verbose) {
cat('\t', 'sending_pop:', sending_pop, '| receiving_pop:', receiving_pop, '\n')
cat('\t', 'sent_gens:', sent_gens, '\n')
cat('\t', 'received_gens:', received_gens, '\n')
cat('\t', 'receiving_gens_to_merge:', receiving_gens_to_merge, '\n\n')
}
# incorporate simple generations (that don't need merging) into the merged pedigree
merged_ped <- list()
for (gen in receiving_all_gens) {
if (!gen %in% receiving_gens_to_merge){
ped <- receiving_ped[[gen]]