Skip to content

Commit

Permalink
Merge pull request #1 from qdread/revision2
Browse files Browse the repository at this point in the history
Revision2
  • Loading branch information
qdread authored Feb 4, 2022
2 parents 1713d13 + 0aadaf4 commit 3e521bb
Show file tree
Hide file tree
Showing 19 changed files with 254 additions and 196 deletions.
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Biodiversity: Farm2Fork

Code to reproduce all analysis presented in the manuscript **Biodiversity effects of food system sustainability actions from farm to fork**, and the data for the associated Shiny app ([temporary link](https://shiny.sesync.org/apps/biodiversity-farm2fork)).
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.5949590.svg)](https://doi.org/10.5281/zenodo.5949590)

Code to reproduce all analysis presented in the manuscript **Biodiversity effects of food system sustainability actions from farm to fork**, and the data for the associated [Shiny app](https://qdread.shinyapps.io/biodiversity-farm2fork).

**Citation (to be updated when final)**: Read, Quentin D., Kelly L. Hondula, and Mary K. Muth. Biodiversity effects of food system sustainability actions from farm to fork. *PNAS*, in preparation.

Expand Down Expand Up @@ -46,4 +48,4 @@ In addition, a few functions are called from an R package `Rutilitybelt` that I
this repo, called `Rutilitybelt_0.0.0.9000.tar.gz`. It is installed from source as part of script `00`. It can also be installed from source using the
command `R CMD INSTALL Rutilitybelt_0.0.0.9000.tar.gz`.

*last modified by QDR, 16 August 2021*
*last modified by QDR, 02 February 2022*
15 changes: 7 additions & 8 deletions final_output/25_create_summary_data.R
Original file line number Diff line number Diff line change
Expand Up @@ -67,16 +67,15 @@ write_csv(totaldemand_sums, file.path(final_output_path, 'totaldemand_sums_all_s

# Goods flows by county ---------------------------------------------------

options(mc.cores = 8)
plan(multicore)
plan(multicore(workers = 8))

fp_goods <- file.path(intermediate_output_path, 'county_consumption_csvs')

scenario_combos <- expand_grid(diet = c('baseline','planetaryhealth','medstyle','usstyle','vegetarian'),
waste = c('baseline','preconsumer','consumer','allavoidable'))

sum_goods_flows_county <- function(diet, waste) {
flows <- read_csv(glue::glue('{fp_goods}/D_{diet}_WR_{waste}_wide.csv'))
sum_goods_flows_county <- function(diet, waste, file_path) {
flows <- read_csv(glue::glue('{file_path}/D_{diet}_WR_{waste}_wide.csv'))
message(glue::glue('{diet} by {waste} read'))
# Outbound: each row represents origin county, sum across all destination counties (columns)
flows_outbound <- cbind(flows[, 1:3], flow_outbound = apply(flows[, -(1:3)], 1, sum)) %>%
Expand All @@ -97,7 +96,7 @@ sum_goods_flows_county <- function(diet, waste) {

}

county_goods_flows <- future_pmap_dfr(scenario_combos, sum_goods_flows_county)
county_goods_flows <- future_pmap_dfr(scenario_combos, sum_goods_flows_county, file_path = fp_goods)

write_csv(county_goods_flows, file.path(final_output_path, 'goodsflows_county_sums_all_scenarios.csv'))

Expand All @@ -108,8 +107,8 @@ fp_landcounties <- file.path(intermediate_output_path, 'county_land_consumption_
scenario_combos <- expand_grid(diet = c('baseline','planetaryhealth','medstyle','usstyle','vegetarian'),
waste = c('baseline','preconsumer','consumer','allavoidable'))

sum_land_flows_county <- function(diet, waste) {
flows <- read_csv(glue::glue('{fp_landcounties}/D_{diet}_WR_{waste}_landconsumption.csv'))
sum_land_flows_county <- function(diet, waste, file_path) {
flows <- read_csv(glue::glue('{file_path}/D_{diet}_WR_{waste}_landconsumption.csv'))
message(glue::glue('{diet} by {waste} read'))
# Longform data so outbound and inbound sums are grouped separately
flows_outbound <- flows %>%
Expand All @@ -132,6 +131,6 @@ sum_land_flows_county <- function(diet, waste) {

}

county_land_flows <- future_pmap_dfr(scenario_combos, sum_land_flows_county)
county_land_flows <- future_pmap_dfr(scenario_combos, sum_land_flows_county, file_path = fp_landcounties)

write_csv(county_land_flows, file.path(final_output_path, 'landflows_county_sums_all_scenarios.csv'))
4 changes: 2 additions & 2 deletions final_output/26_compile_Shiny_data.R
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,8 @@ replace_na_dt(county_land_flow_sums)

# Load foreign goods data -------------------------------------------------

import_crop <- fread(file.path(intermediate_output_path, 'fao_VLT_provisional_crops_disaggregated.csv'))
import_animal <- fread(file.path(intermediate_output_path, 'fao_VLT_provisional_animalonly.csv'))
import_crop <- fread(file.path(intermediate_output_path, 'fao_VLT_crops_disaggregated.csv'))
import_animal <- fread(file.path(intermediate_output_path, 'fao_VLT_animalonly.csv'))

import_crop <- tidyr::separate(import_crop[scenario != '', ], scenario, into = c('D', 'scenario_diet', 'W', 'scenario_waste'), sep = '_')
import_crop[, c('D','W') := NULL]
Expand Down
20 changes: 20 additions & 0 deletions final_output/figs/fig1_revision.R
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,23 @@ dev.off()
pdf(file.path(fp_fig, 'pdfs/fig1.pdf'), height = 9, width = 6)
grid.arrange(p_consprod_top, p_consprod_bottom, nrow = 2, heights = c(1, 2.6))
dev.off()


# Supplemental figure: absolute values ------------------------------------

# Absolute values
p_totaldemand_sums <- ggplot(totaldemand_sums %>% filter(scenario_waste %in% c('baseline', 'allavoidable')), aes(x = short_name, y = demand/1e9)) +
geom_col(aes(fill = kingdom), color = 'black', size = 0.25) +
facet_grid(scenario_waste ~ scenario_diet, labeller = scenario_labeller) +
scale_x_discrete(name = 'food category') +
scale_y_continuous(expand = expansion(mult = c(0, 0.03)), name = 'production (billion USD)') +
scale_fill_manual(values = setNames(okabe_colors[c(8, 4)], c('animal', 'plant'))) +
theme(panel.grid = element_blank(),
axis.text.x = element_text(angle = 45, hjust = 1),
legend.position = 'none')

p_totaldemand_sums <- ggdraw(p_totaldemand_sums + theme(plot.margin = unit(c(25, 25, 5.5, 5.5), 'points'))) +
draw_label(label = 'diet scenario', x = 0.5, y = 0.97) +
draw_label(label = 'waste scenario', x = 0.99, y = 0.5, angle = -90)

ggsave(file.path(fp_fig, 'total_consumption_10_scenarios.png'), p_totaldemand_sums, height = 9*.75, width = 12, dpi = 400)
3 changes: 3 additions & 0 deletions final_output/figs/fig3.R
Original file line number Diff line number Diff line change
Expand Up @@ -173,3 +173,6 @@ png(file.path(fp_fig, 'fig3.png'), height = 7, width = 7, res = 400, units = 'in
grid.draw(gridExtra::gtable_rbind(ggplotGrob(p_top), ggplotGrob(p_bottom)))
dev.off()

pdf(file.path(fp_fig, 'pdfs/fig3.pdf'), height = 7, width = 7)
grid.draw(gridExtra::gtable_rbind(ggplotGrob(p_top), ggplotGrob(p_bottom)))
dev.off()
15 changes: 15 additions & 0 deletions final_output/figs/fig4_and_supplemental_figs_paneledscenariomaps.r
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,21 @@ make_20panel_map_v2(map_panel_data = county_extinction_map_panels[land_use %in%
output_type = 'pdf'
)

# Fig 4 as png
make_20panel_map_v2(map_panel_data = county_extinction_map_panels[land_use %in% 'total' & taxon %in% 'total' & scenario_waste %in% c('baseline', 'allavoidable')],
base_map = county_map,
region_type = 'county',
variable = 'extinction_outbound_vs_baseline',
file_name = 'fig4',
scale_name = 'Change vs.\nbaseline',
scale_factor = 1,
scale_trans = 'identity',
scale_type = 'divergent',
ak_idx = county_ak_idx,
hi_idx = county_hi_idx,
add_theme = theme_void() + theme(legend.position = 'none'),
n_waste = 2
)

###
# For each taxon, total land use, raw extinction outbound.
Expand Down
8 changes: 4 additions & 4 deletions final_output/figs/load_data_all_figs.R
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,6 @@ county_extinction_flow_sums <- read_csv(file.path(final_output_path, 'species_lo
# Flows of species extinctions between states (raw pairwise)
state_extinction_flows <- read_csv(file.path(final_output_path, 'species_lost_state_x_state_all_scenarios_med.csv'), col_types = 'cccccd')

# Foreign virtual land transfers into USA, by country x tnc combination exporting them and by county importing them
foreign_vlt_export <- read_csv(file.path(final_output_path, 'foreign_VLT_by_country_x_TNC.csv'))
foreign_vlt_import <- read_csv(file.path(final_output_path, 'foreign_VLT_to_counties.csv'))

# Foreign flows of species extinctions into USA, by country x tnc combination exporting them and by county importing them
foreign_extinction_export <- read_csv(file.path(final_output_path, 'foreign_species_lost_by_export_country_x_tnc.csv'))
foreign_extinction_import <- read_csv(file.path(final_output_path, 'foreign_species_lost_by_import_county.csv'))
Expand All @@ -54,6 +50,10 @@ foreign_extinction_import <- read_csv(file.path(final_output_path, 'foreign_spec
foreign_animal_export <- read_csv(file.path(intermediate_output_path, 'fao_production_trade_animals.csv'))
foreign_crop_export <- read_csv(file.path(intermediate_output_path, 'fao_production_trade_crops.csv'))

# Foreign virtual land transfers into USA, by country x tnc combination exporting them and by county importing them
foreign_vlt_export <- read_csv(file.path(final_output_path, 'foreign_VLT_by_country_x_TNC.csv'))
foreign_vlt_import <- read_csv(file.path(final_output_path, 'foreign_VLT_to_counties.csv'))

# Map of counties in AEA
county_map <- st_read(file.path(spatial_output_path, 'USA_county_2014_aea.gpkg'))
# Map of TNC ecoregions in AEA
Expand Down
7 changes: 0 additions & 7 deletions final_output/figs/load_data_foreign_maps.R
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,6 @@ foreign_vlt_countries <- foreign_vlt_export[, lapply(.SD, sum, na.rm = TRUE),
by = .(scenario_diet, scenario_waste, country_name, ISO_A3, region_UN, subregion_UN),
.SDcols = patterns('^V')]

foreign_vlt_countries[scenario_diet %in% 'baseline' & scenario_waste %in% 'baseline'][order(-VLT_pasture)]
foreign_vlt_countries[scenario_diet %in% 'baseline' & scenario_waste %in% 'baseline'][order(-VLT_annual)]
foreign_vlt_countries[scenario_diet %in% 'baseline' & scenario_waste %in% 'baseline'][order(-VLT_permanent)]

# Top exporters of virtual land to the United States, baseline case.
foreign_vlt_countries[scenario_diet %in% 'baseline' & scenario_waste %in% 'baseline']

### Compare domestic and foreign VLT into the USA.

# Sum the foreign vlt across all countries.
Expand Down
147 changes: 147 additions & 0 deletions final_output/figs/supplemental_figs_paneledforeignmaps.R
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
source(file.path(code_path, 'final_output/figs/load_data_all_figs.R'))
source(file.path(code_path, 'final_output/figs/load_data_foreign_maps.R'))

library(scico)

# Only make figures for animals, plants, and total
# In total 16 figures will be generated.
# For extinction, 3 maps (animals, plants, total) x 2 (absolute and relative to baseline) = 6
Expand Down Expand Up @@ -224,3 +226,148 @@ for (landtype in landtypes_to_plot) {
)

}


# Alternative version with vertical orientation ---------------------------

make_world_panel_map_vertical <- function(map_panel_data, base_map, region_type, variable, file_name, n_waste = 4, percent_scale = TRUE, ...) {

args <- list(...)

# Calculate global range for fill scale for all plots and insets.
vals <- unlist(map(map_panel_data$data, function(x) x[[variable]]/args$scale_factor))
if (args$scale_trans == 'log10') vals <- vals[vals > 0]
global_scale_range <- range(vals, na.rm = TRUE)

# Create dummy plot with a legend so it can be extracted
scale_labs <- if (percent_scale) scales::percent else waiver()

if (args$scale_type == 'divergent') {

# Remap scale range to 0-1
global_scale_range_remap <- scale_begin_end(vals)

scale_main <- scale_fill_scico(palette = 'vik', begin = global_scale_range_remap[1], end = global_scale_range_remap[2], na.value = 'gray75', name = args$scale_name, trans = args$scale_trans, labels = scale_labs, limits = global_scale_range, guide = guide_colorbar(direction = 'horizontal'))
} else {
global_scale_range_remap = NULL
scale_main <- scale_fill_viridis_c(na.value = 'gray75', name = args$scale_name, trans = args$scale_trans, labels = scale_labs, limits = global_scale_range, guide = guide_colorbar(direction = 'horizontal'))
}

plot_leg <- get_legend(ggplot(mtcars, aes(x=cyl,y=hp,fill=mpg)) + geom_point() + scale_main + theme(legend.key.width = unit(1.5, 'cm')))

# Draw plots
maps_list <- map(map_panel_data$data, function(x) ggplot(left_join(base_map, x)) +
geom_sf(aes_string(fill = variable), size = 0.1) +
geom_sf(data = st_geometry(poly_countries), fill = NA) +
scale_main +
args$add_theme)

waste_labels <- waste_long_names$long_name
if (n_waste == 2) waste_labels <- waste_labels[c(1, 4)]

maps_laidout <- panel_plot(plots = maps_list,
y_labels = diet_long_names$long_name,
x_labels = waste_labels,
y_title = 'diet scenario',
x_title = 'waste scenario',
global_legend = plot_leg,
label_fontsize = 7,
title_fontsize = 14,
panel_width = 60,
panel_height = 35,
label_width = 5,
title_width = 10,
legend_height = 15)

png(glue('{fp_foreignmaps}/{file_name}.png'), width=16,height=24,res=200,units='cm')
grid.draw(maps_laidout)
dev.off()

}

# Extinction maps vertical ---------------------------------------------------------

taxa_to_plot <- c('animals', 'plants', 'total')

for (tax in taxa_to_plot) {
dat <- foreign_extinction_country_panels[taxon %in% tax & land_use %in% 'total']
dat[, scenario_diet := factor(scenario_diet, levels = diet_levels_ordered)]
dat[, scenario_waste := factor(scenario_waste, levels = waste_levels_ordered)]
dat <- dat[order(scenario_waste, scenario_diet)]
message(paste('Drawing maps for', tax))

# Outbound, relative, 10 panels
make_world_panel_map_vertical(map_panel_data = dat[scenario_waste %in% c('baseline', 'allavoidable')],
base_map = country_map_toplot,
region_type = 'country',
variable = 'species_vs_baseline',
file_name = glue('10scenariosvertical_country_extinction_{tax}_outbound_vs_baseline'),
scale_name = 'Change vs.\nbaseline',
scale_factor = 1,
scale_trans = 'identity',
scale_type = 'divergent',
add_theme = theme_void() + theme(legend.position = 'none'),
n_waste = 2
)

# Outbound, absolute, 10 panels
make_world_panel_map_vertical(map_panel_data = dat[scenario_waste %in% c('baseline', 'allavoidable')],
base_map = country_map_toplot,
region_type = 'country',
variable = 'species_lost',
file_name = glue('10scenariosvertical_country_extinction_{tax}_outbound'),
scale_name = 'Virtual extinction\nexport',
scale_factor = 1,
scale_trans = 'log10',
scale_type = 'sequential',
percent_scale = FALSE,
add_theme = theme_void() + theme(legend.position = 'none'),
n_waste = 2
)

}



# Land maps vertical ---------------------------------------------------------------


landtypes_to_plot <- unique(foreign_vlt_country_panels$land_use)

for (landtype in landtypes_to_plot) {
dat <- foreign_vlt_country_panels[land_use %in% landtype]
dat[, scenario_diet := factor(scenario_diet, levels = diet_levels_ordered)]
dat[, scenario_waste := factor(scenario_waste, levels = waste_levels_ordered)]
dat <- dat[order(scenario_waste, scenario_diet)]
message(paste('Drawing maps for', landtype))

# Outbound, relative, 10 panels
make_world_panel_map_vertical(map_panel_data = dat[scenario_waste %in% c('baseline', 'allavoidable')],
base_map = country_map_toplot,
region_type = 'country',
variable = 'VLT_vs_baseline',
file_name = glue('10scenariosvertical_country_{landtype}_outbound_vs_baseline'),
scale_name = 'Change vs.\nbaseline',
scale_factor = 1,
scale_trans = 'identity',
scale_type = 'divergent',
add_theme = theme_void() + theme(legend.position = 'none'),
n_waste = 2
)

# Outbound, absolute, 10 panels
make_world_panel_map_vertical(map_panel_data = dat[scenario_waste %in% c('baseline', 'allavoidable')],
base_map = country_map_toplot,
region_type = 'country',
variable = 'VLT',
file_name = glue('10scenariosvertical_country_{landtype}_outbound'),
scale_name = 'Virtual land\nexport (ha)',
scale_factor = 1,
scale_trans = 'log10',
scale_type = 'sequential',
percent_scale = FALSE,
add_theme = theme_void() + theme(legend.position = 'none'),
n_waste = 2
)

}
Loading

0 comments on commit 3e521bb

Please sign in to comment.