Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
97 commits
Select commit Hold shift + click to select a range
8e2f121
csvv writer running, missing some climate variables atm
TomBearpark Jun 20, 2020
289e32f
csvv writer complete
TomBearpark Jun 20, 2020
a9761c0
Merge branch 'master' of https://github.com/ClimateImpactLab/energy-c…
TomBearpark Jun 21, 2020
982be2b
commits from master
TomBearpark Jun 21, 2020
fc538fe
Create readme.md
TomBearpark Jun 21, 2020
c028a8c
update file path for csvvs
TomBearpark Jun 22, 2020
f364009
Merge branch 'projection' of https://github.com/ClimateImpactLab/ener…
TomBearpark Jun 22, 2020
5a3ef33
config writer path changes, going to run it now on sac
TomBearpark Jun 22, 2020
2ae148c
tweak
TomBearpark Jun 22, 2020
e04160b
First attempt at master projection readme
TomBearpark Jun 22, 2020
be4afb7
Update readme.md
TomBearpark Jun 22, 2020
8a1eb62
Update readme.md
TomBearpark Jun 22, 2020
32e9280
added maxInc_gpid var to break data
TomBearpark Jun 23, 2020
44008d7
Merge branch 'projection' of https://github.com/ClimateImpactLab/ener…
TomBearpark Jun 23, 2020
ca14161
working on config writer
Jun 23, 2020
33ad101
Merge branch 'projection' of https://github.com/ClimateImpactLab/ener…
Jun 23, 2020
63de433
first pass projection files
Jun 23, 2020
603a04a
first pass at configs
Jun 23, 2020
abbe2ce
fixed looping error
Jun 23, 2020
7d089c6
config writer working correctly
Jun 23, 2020
3ccc5dd
added slow adapt configs
TomBearpark Jun 23, 2020
4a58070
included post-projection processing pacakges
TomBearpark Jun 23, 2020
6c83367
making load projection work without gcp-energy
TomBearpark Jun 23, 2020
261022e
updating paths to not depend on gcp-energy
Jun 23, 2020
f99addf
Update readme.md
TomBearpark Jun 23, 2020
f1b5397
added a readme
TomBearpark Jun 23, 2020
6962a87
Merge branch 'projection' of https://github.com/ClimateImpactLab/ener…
TomBearpark Jun 23, 2020
bdbfe18
Update 2_prepare_damage_function_data.R
TomBearpark Jun 23, 2020
c585581
Create readme.md
TomBearpark Jun 23, 2020
c80ceac
Update readme.md
TomBearpark Jun 23, 2020
d45d177
Update readme.md
TomBearpark Jun 23, 2020
8801c50
Update README.md
TomBearpark Jun 23, 2020
f69baa4
Update README.md
TomBearpark Jun 23, 2020
05d135f
Update README.md
TomBearpark Jun 23, 2020
a899e20
Delete load_single.R
TomBearpark Jun 23, 2020
c002a1c
better organisation of bash file
TomBearpark Jun 23, 2020
c364bc6
Update README.md
TomBearpark Jun 23, 2020
fec1ad9
Update readme.md
TomBearpark Jun 23, 2020
b852843
Update readme.md
TomBearpark Jun 23, 2020
12a3e84
Update readme.md
TomBearpark Jun 23, 2020
0f2f2e6
Update readme.md
TomBearpark Jun 23, 2020
1577ef5
Update readme.md
TomBearpark Jun 23, 2020
f8e6958
Update readme.md
TomBearpark Jun 23, 2020
596439d
Update readme.md
TomBearpark Jun 23, 2020
a477197
Update readme.md
TomBearpark Jun 23, 2020
e445b11
Update readme.md
TomBearpark Jun 24, 2020
2cc32fe
added brc projection files
Jun 24, 2020
a6a070d
added projection slurm scrips
Jun 24, 2020
ec4abb7
updated structure of codes that extract inpacts and save in code rele…
TomBearpark Jun 25, 2020
73c7d45
sorted projection extraction codes
TomBearpark Jun 25, 2020
62ff511
Update readme.md
TomBearpark Jun 25, 2020
b4a81bf
Update readme.md
TomBearpark Jun 25, 2020
9a5ce90
Update readme.md
TomBearpark Jun 25, 2020
488fc46
Update readme.md
TomBearpark Jun 25, 2020
228780a
Create readme.md
TomBearpark Jun 25, 2020
3bacd05
updating readme - still more to be done though
TomBearpark Jun 25, 2020
3db1a51
Update readme.md
aarode Jun 26, 2020
a617eb2
Update readme.md
aarode Jun 26, 2020
d913753
Update 2_generate_projection_configs.do
TomBearpark Jun 26, 2020
9c24e3f
Update readme.md
TomBearpark Jun 26, 2020
26768a6
Update readme.md
TomBearpark Jun 26, 2020
b63ab2d
Update readme.md
TomBearpark Jun 26, 2020
8b0cf15
Update readme.md
TomBearpark Jun 26, 2020
6a845fe
Update readme.md
TomBearpark Jun 26, 2020
06f12e0
Update README.md
TomBearpark Jun 26, 2020
22b1406
Update README.md
TomBearpark Jun 26, 2020
10d8449
Update README.md
TomBearpark Jun 26, 2020
8db95e7
Update bash-extraction-script.md
TomBearpark Jun 26, 2020
03cc39e
Update README.md
aarode Jun 26, 2020
e3c0ed8
Update README.md
aarode Jun 26, 2020
cac4d91
Update README.md
aarode Jun 26, 2020
b0d26b9
Update readme.md
aarode Jun 26, 2020
bfaa521
Update readme.md
TomBearpark Jun 27, 2020
bef58fb
Update readme.md
TomBearpark Jun 27, 2020
21c99bd
Update README.md
TomBearpark Jun 27, 2020
2da2798
Update README.md
TomBearpark Jun 27, 2020
f440f7e
Update readme.md
TomBearpark Jun 27, 2020
a2b8502
aggregation bash script
TomBearpark Jun 28, 2020
063982d
Update readme.md
TomBearpark Jun 28, 2020
5f8e057
Update readme.md
TomBearpark Jun 28, 2020
109b2ec
Update 0_save_covariate_data.R
TomBearpark Jun 28, 2020
f6fee08
Update 0_save_covariate_data.R
TomBearpark Jun 28, 2020
75d49f2
aesthetic comment tweaks
TomBearpark Jun 28, 2020
6ed79d6
Update 0_save_covariate_data.R
TomBearpark Jun 28, 2020
32be949
Update 1_prepare_visualisation_data.R
TomBearpark Jun 28, 2020
913ad7d
Update 1_prepare_visualisation_data.R
TomBearpark Jun 28, 2020
2b2b17d
Update 2_prepare_damage_function_data.R
TomBearpark Jun 28, 2020
b93bc31
Update 2_prepare_damage_function_data.R
TomBearpark Jun 28, 2020
9411d20
Update 2_prepare_damage_function_data.R
TomBearpark Jun 28, 2020
522ea1e
Create readme.md
TomBearpark Jun 28, 2020
41aa323
Update readme.md
aarode Jun 29, 2020
9242869
Update readme.md
aarode Jun 29, 2020
ec9ba43
Update extraction_quantiles.sh
TomBearpark Jun 29, 2020
323dcab
Update readme.md
TomBearpark Jun 29, 2020
8cc13eb
Update readme.md
TomBearpark Jun 29, 2020
2df634c
Update readme.md
TomBearpark Jun 29, 2020
185915e
Update 1_prepare_visualisation_data.R
TomBearpark Jun 30, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
3 changes: 2 additions & 1 deletion 0_make_dataset/2_construct_regression_ready_data.do
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ pause off

