-
Notifications
You must be signed in to change notification settings - Fork 4
/
bayes_02_impute_NA_vars.R
1543 lines (1263 loc) · 83.8 KB
/
bayes_02_impute_NA_vars.R
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
# Author: Kelvin Gorospe
# Impute all missing values for:
# FCR
# Feed proportions
# All energy inputs: Electricity, Diesel, Petrol, Natural Gas
# Yield
# Apply edible weight adjustment
# First run: 01_process_data_for_analysis.R, to make lca_dat_clean_groups
rm(list=ls()[!(ls() %in% c("lca_dat_clean_groups", "datadir", "outdir"))])
# Or just reset libraries/directories and read in lca_dat_clean_groups:
library(tidyverse)
library(rstan)
library(data.table)
library(countrycode)
library(bayesplot) # for mcmc_areas_ridges
library(shinystan)
library(brms)
library(tidybayes)
datadir <- "/Volumes/jgephart/BFA Environment 2/Data"
outdir <- "/Volumes/jgephart/BFA Environment 2/Outputs"
lca_dat_clean_groups <- read.csv(file.path(outdir, "lca_clean_with_groups.csv"))
######################################################################################################
# Section 1: Create feed_model_dat_categories for modeling FCR and feed proportions
# Remove species that aren't fed: bivalves, plants
# SELECT STUDY ID COLUMN - use this for rejoining outputs from multiple regression models back together
# Select relevant data columns and arrange by categorical info
feed_model_dat_categories <- lca_dat_clean_groups %>%
select(study_id, fcr = FCR, contains("new"), clean_sci_name, taxa, intensity = Intensity, system = Production_system_group) %>%
arrange(clean_sci_name, taxa, intensity, system) %>%
filter(taxa %in% c("bivalves", "plants")==FALSE) # Remove taxa that don't belong in FCR/feed analysis - bivalves
######################################################################################################
# Step 1: Model FCR as taxa + intensity + system
# ie, remove all NAs and model these data, then use the model to predict FCR for those data with a complete set of predictors
fcr_no_na <- feed_model_dat_categories %>%
#filter(fcr != 0 | is.na(fcr)) %>% # If we want to retain NAs, have to explicitly include is.na(fcr) otherwise NA's get dropped by fcr != 0
filter(fcr != 0) %>% # This also automatically drops NAs
filter(is.na(intensity)==FALSE & is.na(system)==FALSE) %>% # complete predictors - i.e., both intensity AND system are non-NA
select(study_id, fcr, clean_sci_name, taxa, intensity, system)
# Create model matrix for taxa info, then center and scale
options(na.action='na.pass') # First change default options for handling missing data
X_taxa <- model.matrix(object = ~ 1 + taxa,
data = fcr_no_na %>% select(taxa))
options(na.action='na.omit') # Return option back to the default
taxa_sd <- apply(X_taxa[,-1], MARGIN=2, FUN=sd, na.rm=TRUE) # Center all non-intercept variables and scale by 2 standard deviations (ignoring NAs)
options(na.action='na.pass') # First change default options for handling missing data
X_taxa_scaled <- scale(X_taxa[,-1], center=TRUE, scale=2*taxa_sd)
options(na.action='na.omit') # Return option back to the default
# Format intensity and system as ordinal variables, then center and scale
X_ordinal <- fcr_no_na %>%
mutate(intensity = factor(intensity, levels = c("Extensive", "Imp. extensive", "Semi-intensive", "Intensive"))) %>% # set order of factors (low = extensive, high = intensive)
mutate(system = factor(system, levels = c("On- and off-bottom", "Cages & pens", "Ponds", "Recirculating and tanks"))) %>% # set order of factors (low = open, high = closed)
mutate(intensity = as.numeric(intensity)) %>%
mutate(system = as.numeric(system)) %>%
select(intensity, system) %>%
as.matrix()
ordinal_sd<-apply(X_ordinal, MARGIN=2, FUN=sd, na.rm=TRUE) # Center all non-intercept variables and scale by 2 standard deviations (ignoring NAs)
options(na.action='na.pass') # First change default options for handling missing data
X_ordinal_scaled <- scale(X_ordinal, center=TRUE, scale=2*ordinal_sd)
options(na.action='na.omit') # Return option back to the default
# Create dataframe for brms and rename feed variables
fcr_brms_data <- data.frame(y = fcr_no_na$fcr, X_taxa_scaled, X_ordinal_scaled)
# Set model formula
fcr_brms <- brmsformula(y ~ 1 + ., family = Gamma("log"))
# Use "resp = <response_variable>" to specify different priors for different response variables
all_priors <- c(set_prior("normal(0,5)", class = "b"), # priors for y response variables
set_prior("normal(0,2.5)", class = "Intercept"),
set_prior("exponential(1)", class = "shape"))
# Model converges after increasing the adapt_delta and iterations from default values
# Rule of thumb: bulk and tail effective sample sizes should be 100 x number of chains (i.e., at least 400)
# increasing max_treedepth is more about efficiency (instead of validity)
# See: https://mc-stan.org/misc/warnings.html
fit_fcr_no_na <- brm(fcr_brms, data = fcr_brms_data,
prior = all_priors, cores = 4, seed = "11729", iter = 5000, control = list(adapt_delta = 0.99))
# Get stan code
#stancode(fit_fcr_no_na)
######################################################################################################
# Use fcr model to predict NA fcrs for studies with complete set of predictors
# Both intensity AND system are non-NA
fcr_complete_predictors <- feed_model_dat_categories %>%
filter(fcr != 0 | is.na(fcr)) %>% # Have to explicitly include is.na(fcr) otherwise NA's get dropped by fcr != 0
filter(is.na(intensity)==FALSE & is.na(system)==FALSE) %>%
filter(is.na(fcr))
# PROBLEM: lca_complete predictors has more taxa than originally model:
taxa_not_modeled <- setdiff(unique(fcr_complete_predictors$taxa), unique(fcr_no_na$taxa)) # these taxa were never modeled so they can't be predicted below
# DROP THESE FOR NOW:
fcr_complete_predictors <- fcr_complete_predictors %>%
filter(taxa %in% taxa_not_modeled == FALSE)
# Now check the other way, which taxa were in the original model but not a part of the data that needs to be predicted:
setdiff(unique(fcr_no_na$taxa), unique(fcr_complete_predictors$taxa))
# If original model has taxa that are not part of fcr_complete_predictors, need to convert to factor and expand/assign levels manually - having trouble automating this
# See list of unique taxa in fcr_no_na - remember the first level is part of the "contrasts" in design matrix
sort(unique(fcr_no_na$taxa))
fcr_complete_predictors <- fcr_complete_predictors %>%
mutate(taxa = as.factor(taxa))
levels(fcr_complete_predictors$taxa) <- list(catfish = "catfish",
hypoph_carp = "hypoph_carp",
milkfish = "milkfish",
misc_diad = "misc_diad",
misc_marine = "misc_marine",
oth_carp = "oth_carp",
salmon = "salmon",
shrimp = "shrimp",
tilapia = "tilapia",
trout = "trout")
# Create NEW taxa model matrix for the studies whose feeds need to be predicted
# Taxa categories:
options(na.action='na.pass') # First change default options for handling missing data
X_taxa_new <- model.matrix(object = ~ 1 + taxa,
data = fcr_complete_predictors %>% select(taxa))
options(na.action='na.omit') # Return option back to the default
# Center and Scale: BUT now center by the mean of the original modeled dataset above AND scale by the same 2*SD calculated from the original, modeled dataset above
options(na.action='na.pass') # First change default options for handling missing data
X_taxa_new_scaled <- scale(X_taxa_new[,-1], center=apply(X_taxa[,-1], MARGIN = 2, FUN = mean), scale=2*taxa_sd)
options(na.action='na.omit') # Return option back to the default
# System and Intensity variables:
# Format intensity and system as ordinal variables, then center and scale
X_ordinal_new <- fcr_complete_predictors %>%
mutate(intensity = factor(intensity, levels = c("Extensive", "Imp. extensive", "Semi-intensive", "Intensive"))) %>% # set order of factors (low = extensive, high = intensive)
mutate(system = factor(system, levels = c("On- and off-bottom", "Cages & pens", "Ponds", "Recirculating and tanks"))) %>% # set order of factors (low = open, high = closed)
mutate(intensity = as.numeric(intensity)) %>%
mutate(system = as.numeric(system)) %>%
select(intensity, system) %>%
as.matrix()
# Center and Scale: BUT now center by the mean of the original modeled dataset above AND scale by the same 2*SD calculated from the original, modeled dataset above
options(na.action='na.pass') # First change default options for handling missing data
X_ordinal_new_scaled <- scale(X_ordinal_new, center=apply(X_ordinal, MARGIN = 2, FUN = mean), scale=2*ordinal_sd)
options(na.action='na.omit') # Return option back to the default
# Create dataframe for brms and rename feed variables
brms_new_fcr_data <- data.frame(cbind(X_taxa_new_scaled, X_ordinal_new_scaled))
# Make predictions
#predicted_fcr_dat <- predict(fit_no_na, newdata = brms_new_fcr_data)
# Use tidybayes instead:
predicted_fcr_dat <- add_predicted_draws(newdata = brms_new_fcr_data, model = fit_fcr_no_na)
# Get point and interval estimates from predicted data
# Select just the prediction columns
# Join these with the modeled data (fcr_complete_predictors) to get metadata on taxa/intensity/syste,
fcr_dat_intervals <- predicted_fcr_dat %>%
median_qi(.value = .prediction) %>% # Rename prediction to value
ungroup() %>%
select(contains("."))
# .row is equivalent to the row number in the modeled dataset (fcr_complete_predictors) - create a join column for this
fcr_metadat<- fcr_complete_predictors %>%
select(study_id, clean_sci_name, taxa, intensity, system) %>%
mutate(.row = row_number())
fcr_predictions <- fcr_dat_intervals %>%
left_join(fcr_metadat, by = ".row") %>%
rename(fcr = .value)
######################################################################################################
# No need to create model of just inetnsity + system because all taxa were predicted
######################################################################################################
# Bind fcr_no_na (data), fcr_predictions, and fcr_predictions_no_taxa
full_fcr_dat <- fcr_predictions %>%
bind_rows(fcr_no_na) %>%
#bind_rows(fcr_predictions_no_taxa) %>%
mutate(data_type = if_else(is.na(.point), true = "data", false = "prediction")) %>%
arrange(taxa, intensity, system, clean_sci_name) %>%
rownames_to_column() # Arrange by taxa first, then create dummy column for plotting
# Quick check: PLOT DATA + PREDICTIONS
ggplot(full_fcr_dat, aes(x = fcr, y = taxa)) + geom_boxplot(outlier.shape = NA) + geom_jitter(aes(color = data_type))
# Generate summaries for supplementary information:
source("Functions.R")
plot_for_si(name_of_fit = "fit_fcr_no_na", name_of_data = "full_fcr_dat", name_of_var = "fcr")
rm(list=ls()[!(ls() %in% c("lca_dat_clean_groups", "feed_model_dat_categories",
"full_fcr_dat"))])
######################################################################################################
# Step 2: Model feed proportions
# Brms dirichlet regression doesn't support missing data, so strategy here is to remove all NAs and model these data
# Then use the model to predict missing feed proportion data for those data that have a complete set of predictors
# Remove fcr == 0 (species that aren't fed)
feed_no_na <- feed_model_dat_categories %>%
filter(fcr != 0 | is.na(fcr)) %>% # Have to explicitly include is.na(fcr) otherwise NA's get dropped by fcr != 0
filter(is.na(intensity)==FALSE & is.na(system)==FALSE) %>% # complete predictors - i.e., both intensity AND system are non-NA
filter(is.na(feed_soy_new)==FALSE) %>%
rename(feed_soy = feed_soy_new,
feed_crops = feed_crops_new,
feed_fmfo = feed_fmfo_new,
feed_animal = feed_animal_new) %>%
select(study_id, clean_sci_name, taxa, intensity, system, contains("feed"))
# Set data for model:
# Create model matrix for taxa info, then center and scale
options(na.action='na.pass') # First change default options for handling missing data
X_taxa <- model.matrix(object = ~ 1 + taxa,
data = feed_no_na %>% select(taxa))
options(na.action='na.omit') # Return option back to the default
taxa_sd <- apply(X_taxa[,-1], MARGIN=2, FUN=sd, na.rm=TRUE) # Center all non-intercept variables and scale by 2 standard deviations (ignoring NAs)
options(na.action='na.pass') # First change default options for handling missing data
X_taxa_scaled <- scale(X_taxa[,-1], center=TRUE, scale=2*taxa_sd)
options(na.action='na.omit') # Return option back to the default
# Format intensity and system as ordinal variables, then center and scale
X_ordinal <- feed_no_na %>%
mutate(intensity = factor(intensity, levels = c("Extensive", "Imp. extensive", "Semi-intensive", "Intensive"))) %>% # set order of factors (low = extensive, high = intensive)
mutate(system = factor(system, levels = c("On- and off-bottom", "Cages & pens", "Ponds", "Recirculating and tanks"))) %>% # set order of factors (low = open, high = closed)
mutate(intensity = as.numeric(intensity)) %>%
mutate(system = as.numeric(system)) %>%
select(intensity, system) %>%
as.matrix()
ordinal_sd<-apply(X_ordinal, MARGIN=2, FUN=sd, na.rm=TRUE) # Center all non-intercept variables and scale by 2 standard deviations (ignoring NAs)
options(na.action='na.pass') # First change default options for handling missing data
X_ordinal_scaled <- scale(X_ordinal, center=TRUE, scale=2*ordinal_sd)
options(na.action='na.omit') # Return option back to the default
# Create dataframe for brms and rename feed variables
feed_brms_data <- data.frame(cbind(feed_no_na %>% select(contains("feed")), X_taxa_scaled, X_ordinal_scaled))
# Response variable must be a matrix, create function bind since cbind within the brm function is reserved for specifying multivariate models
bind <- function(...) cbind(...)
feed_brms <- brmsformula(bind(feed_soy, feed_crops, feed_fmfo, feed_animal) ~ 1 + ., family = dirichlet())
# Model converges after increasing the adapt_delta and iterations from default values
fit_feed_no_na <- brm(feed_brms, data = feed_brms_data,
cores = 4, seed = "11729", iter = 5000)
summary(fit_feed_no_na)
######################################################################################################
# Use feed proportion model to predict NA feeds for studies with complete set of predictors
# Both intensity AND system are non-NA
feed_complete_predictors <- feed_model_dat_categories %>%
filter(fcr != 0 | is.na(fcr)) %>% # Have to explicitly include is.na(fcr) otherwise NA's get dropped by fcr != 0
filter(is.na(intensity)==FALSE & is.na(system)== FALSE) %>%
filter(is.na(feed_soy_new))
# PROBLEM: lca_complete predictors has more taxa than originally model:
taxa_not_modeled <- setdiff(unique(feed_complete_predictors$taxa), unique(feed_no_na$taxa)) # these taxa were never modeled so they can't be predicted below
# DROP THESE FOR NOW:
feed_complete_predictors <- feed_complete_predictors %>%
filter(taxa %in% taxa_not_modeled == FALSE)
# Now check the other way, which taxa were in the original model but not a part of the data that needs to be predicted:
setdiff(unique(feed_no_na$taxa), unique(feed_complete_predictors$taxa))
# If original model has taxa that are not part of feed_complete_predictors, need to convert to factor and expand/assign levels manually - having trouble automating this
# See list of unique taxa in feed_no_na - remember the first level is part of the "contrasts" in design matrix
sort(unique(feed_no_na$taxa))
feed_complete_predictors <- feed_complete_predictors %>%
mutate(taxa = as.factor(taxa))
levels(feed_complete_predictors$taxa) <- list(catfish = "catfish",
hypoph_carp = "hypoph_carp",
milkfish = "milkfish",
misc_diad = "misc_diad",
misc_marine = "misc_marine",
oth_carp = "oth_carp",
salmon = "salmon",
shrimp = "shrimp",
tilapia = "tilapia",
trout = "trout")
# Create NEW taxa model matrix for the studies whose feeds need to be predicted
# Taxa categories:
options(na.action='na.pass') # First change default options for handling missing data
X_taxa_new <- model.matrix(object = ~ 1 + taxa,
data = feed_complete_predictors %>% select(taxa))
options(na.action='na.omit') # Return option back to the default
# Center and Scale: BUT now center by the mean of the original modeled dataset above AND scale by the same 2*SD calculated from the original, modeled dataset above
options(na.action='na.pass') # First change default options for handling missing data
X_taxa_new_scaled <- scale(X_taxa_new[,-1], center=apply(X_taxa[,-1], MARGIN = 2, FUN = mean), scale=2*taxa_sd)
options(na.action='na.omit') # Return option back to the default
# System and Intensity variables:
# Format intensity and system as ordinal variables, then center and scale
X_ordinal_new <- feed_complete_predictors %>%
mutate(intensity = factor(intensity, levels = c("Extensive", "Imp. extensive", "Semi-intensive", "Intensive"))) %>% # set order of factors (low = extensive, high = intensive)
mutate(system = factor(system, levels = c("On- and off-bottom", "Cages & pens", "Ponds", "Recirculating and tanks"))) %>% # set order of factors (low = open, high = closed)
mutate(intensity = as.numeric(intensity)) %>%
mutate(system = as.numeric(system)) %>%
select(intensity, system) %>%
as.matrix()
# Center and Scale: BUT now center by the mean of the original modeled dataset above AND scale by the same 2*SD calculated from the original, modeled dataset above
options(na.action='na.pass') # First change default options for handling missing data
X_ordinal_new_scaled <- scale(X_ordinal_new, center=apply(X_ordinal, MARGIN = 2, FUN = mean), scale=2*ordinal_sd)
options(na.action='na.omit') # Return option back to the default
# Create dataframe for brms and rename feed variables
brms_new_feed_data <- data.frame(cbind(X_taxa_new_scaled, X_ordinal_new_scaled))
# Make predictions
#predicted_feed_dat <- predict(fit_no_na, newdata = brms_new_feed_data)
# Use tidybayes instead:
predicted_feed_dat <- add_predicted_draws(newdata = brms_new_feed_data, model = fit_feed_no_na)
# Get point and interval estimates from predicted data
# Select just the prediction columns
# Join these with the original lca data (feed_complete_predictors) to get metadata on taxa/intensity/syste,
feed_dat_intervals <- predicted_feed_dat %>%
median_qi(.value = .prediction) %>% # Rename prediction to value
ungroup() %>%
select(contains("."))
# .row is equivalent to the row number in the original dataset (feed_complete_predictors) - create a join column for this
feed_metadat<- feed_complete_predictors %>%
select(study_id, clean_sci_name, taxa, intensity, system) %>%
mutate(.row = row_number())
feed_predictions <- feed_dat_intervals %>%
left_join(feed_metadat, by = ".row") %>%
rename(feed_proportion = .value)
######################################################################################################
# No need to create model of just inetnsity + system because all taxa were predicted
######################################################################################################
# Reformat data so it can row-bind with predictions
feed_no_na_long <- feed_no_na %>%
pivot_longer(cols = c("feed_soy", "feed_crops", "feed_fmfo", "feed_animal"), names_to = ".category", values_to = "feed_proportion")
# Bind feed_no_na (data), feed_predictions, and feed_predictions_no_taxa
full_feed_dat <- feed_predictions %>%
bind_rows(feed_no_na_long) %>%
#bind_rows(feed_predictions_no_taxa) %>%
mutate(data_type = if_else(is.na(.point), true = "data", false = "prediction")) %>%
arrange(taxa, intensity, system, clean_sci_name) %>%
rownames_to_column() # Arrange by taxa first, then create dummy column for plotting
# Check data + predictions
feed_vars <- c("soy", "crops", "fmfo", "animal")
for (i in 1:length(feed_vars)) {
p <- ggplot(data = full_feed_dat %>%
filter(str_detect(.category, feed_vars[i])), aes(y = taxa, x = feed_proportion)) +
geom_boxplot(outlier.shape = NA) +
#geom_violin(aes(color = taxa), scale = "width") +
geom_jitter(aes(color = data_type), size = 3) +
theme_classic() +
labs(title = paste("Boxplots of ", feed_vars[i], " feed proportions", sep = ""),
x = "",
y = "") +
theme(axis.text.x = element_text(hjust = 1))
print(p)
}
# Generate summaries for supplementary information:
source("Functions.R")
plot_for_si(name_of_fit = "fit_feed_no_na", name_of_data = "full_feed_dat", name_of_var = "feed_proportion", regression_type = "dirichlet")
rm(list=ls()[!(ls() %in% c("lca_dat_clean_groups", "feed_model_dat_categories",
"full_fcr_dat",
"full_feed_dat"))])
######################################################################################################
# Section 2: Create ghg_model_dat_categories for modeling all energy inputs
# DECISION: adjusting zeroes to be very small amount for all energy datasets
# Need to do this for gamma regression
# Get model-specific data:
# SELECT STUDY ID COLUMN - use this for rejoining outputs from multiple regression models back together
# Select relevant data columns and arrange by categorical info
# Select iso3c so this can be joined with country-specific GHG emissions for electricity
ghg_model_dat_categories <- lca_dat_clean_groups %>%
select(study_id, Country, iso3c, electric = Electricity_kwh, diesel = Diesel_L, petrol = Petrol_L, natgas = NaturalGas_L, clean_sci_name, taxa, intensity = Intensity, system = Production_system_group) %>%
arrange(clean_sci_name, taxa, intensity, system) %>%
mutate(electric = if_else(electric == 0, true = 0.01, false = electric),
diesel = if_else(diesel == 0, true = 0.01, false = diesel),
petrol = if_else(petrol == 0, true = 0.01, false = petrol),
natgas = if_else(natgas == 0, true = 0.01, false = natgas))
######################################################################################################
# Step 1: Model electricity as taxa + intensity + system
electric_no_na <- ghg_model_dat_categories %>%
filter(is.na(electric)==FALSE) %>% # Drop NAs (Keep zeroes)
#mutate(electric = if_else(electric == 0, true = min(electric[electric!=0]), false = electric)) %>% # Not modeling the zeroes, option 1: adjust these to the minimum value
filter(electric != 0) %>% # Not modeling the zeroes, option 2: drop all zeroes
filter(is.na(intensity)==FALSE & is.na(system)==FALSE) %>% # complete predictors - i.e., both intensity AND system are non-NA
select(study_id, Country, iso3c, electric, clean_sci_name, taxa, intensity, system)
# Create model matrix for taxa info, then center and scale
X_taxa <- model.matrix(object = ~ 1 + taxa,
data = electric_no_na %>% select(taxa))
taxa_sd <- apply(X_taxa[,-1], MARGIN=2, FUN=sd, na.rm=TRUE) # Center all non-intercept variables and scale by 2 standard deviations (ignoring NAs)
#taxa_sd <- sd(X_taxa[,-1], na.rm = TRUE)
X_taxa_scaled <- scale(X_taxa[,-1], center=TRUE, scale=2*taxa_sd)
# Format intensity and system as ordinal variables, then center and scale
X_ordinal <- electric_no_na %>%
mutate(intensity = factor(intensity, levels = c("Extensive", "Imp. extensive", "Semi-intensive", "Intensive"))) %>% # set order of factors (low = extensive, high = intensive)
mutate(system = factor(system, levels = c("On- and off-bottom", "Cages & pens", "Ponds", "Recirculating and tanks"))) %>% # set order of factors (low = open, high = closed)
mutate(intensity = as.numeric(intensity)) %>%
mutate(system = as.numeric(system)) %>%
select(intensity, system) %>%
as.matrix()
ordinal_sd<-apply(X_ordinal, MARGIN=2, FUN=sd, na.rm=TRUE) # Center all non-intercept variables and scale by 2 standard deviations (ignoring NAs)
X_ordinal_scaled <- scale(X_ordinal, center=TRUE, scale=2*ordinal_sd)
# Create dataframe for brms and rename feed variables
electric_brms_data <- data.frame(y = electric_no_na$electric, X_taxa_scaled, X_ordinal_scaled)
names(electric_brms_data)
# Set model formula
electric_brms <- brmsformula(y ~ 1 + ., family = Gamma("log"))
# Equivalent to:
# electric_brms <- brmsformula(y ~ 1 + taxatilapia + taxatrout +
# intensity + system, family = Gamma("log"))
# Use "resp = <response_variable>" to specify different priors for different response variables
all_priors <- c(set_prior("normal(0,5)", class = "b"), # priors for y response variables
set_prior("normal(0,2.5)", class = "Intercept"),
set_prior("exponential(1)", class = "shape"))
# Model converges after increasing the adapt_delta and iterations from default values
# Rule of thumb: bulk and tail effective sample sizes should be 100 x number of chains (i.e., at least 400)
# increasing max_treedepth is more about efficiency (instead of validity)
# See: https://mc-stan.org/misc/warnings.html
fit_electric_no_na <- brm(electric_brms, data = electric_brms_data,
prior = all_priors, cores = 4, seed = "11729", iter = 5000, control = list(adapt_delta = 0.99))
# Get stan code
#stancode(fit_electric_no_na)
######################################################################################################
# Use model to predict NAs for studies with complete set of predictors
# Both intensity AND system are non-NA
electric_complete_predictors <- ghg_model_dat_categories %>%
filter(is.na(electric)) %>%
filter(is.na(intensity)==FALSE & is.na(system)==FALSE)
# PROBLEM: lca_complete predictors has more taxa than originally model:
taxa_not_modeled <- setdiff(unique(electric_complete_predictors$taxa), unique(electric_no_na$taxa)) # these taxa were never modeled so they can't be predicted below
# DROP THESE FOR NOW:
electric_complete_predictors <- electric_complete_predictors %>%
filter(taxa %in% taxa_not_modeled == FALSE)
# Now check the other way, which taxa were in the original model but not a part of the data that needs to be predicted:
setdiff(unique(electric_no_na$taxa), unique(electric_complete_predictors$taxa))
# If original model has taxa that are not part of electric_complete_predictors,
# Use list of unique taxa in original model and use this to expand/assign levels manually - having trouble automating this
# Include all levels here, but remember the first level won't show up in design matrix - instead, it's part of the "contrasts"
sort(unique(electric_no_na$taxa))
electric_complete_predictors <- electric_complete_predictors %>%
mutate(taxa = as.factor(taxa))
levels(electric_complete_predictors$taxa) <- list(bivalves = "bivalves",
catfish = "catfish",
hypoph_carp = "hypoph_carp",
milkfish = "milkfish",
misc_diad = "misc_diad",
misc_marine = "misc_marine",
oth_carp = "oth_carp",
plants = "plants",
salmon = "salmon",
shrimp = "shrimp",
tilapia = "tilapia",
trout = "trout")
# Create NEW taxa model matrix for the studies to be predicted
# Taxa categories:
X_taxa_new <- model.matrix(object = ~ 1 + taxa,
data = electric_complete_predictors %>% select(taxa))
# Center and Scale: BUT now center by the mean of the original modeled dataset above AND scale by the same 2*SD calculated from the original, modeled dataset above
X_taxa_new_scaled <- scale(X_taxa_new[,-1], center=apply(X_taxa[,-1], MARGIN = 2, FUN = mean), scale=2*taxa_sd)
# System and Intensity variables:
# Format intensity and system as ordinal variables, then center and scale
X_ordinal_new <- electric_complete_predictors %>%
mutate(intensity = factor(intensity, levels = c("Extensive", "Imp. extensive", "Semi-intensive", "Intensive"))) %>% # set order of factors (low = extensive, high = intensive)
mutate(system = factor(system, levels = c("On- and off-bottom", "Cages & pens", "Ponds", "Recirculating and tanks"))) %>% # set order of factors (low = open, high = closed)
mutate(intensity = as.numeric(intensity)) %>%
mutate(system = as.numeric(system)) %>%
select(intensity, system) %>%
#select(system) %>%
as.matrix()
# Center and Scale: BUT now center by the mean of the original modeled dataset above AND scale by the same 2*SD calculated from the original, modeled dataset above
X_ordinal_new_scaled <- scale(X_ordinal_new, center=apply(X_ordinal, MARGIN = 2, FUN = mean), scale=2*ordinal_sd)
# Create dataframe for brms and rename feed variables
brms_new_electric_dat <- data.frame(cbind(X_taxa_new_scaled, X_ordinal_new_scaled))
# Make predictions
#predicted_electric_dat <- predict(fit_no_na, newdata = brms_new_electric_data)
# Use tidybayes instead:
predicted_electric_dat <- add_predicted_draws(newdata = brms_new_electric_dat, model = fit_electric_no_na)
# Get point and interval estimates from predicted data
# Select just the prediction columns
# Join these with the modeled data (electric_complete_predictors) to get metadata on taxa/intensity/syste,
electric_dat_intervals <- predicted_electric_dat %>%
median_qi(.value = .prediction) %>% # Rename prediction to value
ungroup() %>%
select(contains("."))
# .row is equivalent to the row number in the modeled dataset (electric_complete_predictors) - create a join column for this
electric_metadat<- electric_complete_predictors %>%
select(study_id, Country, iso3c, clean_sci_name, taxa, intensity, system) %>%
mutate(.row = row_number())
electric_predictions <- electric_dat_intervals %>%
left_join(electric_metadat, by = ".row") %>%
rename(electric = .value)
######################################################################################################
# No need to create model of just inetnsity + system because all taxa were predicted
######################################################################################################
# Bind electric_no_na (data), electric_predictions, and electric_predictions_no_taxa
full_electric_dat <- electric_predictions %>%
bind_rows(electric_no_na) %>%
#bind_rows(electric_predictions_no_taxa) %>%
mutate(data_type = if_else(is.na(.point), true = "data", false = "prediction")) %>%
arrange(taxa, intensity, system, clean_sci_name) %>%
rownames_to_column() # Arrange by taxa first, then create dummy column for plotting
# Quick check: PLOT DATA + PREDICTIONS
ggplot(full_electric_dat, aes(x = electric, y = taxa)) + geom_boxplot(outlier.shape = NA) + geom_jitter(aes(color = data_type))
# Outlier in misc_diad looks like it's being pulled to a much lower electricity value because system == "Cages & pens"
# See plot for just the Cages and pens studies:
ggplot(full_electric_dat %>% filter(system == "Cages & pens"), aes(x = electric, y = taxa)) + geom_boxplot(outlier.shape = NA) + geom_jitter(aes(color = data_type))
## FIX IT - temporary fix - filter out predictions with high uncertainty based on highest and lowest data values
## shouldn't be predicting out of the range of observations
min_dat <- full_electric_dat %>%
filter(data_type == "data") %>%
pull(electric) %>%
min()
max_dat <- full_electric_dat %>%
filter(data_type == "data") %>%
pull(electric) %>%
max()
full_electric_dat <- full_electric_dat %>%
filter(electric <= max_dat & electric >= min_dat)
# Generate summaries for supplementary information:
source("Functions.R")
plot_for_si(name_of_fit = "fit_electric_no_na", name_of_data = "full_electric_dat", name_of_var = "electric")
rm(list=ls()[!(ls() %in% c("lca_dat_clean_groups",
"feed_model_dat_categories",
"full_fcr_dat",
"full_feed_dat",
"ghg_model_dat_categories",
"full_electric_dat"))])
######################################################################################################
# Step 2: Model diesel
diesel_no_na <- ghg_model_dat_categories %>%
filter(is.na(diesel)==FALSE) %>% # Drop NAs (Keep zeroes)
#mutate(diesel = if_else(diesel == 0, true = 0.01, false = diesel)) %>% # Not modeling the zeroes, option 1: adjust these to the minimum value
filter(diesel != 0) %>% # Not modeling the zeroes, option 2: drop all zeroes
filter(is.na(intensity)==FALSE & is.na(system)==FALSE) %>% # complete predictors - i.e., both intensity AND system are non-NA
select(study_id, Country, iso3c, diesel, clean_sci_name, taxa, intensity, system)
# Create model matrix for taxa info, then center and scale
X_taxa <- model.matrix(object = ~ 1 + taxa,
data = diesel_no_na %>% select(taxa))
taxa_sd <- apply(X_taxa[,-1], MARGIN=2, FUN=sd, na.rm=TRUE) # Center all non-intercept variables and scale by 2 standard deviations (ignoring NAs)
X_taxa_scaled <- scale(X_taxa[,-1], center=TRUE, scale=2*taxa_sd)
# Format intensity and system as ordinal variables, then center and scale
X_ordinal <- diesel_no_na %>%
mutate(intensity = factor(intensity, levels = c("Extensive", "Imp. extensive", "Semi-intensive", "Intensive"))) %>% # set order of factors (low = extensive, high = intensive)
mutate(system = factor(system, levels = c("On- and off-bottom", "Cages & pens", "Ponds", "Recirculating and tanks"))) %>% # set order of factors (low = open, high = closed)
mutate(intensity = as.numeric(intensity)) %>%
mutate(system = as.numeric(system)) %>%
select(intensity, system) %>%
#select(system) %>%
as.matrix()
ordinal_sd<-apply(X_ordinal, MARGIN=2, FUN=sd, na.rm=TRUE) # Center all non-intercept variables and scale by 2 standard deviations (ignoring NAs)
X_ordinal_scaled <- scale(X_ordinal, center=TRUE, scale=2*ordinal_sd)
# Create dataframe for brms and rename feed variables
diesel_brms_data <- data.frame(y = diesel_no_na$diesel, X_taxa_scaled, X_ordinal_scaled)
names(diesel_brms_data)
# Set model formula
diesel_brms <- brmsformula(y ~ 1 + ., family = Gamma("log"))
# Use "resp = <response_variable>" to specify different priors for different response variables
all_priors <- c(set_prior("normal(0,5)", class = "b"), # priors for y response variables
set_prior("normal(0,2.5)", class = "Intercept"),
set_prior("exponential(1)", class = "shape"))
# Model converges after increasing the adapt_delta and iterations from default values
# Rule of thumb: bulk and tail effective sample sizes should be 100 x number of chains (i.e., at least 400)
# increasing max_treedepth is more about efficiency (instead of validity)
# See: https://mc-stan.org/misc/warnings.html
fit_diesel_no_na <- brm(diesel_brms, data = diesel_brms_data,
prior = all_priors, cores = 4, seed = "11729", iter = 5000, control = list(adapt_delta = 0.99))
# Get stan code
#stancode(fit_diesel_no_na)
######################################################################################################
# Use model to predict NAs for studies with complete set of predictors
# Both intensity AND system are non-NA
diesel_complete_predictors <- ghg_model_dat_categories %>%
filter(is.na(diesel)) %>%
filter(is.na(intensity)==FALSE & is.na(system)== FALSE)
# PROBLEM: lca_complete predictors has more taxa than originally model:
taxa_not_modeled <- setdiff(unique(diesel_complete_predictors$taxa), unique(diesel_no_na$taxa)) # these taxa were never modeled so they can't be predicted below
# DROP THESE FOR NOW:
diesel_complete_predictors <- diesel_complete_predictors %>%
filter(taxa %in% taxa_not_modeled == FALSE)
# Now check the other way, which taxa were in the original model but not a part of the data that needs to be predicted:
setdiff(unique(diesel_no_na$taxa), unique(diesel_complete_predictors$taxa))
# If original model has taxa that are not part of diesel_complete_predictors,
# Use list of unique taxa in original model and use this to expand/assign levels manually - having trouble automating this
# Include all levels here, but remember the first level won't show up in design matrix - instead, it's part of the "contrasts"
sort(unique(diesel_no_na$taxa))
diesel_complete_predictors <- diesel_complete_predictors %>%
mutate(taxa = as.factor(taxa))
levels(diesel_complete_predictors$taxa) <- list(bivalves = "bivalves",
catfish = "catfish",
hypoph_carp = "hypoph_carp",
milkfish = "milkfish",
misc_diad = "misc_diad",
misc_marine = "misc_marine",
oth_carp = "oth_carp",
plants = "plants",
salmon = "salmon",
shrimp = "shrimp",
tilapia = "tilapia",
trout = "trout")
# Create NEW taxa model matrix for the studies to be predicted
# Taxa categories:
X_taxa_new <- model.matrix(object = ~ 1 + taxa,
data = diesel_complete_predictors %>% select(taxa))
# Center and Scale: BUT now center by the mean of the original modeled dataset above AND scale by the same 2*SD calculated from the original, modeled dataset above
X_taxa_new_scaled <- scale(X_taxa_new[,-1], center=apply(X_taxa[,-1], MARGIN = 2, FUN = mean), scale=2*taxa_sd)
# System and Intensity variables:
# Format intensity and system as ordinal variables, then center and scale
X_ordinal_new <- diesel_complete_predictors %>%
mutate(intensity = factor(intensity, levels = c("Extensive", "Imp. extensive", "Semi-intensive", "Intensive"))) %>% # set order of factors (low = extensive, high = intensive)
mutate(system = factor(system, levels = c("On- and off-bottom", "Cages & pens", "Ponds", "Recirculating and tanks"))) %>% # set order of factors (low = open, high = closed)
mutate(intensity = as.numeric(intensity)) %>%
mutate(system = as.numeric(system)) %>%
select(intensity, system) %>%
#select(system) %>%
as.matrix()
# Center and Scale: BUT now center by the mean of the original modeled dataset above AND scale by the same 2*SD calculated from the original, modeled dataset above
X_ordinal_new_scaled <- scale(X_ordinal_new, center=apply(X_ordinal, MARGIN = 2, FUN = mean), scale=2*ordinal_sd)
# Create dataframe for brms and rename feed variables
brms_new_diesel_dat <- data.frame(cbind(X_taxa_new_scaled, X_ordinal_new_scaled))
# Make predictions
#predicted_diesel_dat <- predict(fit_no_na, newdata = brms_new_diesel_data)
# Use tidybayes instead:
predicted_diesel_dat <- add_predicted_draws(newdata = brms_new_diesel_dat, model = fit_diesel_no_na)
#predicted_diesel_dat <- add_fitted_draws(newdata = brms_new_diesel_dat, model = fit_diesel_no_na)
# Get point and interval estimates from predicted data
# Select just the prediction columns
# Join these with the modeled data (diesel_complete_predictors) to get metadata on taxa/intensity/syste,
diesel_dat_intervals <- predicted_diesel_dat %>%
median_qi(.value = .prediction) %>% # Rename prediction to value
ungroup() %>%
select(contains("."))
# .row is equivalent to the row number in the modeled dataset (diesel_complete_predictors) - create a join column for this
diesel_metadat<- diesel_complete_predictors %>%
select(study_id, Country, iso3c, clean_sci_name, taxa, intensity, system) %>%
mutate(.row = row_number())
diesel_predictions <- diesel_dat_intervals %>%
left_join(diesel_metadat, by = ".row") %>%
rename(diesel = .value)
######################################################################################################
# No need to create model of just inetnsity + system because all taxa were predicted
######################################################################################################
# Bind diesel_no_na (data), diesel_predictions, and diesel_predictions_no_taxa
full_diesel_dat <- diesel_predictions %>%
bind_rows(diesel_no_na) %>%
#bind_rows(diesel_predictions_no_taxa) %>%
mutate(data_type = if_else(is.na(.point), true = "data", false = "prediction")) %>%
arrange(taxa, intensity, system, clean_sci_name) %>%
rownames_to_column() # Arrange by taxa first, then create dummy column for plotting
# Quick check: PLOT DATA + PREDICTIONS
ggplot(full_diesel_dat, aes(x = diesel, y = taxa)) + geom_boxplot(outlier.shape = NA) + geom_jitter(aes(color = data_type))
## FIX IT - temporary fix - filter out predictions with high uncertainty based on highest and lowest data values
## shouldn't be predicting out of the range of observations
min_dat <- full_diesel_dat %>%
filter(data_type == "data") %>%
pull(diesel) %>%
min()
max_dat <- full_diesel_dat %>%
filter(data_type == "data") %>%
pull(diesel) %>%
max()
full_diesel_dat <- full_diesel_dat %>%
filter(diesel <= max_dat & diesel >= min_dat)
# Check again: PLOT DATA + PREDICTIONS
ggplot(full_diesel_dat, aes(x = diesel, y = taxa)) + geom_boxplot(outlier.shape = NA) + geom_jitter(aes(color = data_type))
# Generate summaries for supplementary information
source("Functions.R")
plot_for_si(name_of_fit = "fit_diesel_no_na", name_of_data = "full_diesel_dat", name_of_var = "diesel")
rm(list=ls()[!(ls() %in% c("lca_dat_clean_groups",
"feed_model_dat_categories",
"full_fcr_dat",
"full_feed_dat",
"ghg_model_dat_categories",
"full_electric_dat",
"full_diesel_dat"))])
######################################################################################################
# Step 3: Model petrol
petrol_no_na <- ghg_model_dat_categories %>%
filter(is.na(petrol)==FALSE) %>% # Drop NAs (Keep zeroes)
#mutate(petrol = if_else(petrol == 0, true = min(petrol[petrol!=0]), false = petrol)) %>% # Not modeling the zeroes, option 1: adjust these to the minimum value
filter(petrol != 0) %>% # Not modeling the zeroes, option 2: drop zeroes
filter(is.na(intensity)==FALSE & is.na(system)==FALSE) %>% # complete predictors - i.e., both intensity AND system are non-NA
select(study_id, Country, iso3c, petrol, clean_sci_name, taxa, intensity, system)
# Create model matrix for taxa info, then center and scale
X_taxa <- model.matrix(object = ~ 1 + taxa,
data = petrol_no_na %>% select(taxa))
taxa_sd <- apply(X_taxa[,-1], MARGIN=2, FUN=sd, na.rm=TRUE) # Center all non-intercept variables and scale by 2 standard deviations (ignoring NAs)
X_taxa_scaled <- scale(X_taxa[,-1], center=TRUE, scale=2*taxa_sd)
# Format intensity and system as ordinal variables, then center and scale
X_ordinal <- petrol_no_na %>%
mutate(intensity = factor(intensity, levels = c("Extensive", "Imp. extensive", "Semi-intensive", "Intensive"))) %>% # set order of factors (low = extensive, high = intensive)
mutate(system = factor(system, levels = c("On- and off-bottom", "Cages & pens", "Ponds", "Recirculating and tanks"))) %>% # set order of factors (low = open, high = closed)
mutate(intensity = as.numeric(intensity)) %>%
mutate(system = as.numeric(system)) %>%
select(intensity, system) %>%
#select(system) %>%
as.matrix()
ordinal_sd<-apply(X_ordinal, MARGIN=2, FUN=sd, na.rm=TRUE) # Center all non-intercept variables and scale by 2 standard deviations (ignoring NAs)
X_ordinal_scaled <- scale(X_ordinal, center=TRUE, scale=2*ordinal_sd)
# Create dataframe for brms and rename feed variables
petrol_brms_data <- data.frame(y = petrol_no_na$petrol, X_taxa_scaled, X_ordinal_scaled)
names(petrol_brms_data)
# Set model formula
petrol_brms <- brmsformula(y ~ 1 + ., family = Gamma("log"))
# Use "resp = <response_variable>" to specify different priors for different response variables
all_priors <- c(set_prior("normal(0,5)", class = "b"), # priors for y response variables
set_prior("normal(0,2.5)", class = "Intercept"),
set_prior("exponential(1)", class = "shape"))
# Model converges after increasing the adapt_delta and iterations from default values
# Rule of thumb: bulk and tail effective sample sizes should be 100 x number of chains (i.e., at least 400)
# increasing max_treedepth is more about efficiency (instead of validity)
# See: https://mc-stan.org/misc/warnings.html
fit_petrol_no_na <- brm(petrol_brms, data = petrol_brms_data,
prior = all_priors, cores = 4, seed = "11729", iter = 5000, control = list(adapt_delta = 0.99))
# Get stan code
#stancode(fit_petrol_no_na)
######################################################################################################
# Use model to predict NAs for studies with complete set of predictors
# Both intensity AND system are non-NA
petrol_complete_predictors <- ghg_model_dat_categories %>%
filter(is.na(petrol)) %>%
filter(is.na(intensity)==FALSE & is.na(system)== FALSE)
# PROBLEM: lca_complete predictors has more taxa than originally model:
taxa_not_modeled <- setdiff(unique(petrol_complete_predictors$taxa), unique(petrol_no_na$taxa)) # these taxa were never modeled so they can't be predicted below
# DROP THESE FOR NOW:
petrol_complete_predictors <- petrol_complete_predictors %>%
filter(taxa %in% taxa_not_modeled == FALSE)
# Now check the other way, which taxa were in the original model but not a part of the data that needs to be predicted:
setdiff(unique(petrol_no_na$taxa), unique(petrol_complete_predictors$taxa))
# If original model has taxa that are not part of petrol_complete_predictors,
# Use list of unique taxa in original model and use this to expand/assign levels manually - having trouble automating this
# Include all levels here, but remember the first level won't show up in design matrix - instead, it's part of the "contrasts"
sort(unique(petrol_no_na$taxa))
petrol_complete_predictors <- petrol_complete_predictors %>%
mutate(taxa = as.factor(taxa))
levels(petrol_complete_predictors$taxa) <- list(bivalves = "bivalves",
catfish = "catfish",
hypoph_carp = "hypoph_carp",
milkfish = "milkfish",
misc_diad = "misc_diad",
misc_marine = "misc_marine",
oth_carp = "oth_carp",
plants = "plants",
salmon = "salmon",
shrimp = "shrimp",
tilapia = "tilapia",
trout = "trout")
# Create NEW taxa model matrix for the studies to be predicted
# Taxa categories:
X_taxa_new <- model.matrix(object = ~ 1 + taxa,
data = petrol_complete_predictors %>% select(taxa))
# Center and Scale: BUT now center by the mean of the original modeled dataset above AND scale by the same 2*SD calculated from the original, modeled dataset above
X_taxa_new_scaled <- scale(X_taxa_new[,-1], center=apply(X_taxa[,-1], MARGIN = 2, FUN = mean), scale=2*taxa_sd)
# Format intensity and system as ordinal variable, then center and scale
# System and Intensity variables:
# Format intensity and system as ordinal variables, then center and scale
X_ordinal_new <- petrol_complete_predictors %>%
mutate(intensity = factor(intensity, levels = c("Extensive", "Imp. extensive", "Semi-intensive", "Intensive"))) %>% # set order of factors (low = extensive, high = intensive)
mutate(system = factor(system, levels = c("On- and off-bottom", "Cages & pens", "Ponds", "Recirculating and tanks"))) %>% # set order of factors (low = open, high = closed)
mutate(intensity = as.numeric(intensity)) %>%
mutate(system = as.numeric(system)) %>%
select(intensity, system) %>%
#select(system) %>%
as.matrix()
# Center and Scale: BUT now center by the mean of the original modeled dataset above AND scale by the same 2*SD calculated from the original, modeled dataset above
X_ordinal_new_scaled <- scale(X_ordinal_new, center=apply(X_ordinal, MARGIN = 2, FUN = mean), scale=2*ordinal_sd)
# Create dataframe for brms and rename feed variables
brms_new_petrol_dat <- data.frame(cbind(X_taxa_new_scaled, X_ordinal_new_scaled))
# Make predictions
#predicted_petrol_dat <- predict(fit_no_na, newdata = brms_new_petrol_data)
# Use tidybayes instead:
predicted_petrol_dat <- add_predicted_draws(newdata = brms_new_petrol_dat, model = fit_petrol_no_na)
# Get point and interval estimates from predicted data
# Select just the prediction columns
# Join these with the modeled data (petrol_complete_predictors) to get metadata on taxa/intensity/syste,
petrol_dat_intervals <- predicted_petrol_dat %>%
median_qi(.value = .prediction) %>% # Rename prediction to value
ungroup() %>%
select(contains("."))
# .row is equivalent to the row number in the modeled dataset (petrol_complete_predictors) - create a join column for this
petrol_metadat<- petrol_complete_predictors %>%
select(study_id, Country, iso3c, clean_sci_name, taxa, intensity, system) %>%
mutate(.row = row_number())
petrol_predictions <- petrol_dat_intervals %>%
left_join(petrol_metadat, by = ".row") %>%
rename(petrol = .value)
######################################################################################################
# No need to create model of just inetnsity + system because all taxa were predicted
######################################################################################################
# Bind petrol_no_na (data), petrol_predictions, and petrol_predictions_no_taxa
full_petrol_dat <- petrol_predictions %>%
bind_rows(petrol_no_na) %>%
#bind_rows(petrol_predictions_no_taxa) %>%
mutate(data_type = if_else(is.na(.point), true = "data", false = "prediction")) %>%
arrange(taxa, intensity, system, clean_sci_name) %>%
rownames_to_column() # Arrange by taxa first, then create dummy column for plotting
# Quick Check: PLOT DATA + PREDICTIONS
ggplot(full_petrol_dat, aes(x = petrol, y = taxa)) + geom_boxplot(outlier.shape = NA) + geom_jitter(aes(color = data_type))
# Generate summaries for supplementary information
source("Functions.R")
plot_for_si(name_of_fit = "fit_petrol_no_na", name_of_data = "full_petrol_dat", name_of_var = "petrol")
rm(list=ls()[!(ls() %in% c("lca_dat_clean_groups",
"feed_model_dat_categories",
"full_fcr_dat",
"full_feed_dat",
"ghg_model_dat_categories",
"full_electric_dat",
"full_diesel_dat",
"full_petrol_dat"))])
######################################################################################################
# Step 4: Model natural gas
natgas_no_na <- ghg_model_dat_categories %>%
filter(is.na(natgas)==FALSE) %>% # Drop NAs (Keep zeroes)
#mutate(natgas = if_else(natgas == 0, true = min(natgas[natgas!=0]), false = natgas)) %>% # Not modeling the zeroes, option 1: adjust these to the minimum value
filter(natgas != 0) %>% # Not modeling the zeroes option 2: drop zeroes
filter(is.na(intensity)==FALSE & is.na(system)==FALSE) %>% # complete predictors - i.e., both intensity AND system are non-NA
select(study_id, Country, iso3c, natgas, clean_sci_name, taxa, intensity, system)
# Create model matrix for taxa info, then center and scale
X_taxa <- model.matrix(object = ~ 1 + taxa,
data = natgas_no_na %>% select(taxa))
# If only one column, no need to use the apply() function
taxa_sd <- apply(X_taxa[,-1], MARGIN=2, FUN=sd, na.rm=TRUE) # Center all non-intercept variables and scale by 2 standard deviations (ignoring NAs)
#taxa_sd <- sd(X_taxa[,-1], na.rm = TRUE)
X_taxa_scaled <- scale(X_taxa[,-1], center=TRUE, scale=2*taxa_sd)
# Format intensity and system as ordinal variables, then center and scale
X_ordinal <- natgas_no_na %>%
mutate(intensity = factor(intensity, levels = c("Extensive", "Imp. extensive", "Semi-intensive", "Intensive"))) %>% # set order of factors (low = extensive, high = intensive)
mutate(system = factor(system, levels = c("On- and off-bottom", "Cages & pens", "Ponds", "Recirculating and tanks"))) %>% # set order of factors (low = open, high = closed)
mutate(intensity = as.numeric(intensity)) %>%
mutate(system = as.numeric(system)) %>%
select(intensity, system) %>%
#select(system) %>%
as.matrix()
ordinal_sd<-apply(X_ordinal, MARGIN=2, FUN=sd, na.rm=TRUE) # Center all non-intercept variables and scale by 2 standard deviations (ignoring NAs)
X_ordinal_scaled <- scale(X_ordinal, center=TRUE, scale=2*ordinal_sd)
# Create dataframe for brms and rename feed variables
natgas_brms_data <- data.frame(y = natgas_no_na$natgas, X_taxa_scaled, X_ordinal_scaled)
names(natgas_brms_data)
# Set model formula
natgas_brms <- brmsformula(y ~ 1 + ., family = Gamma("log"))
# Equivalent to:
# natgas_brms <- brmsformula(y ~ 1 + taxatilapia + taxatrout +
# intensity + system, family = Gamma("log"))
# Use "resp = <response_variable>" to specify different priors for different response variables
all_priors <- c(set_prior("normal(0,5)", class = "b"), # priors for y response variables
set_prior("normal(0,2.5)", class = "Intercept"),
set_prior("exponential(1)", class = "shape"))
# Model converges after increasing the adapt_delta and iterations from default values
# Rule of thumb: bulk and tail effective sample sizes should be 100 x number of chains (i.e., at least 400)
# increasing max_treedepth is more about efficiency (instead of validity)
# See: https://mc-stan.org/misc/warnings.html
fit_natgas_no_na <- brm(natgas_brms, data = natgas_brms_data,
prior = all_priors, cores = 4, seed = "11729", iter = 5000, control = list(adapt_delta = 0.99))
# Get stan code
#stancode(fit_natgas_no_na)
######################################################################################################
# Use model to predict NAs for studies with complete set of predictors
# Both intensity AND system are non-NA
natgas_complete_predictors <- ghg_model_dat_categories %>%
filter(is.na(natgas)) %>%
filter(is.na(intensity)==FALSE & is.na(system)== FALSE)
# PROBLEM: lca_complete predictors has more taxa than originally model:
taxa_not_modeled <- setdiff(unique(natgas_complete_predictors$taxa), unique(natgas_no_na$taxa)) # these taxa were never modeled so they can't be predicted below
# DROP THESE FOR NOW:
natgas_complete_predictors <- natgas_complete_predictors %>%
filter(taxa %in% taxa_not_modeled == FALSE)