global root "/Users/`c(username)'/Documents/repos/energy-code-release-2020"


/////////////////////////////////////////////////////////////////////////////////////////////////

******Set Script Toggles********************************************************
Expand Down Expand Up @@ -122,6 +121,8 @@ replace hdd20_TINV_GMFD = hdd20_other_TINV_GMFD if inlist(product,"other_energy"
qui egen avgHDD_tpid=mean(hdd20_TINV_GMFD), by(tpid) //average HDD in each cell
qui egen avgInc_tgpid=mean(lgdppc_MA15), by(tgpid) //average lgdppc in each cell

qui egen maxInc_gpid=max(lgdppc_MA15), by(gpid) //max lgdppc in each cell - this is needed for configs

//max lggdppc for each large income group for each cell
foreach var in "other_energy" "electricity" {
qui egen maxInc_largegpid_`var'=max(lgdppc_MA15), by(largegpid_`var')
Expand Down
2 changes: 1 addition & 1 deletion 1_analysis/1_uninteracted_regression.do
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ macro drop _all

// path to energy-code-release repo

global root "/Users/`c(username)'/Documents/repos/energy-code-release"
global root "/Users/`c(username)'/Documents/repos/energy-code-release-2020"

/////////////////////////////////////////////////////////////////////////////////////////////////

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
### Packages for processing projection output

##### `load_projection/.`
- This directory contains functions to query projection data from median projection output. Documentation for how to use these functions is within the subdirectory `load_projection`.
- Please note that this depends on projection system codes that are currently unreleased (specifically, `quantiles.py` from the `open-estimate` repo).
- To run this code, you should be inside the `risingverse-py27` conda environment. See the readme in `2_projection/2_running_projections/` for more details.

##### `future_gdp_pop_data.py`
- To run this code, you will need to be inside the `risingverse` conda environment. Please see the readme in `2_projection/2_running_projections/` for more details.
- Functions retrieve the following outputs from the projection system:
- future population data for each impact region for all years
- global gdp time series into the future
- future income per capita data for each impact region for all years

Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# adapted from mortality valuation code
# check to make sure population interpolation is happening how you want it to be

from impactcommon.exogenous_economy import gdppc, provider
import numpy as np
import pandas as pd
import metacsv
from impactlab_tools.utils import files
import os

## Takes landscan2011 and fills in where no pop (held constant at 2011)

def get_missing_pop(df, dfir, lspop):
tmp = dfir.merge(df.loc[(df.year == 2015) & (df.ssp == 'SSP3')], how = 'left', on = ['region', 'iso'])
tmp = tmp.loc[np.isnan(tmp['pop']),'region']
tmplist = []
for reg in tmp:
for ssp in df.ssp.unique():
yvect = df.year.unique()
series = np.repeat(lspop.loc[lspop.hierid == reg,'lspopzeros'], yvect.size)
svect = np.repeat(ssp, yvect.size)
rvect = np.repeat(reg, yvect.size)
isovect = np.repeat(lspop.loc[lspop.hierid == reg,'ISO'], yvect.size)
tmpdf = pd.DataFrame({'year':yvect, 'region':rvect, 'pop':series, 'ssp':svect, 'iso':isovect})
tmplist.append(tmpdf)
dfp = pd.concat(tmplist,sort = False)
return dfp

## Get population for all impact regions

def get_pop():

lspop = pd.read_csv(files.sharedpath('social/processed/LandScan2011/gcpregions.csv'), header = 17)

dfir = metacsv.read_csv(files.sharedpath("regions/hierarchy_metacsv.csv"))
dfir = dfir.loc[dfir.is_terminal].reset_index(drop=True)
dfir.drop(['parent-key', 'name', 'alternatives', 'is_terminal', 'gadmid', 'agglomid', 'notes'],axis=1,inplace=True)
dfir.rename(columns={'region-key':'region'}, inplace=True)
dfir['iso'] = dfir.region.apply(lambda x: x[:3])

df = pd.read_csv(files.sharedpath('social/baselines/population/merged/population-merged.all.csv'))

df.rename(columns={'value':'pop'}, inplace=True)
df['iso'] = df.region.apply(lambda x: x[:3])
df.drop(['index'], axis=1, inplace=True)
df = df.loc[df.year>2005]

dff = df.append(get_missing_pop(df,dfir,lspop), sort = False).sort_values(['region','year']).reset_index(drop=True)

return dff

# get gdp pc for all impact regions

def get_gdppc_all_regions(model, ssp):

print(model+" "+ssp)
os.chdir(os.getenv("HOME") + '/repos/impact-calculations')
moddict = {'high' : 'OECD Env-Growth', 'low' : 'IIASA GDP'}
df = metacsv.read_csv(files.sharedpath("regions/hierarchy_metacsv.csv"))
tmplist = []
yvect = np.arange(2010, 2101)
svect = np.repeat(ssp, yvect.size)
mvect = np.repeat(moddict[model], yvect.size)
provider = gdppc.GDPpcProvider(model,ssp)

for ii in np.where(df.is_terminal)[0]:
series = provider.get_timeseries(df['region-key'][ii])
rvect = np.repeat(df['region-key'][ii], yvect.size)
tmp = pd.DataFrame({'region':rvect, 'year':yvect, 'gdppc':series, 'ssp':svect, 'model':mvect})
tmplist.append(tmp)

dfg = pd.concat(tmplist, sort = False)

return dfg

# create a global gdp time series -- input data frame output from get_gdppc_all_regions
# this whole situation could be made smarter :)... go for it if you are tryna

def convert_global_gdp(df):
df['year_floor'] = df.year/5
df['year_floor'] = df.year_floor.round()
df['year_floor'] = df.year_floor*5
df = df.astype({'year_floor':'int64'})
pop = get_pop().rename(columns={'year':'year_floor'})
pop = pop.loc[pop.ssp == 'SSP3']
df2 = df.merge(pop, on = ['region', 'year_floor','ssp'], how = 'left')
df2['gdp'] = df2['pop']*df2['gdppc']
dff = df2[['gdp','ssp','year']].groupby(['ssp','year']).sum()
return dff
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Query Projection Output Data

- The purpose of the codes in this directory is to extract and load projection system outputs.
- The projection system outputs ncdf files, which are GCM specific.
- In order to calculate quantiles and means of the impacts across these GCMs, we run a code called `quantiles.py` from the `open-estimate` repo (not currently released). This code outputs a csv of impacts, where the impacts are calculated as means or quantiles of the impacts from each of the GCMs.
- When running the `load.median()` function from this package, we:
- First check if the desired csv of quantiles of our impacts already exists.
- If it does exist, we load it.
- If it doesn't exist, we run a wrapper for `quantiles.py` that extracts the desired output csv from the ncdf files, and the loads it.
- Please note, in order to extract the outputs, this package reads the necessary extraction configs in this repo, to work out which extraction command is needed for a given query.
- Currently the system is only set up to query point estimate and delta method output (i.e. variance of projected impact estimates, see Appendix Section C.5). If you would like to query single run outputs, you will need to add more functionality.

## Necessary steps for using this system:
1. Create a bash script similar to `example.sh`, which extracts a specific file specified by a set of parameters. Please reference `bash-extraction-script.md` for documentation on necessary syntax for creating a bash script which will integrate with the data querying code. Note - the bash script that is actually used in this code is in this folder and is called `extraction_quantiles.sh`.
2. Write necessary configs for all desired extraction calls from `quantiles.py` (a code in an external repo used for extracting quantiles across projection system outputs).
3. Add a get.*.code.paths() function to tell the querying system where your extraction bash script created in step 1 lives.
4. Source all functions in this directory.
5. Query Data - please reference `load-projection-parameters.md`. Also here's a code snippet for how to go about querying data:
```
projection.packages = {path_to_load_projection}

miceadds::source.all(paste0(projection.packages,"load_projection/"))
args <- list(
conda_env = 'risingverse-py27', # your conda environment
proj_mode = '_dm', # '' and _dm are the two options. Determines if we are extracting means(`''`) or variances (`'_dm'`)
region = "ARE.5", # needs to be specified for delta method outputs. A region for which we have a projection result (can be an aggregated region)
rcp = NULL,
ssp = "SSP3",
price_scen = 'price014', # have this as NULL, "price014", "MERGEETL", ...
unit = "damage", # 'damagepc' ($ pc) 'impactpc' (kwh pc) 'damage' ($ pc). Must be impactpc if price scenario is NULL
uncertainty = "values", # full, climate, values
geo_level = "levels", # aggregated (ir agglomerations such as countries or the "global" region) or 'levels' (single IRs)
model = "TINV_clim_income_spline", # energy specific
adapt_scen = "fulladapt", # adaptation scenario - can be "fulladapt", "noadapt", or "incadapt"
clim_data = "GMFD", # energy specific
iam = "high",
yearlist = as.character(seq(1980,2100,1)),
spec = "OTHERIND_total_energy", # can be "OTHERIND_total_energy", "OTHERIND_electricity", or "OTHERIND_other_energy"
dollar_convert = "yes", # determines whether to convert dollar outputs from 2005 USD to billions of 2019 USD.
grouping_test = "semi-parametric") # energy specific)

df = do.call(load.median, args)

```

For first time users, these are the functions I predict you will need to adapt to make sure they make sense for you sector as well as energy:
* assign.names(), load.median.check.params() (this is not an all encompassing list... I'll add to it as I think of more things)

## Code Outline:

### bash.R - Functions for interacting with extraction bash script from R

* *call.shell.script()* - Calls extraction shell script
* *check.memory()* - Kills process if there isn't enough available memory for the process to keep running
* *get.available.memory()* - Get available memory for use
* *get.process.memory.use()* - Get process memory use (in percent of total memory)
* *get.bash.parameters()* - Gets parameters ready for use in call.shell.script. Along the way, function checks to make sure parameter values are within the functionality of the extraction shell and required parameters have non-null non-blank values
* *extract()* - Perform extraction while monitoring memory use
* *check.file.complete()* - Check to see if a file is complete based on time last touched

### load_median.R - Query data from Median Run

* *load.median.check.params()* - Check data query parameters are valid (always a work in progress :) - more should be added whenever anyone has time!)
* *load.median()* * - loads a csv of results if it exists, and if not, runs an extraction

### clean_data.R - Clean queried data

* *assign.names()* - based on data query and data frame add more variables to df to define what the contents of the data frame is
* *convert.to.2019* - changes means and variances from 2005 to 2019 dollars

### get_paths.R - Functions for getting desired paths and file names from query}

* *get.energy.code.paths()* - get path to energy quantiles extraction shell
* *get.file.paths()* - Get relevant file paths for querying data
* *get.paths()* - Get relevant code and file paths

### parse.R - Functions for parsing config and shell scripts to extract desired info about query

* *get.line.var()* - look through a specific string for a specific parameter's definition
* *get.file.var()* - Scroll through all lines of a file and get value of a specific variable defined at some point in the file
* *get.shell.file.parameters()* - Get list of parameters that need to be defined when calling extraction bash script as well as information about that parameter
* this function relies on very specific syntax in the extraction bash script. I document the syntax specifics [here](https://github.com/ClimateImpactLab/energy-code-release-2020/blob/projection/2_projection/0_packages_programs_inputs/extract_projection_outputs/load_projection/bash-extraction-script.md).
* *parse.config.structure()* - Convert an extraction config's file-structure parameter to the file prefix outputted from the extraction config





Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# How to set up a bash extraction script that agrees with the data querying system

#### 0) Checkout [example.sh](https://github.com/ClimateImpactLab/energy-code-release-2020/blob/projection/2_projection/0_packages_programs_inputs/extract_projection_outputs/load_projection/example.sh)
This file extracts a specific file or set of files specified by a set of parameters. Some of the syntax used in this script is not arbitrary and essential to the functionality of the querying code. I try to flag the important syntax below and explain the reasoning behind it. Also to better understand how to set this script up and the configs that it references checkout [prospectus-tools](https://github.com/jrising/prospectus-tools/tree/master/gcp/extract).

#### 1) Essential syntax to note (obviously if you think of a more simplified way of doing this improve it!)

##### a) the extract boolean is an essential parameter and its functionality must be replicated
why you might ask: currently the code uses the bash script in two ways
* its used to get file path information (config path, log file, and the queried data's file suffix (present or future))
* the config path is necessary to get the queried data's file prefix (present or future)
* the log file is usefule in monitoring extraction progress if extraction is necessary
* the file suffix is necessary for seeing if the file already exists, so the code can determine if extraction is necessary
* checkout [get.file.paths()](https://github.com/ClimateImpactLab/energy-code-release-2020/blob/projection/2_projection/0_packages_programs_inputs/extract_projection_outputs/load_projection/get_paths.R) to better understand why this functionality is important
* its also used to extract files if necessary

##### b) parameters are defined in a very specific way... copy this syntax

For example, this line defines the model parameter. The slashes (`/`) indicate the start and stop of a definition. The colons (`:`) seperate the definition type from the definition value.
```
## / parameter:model / options:TINV_clim_income_spline, TINV_clim_income_spline_lininter / required:yes /
```
Each parameter the bash extraction script has functionality for should be documented in the file in this way.
why you might ask (...inquisitive bunch):
* to confirm the bash script is being fed the right parameters, the script checks to make sure you are feedint the script all the required parameters and that all of the parameters' values are supported by the script.
* checkout [get.shell.file.parameters()](https://github.com/ClimateImpactLab/energy-code-release-2020/blob/projection/2_projection/0_packages_programs_inputs/extract_projection_outputs/load_projection/parse.R) and [get.bash.parameters()](https://github.com/ClimateImpactLab/energy-code-release-2020/blob/projection/2_projection/0_packages_programs_inputs/extract_projection_outputs/load_projection/bash.R) to understand the ins and outs of why this specific syntax is necessary for the current code's status.

##### c) the following four lines of code are necessary

```
echo "extraction.config:${ecp}"
echo "suffix:${suffix}"
echo "log.file:${log_file}"
```
and, at the bottom of the script in the extraction conditional
```
echo "pid:$!"
```
why you might ask? ...this one i'll let you figure out. Here are two hints [get.file.paths()](https://github.com/ClimateImpactLab/energy-code-release-2020/blob/projection/2_projection/0_packages_programs_inputs/extract_projection_outputs/load_projection/get_paths.R) and [extract()](https://github.com/ClimateImpactLab/energy-code-release-2020/blob/projection/2_projection/0_packages_programs_inputs/extract_projection_outputs/load_projection/bash.R)


Loading