---
title: "Can the world become carbon neutral using direct solar energy?"
author: "Duncan Golicher"
date: "12/30/2019"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,warning=FALSE,message=FALSE)


```



```{r}

# devtools::install_github("dgolicher/aqm")  Uncomment to install data packages from github
# devtools::install_github("dgolicher/giscourse")

library(aqm)
library(giscourse)
libs()
library(tmap)
library(mapview)
library(sf)
library(tidyverse)
library(rjags)
library(ggmcmc)
library(polspline)
library(propagate)

wld<-rnaturalearth::ne_countries(scale=10, ret="sf")
wld$Code<-wld$iso_a3 
```


# A "photosynthetic" global economy?

In 2008 David Mackay published a very useful on-line book which contained detailed calculations on the amount of energy consumed per person in the UK and the potential for replacing  their fossil fuel consumption by renewables. 

https://www.withouthotair.com/

The conclusion of this work was that the UK could not easily switch to using only renewable sources of energy based on the current levels of energy consumption. There are simply too few renewable options that produce enough energy per unit of surface area. Even if wind turbines were placed on every available onshore and offshore site the total energy produced would barely reach 10% of consumption. Some combination of assorted renewable sources, plus nuclear might end up as an option that would reduce carbon emissions to sustainable levels. This would be combined with energy efficient homes and energy efficient transport. 

All the calculations in the book still hold up, at least to within the level of precision that would be useful to consider the options. However back in 2009 the potential of direct solar energy was still unclear. At the time the book was written photovoltaic panels were much more expensive and were much less efficient than they are today. The last chapter of the book included calculations on the amount of solar power that could be generated in deserts. The conclusion was that switching to this energy source would be feasible in theory, but would be technically and politically impossible. The failure of the desertec project seems to have confirmed this.
https://newint.org/features/2015/03/01/desertec-long
Is this still true? The dertec project was based mainly around concentrated solar power. Could cheap photovoltaic energy change the game?


The aim of this article is to try to update some of David Mackay's data driven calculations a little. There is nothing  wrong with just writing down some simple calculations on the back of an envelope providing they do use defensible empirical data. However the back of an envelope cannot run MCMC model fitting. So I have documented some quick calculations in R and included all the code so that the workings can be checked. 

## World energy production

Data from  https://ourworldindata.org/energy-production-and-changing-energy-sources has been added to the aqm package for easy access. The code below shows the data concisely. 

```{r, warning=FALSE}
# https://ourworldindata.org/energy-production-and-changing-energy-sources 

data("global_energy")
d<-global_energy


d %>% filter(Year==2017) %>% arrange(value) %>% 
  mutate(name = factor(name, name)) %>% mutate(percent=100*value/sum(value)) %>%
  
  
ggplot(aes(x=name, y=value, label=paste(round(percent,1), "%"))) + geom_col() +  geom_label() +coord_flip() + ylab("Terrawatt-hours") +ggtitle("World energy production in 2017")

```
   
   
(Note that a terrawatt hour is 1 x 10¹² Watthours i.e 1 x 10⁹ kWh.)  


In 2017 the world still relied  on fossil fuels. All renewable sources including hydro electric made up just 7% of the total energy production. Around 18% of total world energy production was in the form of electricity. The other 82% was used for heat and transportation. 

This is a key detail to remember. Whenever any report cites the contribution of renewables to the energy mix it is absolutely vital to check whether the figure refers to total energy production or the proportion of the electricity generated. They are very different figures. The difference is almost an order of magnitude! Direct solar power clearly contributes a very tiny fraction at 0.3% of the total energy production but this is just under 2% of total electrical production. Still small, but 2% does sound much better than 0.3%. If a non academic online article is trying to talk up the contribution of solar it will base calculations on the 2% and to improve on this it will find additional denominators to make the figure  even more impressive. This is all just more hot air as the title of Mackay's book suggests. The online hype is mainly aimed at influencing short term share prices.

The unspun reality is that only 0.3% of total power production came from solar in 2017. Some of the spin comes from solar energy producers, some may even comes from oil companies in order to give the impression that their own contribution to global emissions is less than it really is. To work around any hype the best strategy is to gnore all but the primary data sources and check all the  calculations.  

A key question to be answered is "are these underlying figures set to change dramatically in the near future?" 

Current total world energy production stands at around `r ttl<-160 * 10^12 ` 160 x 10¹² kWh per year and still rising. There are good reasons to suspect that the upward trend will flatten out in the near future, but there is little in the aggregated global data to show any slow down in overall production. The main reason that some major countries such as the UK and USA have constrained Co_2 emissions slightly has been the switch from oil and coal to gas. 

```{r, warning=FALSE}
d %>% filter(Year> 1960) %>% 
ggplot( aes(x=Year,y=value/ 1000,fill=name)) + geom_area() + ylab("Kwh * 10^12") +ggtitle("Total global energy production") + scale_fill_brewer(palette = "Dark2")
```

## Solar percentage supply by country and entity

The table below shows that Japan and Italy currently produce the highest percentage of their energy through direct solar. The percentages remain below 2% of total energy production.

```{r}
data("energy_by_country")
d<-energy_by_country
d %>% filter(Year==2018) %>% group_by(Entity, name) %>% summarise(production=round(value,2))  %>% mutate(percent=(round(100*production/sum(production),2))) %>% filter(name=="Solar") %>%  arrange(-percent) %>% filter(percent> 0.1) %>% dt()
```

At present solar power clearly only makes a very minor contribution to all countries energy supply. 

The argument in favour of directly converting solar energy into a form that can be used to power our entire economy is very simple. Most other forms of energy, with the exception of nuclear, wind and hydro, are based on the highly inefficient solar energy conversion mechanism that is biological photosynthesis. The alternative to capturing sunlight through biological processes (and other indirect processes such as wind and rain) is to simply "cut out the middle man". We could base our future economy on direct solar capture taking place in real time. That would turn humanity into a photosynthetic civilisation, in the sense that we would synthesise all our most important needs directly from sunlight. The idea has been around for a long time. In 1986 the German physicist Gerhard Knies calculated that in just six hours, the world’s deserts receive more energy from the sun than humans consume in a year. Interesting, but totally irrelevant if the energy cannot be captured.

Biological photosynthesis at best can only convert around 4% of incoming solar radiation into usable biomass. The world's fossil fuel reserves are the result of integrating this highly inefficient process over millions of years. One of the best arguments against using the current biological photosynthetic process as a solar energy harvesting mechanism is that the photosynthetic process involves two key inputs. These are water and solar radiation. A major problem lies in the fact that the availability of each of these inputs has the tendency to be negatively correlated with the other. Sunny areas tend to have low rainfall, wet areas tend to be less sunny. Thus the production of bio-fuels is either inefficient or it takes scarce resources away from agriculture or it does both. The most efficient crop production involves irrigation, but this leads to additional issues. Photosynthesis taking place on productive crop land has to continue in order to provide food for the human population.  Bio-fuel production poses a risk to biodiversity by destroying functioning ecosystems in the most productive regions of the tropics. 
In stark contrast the best area to harvest solar energy directly is unproductive desert with relatively low biological diversity and low rainfall. Urban areas, and paved surfaces that neither support crops nor much biodiversity alsoe provide a suprisingly large potential contribution to direct solar energy capture.

## The potential of solar power

The total energy that could be captured through the use of photovoltaic cells or other direct conversion mechanisms varies according to latitude and climate. 

https://globalsolaratlas.info/download

```{r}
wld %>% filter(name %in% c("United Kingdom", "Finland", "Italy")) -> UK
library(raster)
library(RColorBrewer)

ghi<-raster("GHI/GHI.tif")
ghi<-raster::crop(ghi, UK)
counties<-rnaturalearth::ne_states(country="United Kingdom", ret="sf")
raster::plot(ghi*365, col=brewer.pal(10,"Spectral")[10:1])
```



![](https://britishbusinessenergy.co.uk/wp-content/uploads/SolarGIS-Solar-map-Europe-en.png)

Solar panels have a maximum efficiency of about 20%. They therefore produce around **200 kwh of electricty per square meter per year** in the South of England. There is more energy to be converted in sunnier climates, with a maximum value of around 400 to 500 kWh in a sunny desert with clear skies almost every day. Note that concentrated solar power only would be viable at all in deserts. In the case of PVA based power generation deserts are clearly prefered sites, but panels placed in a desert are only two to three times more efficient than in the sunnier parts of Europe.

Taking the lower 200 kWh as the average figure for energy generation we can get a rough and ready estimate the land surface that needs to be covered by solar panels to provide the entire current world's energy supply.


```{r}
sqmt<-160 * 10^12 / 200
sqkm<-sqmt/1000000
tsqkm<-sqkm /1000

```


This figure of `r tsqkm` thousand square kilometres is clearly a very large area. It is similar in magnitude to the entire land area of France or Spain. China has a total land area of just under 10 million square kilometres, so the figure represents `r round(100*tsqkm/10000,1)` \% of the area China. It is not worth trying to find a more precise estimate than this, as there are far too many uncertainties involved. The basic workings are shown in R just to ensure that no errors have been made with orders of magnitude. Given that the units of power (watts) and energy(Kwh) involved are rather non intuitive some care is needed to prevent accidental mistakes involving powers of 10.

Having a ball park figure is useful. While this is a large area, it is still much less than the total land area currently used for crops (11 million square km) and very much less than the total used in agriculture (50 million square km). This observation alone demonstrates the fundamental inefficiency of biological photosynthesis. The current human population requires much more land for food than it does to produce the energy required to maintain an energy intensive modern economy. This is quite surprising in itself.

To make the energy production efficient and with a very low impact on biodiversity it should be concentrated in barren deserts. The total area of the Sahara desert is 9.2 million square km.  Covering a proportion of the Algerian desert with solar panels could produce the entire World's energy if it were possible to solve all the associated problems of energy storage and transportation. Unfortunately these practical problems are still totally insurmountable in practice (the desertec project is stalled and unlikely to ever continue in the current political climate) but the fact that the sums do add up are a cause for optimism.


```{r}
tsqkm<-tsqkm/2 ## The solar energy is at least twice that of the UK, so lower the area needed by a half 
r<-sqrt(tsqkm*1000) * 1000
algeria<-rnaturalearth::ne_countries(country = 'algeria', scale=10, ret="sf")
algeria<-st_transform(algeria,3857)
poly<-st_centroid(algeria)
poly<-st_as_sfc(st_bbox(st_buffer(poly,r/2)))
africa<-rnaturalearth::ne_countries(continent = 'africa', scale=10, ret="sf")
library(tmap)
qtm(africa)+qtm(algeria) + qtm(poly,fill="red")
```


## UK

The UK currently produces around 2.2 thousand terrawatt hours per year, which is about `r 100* 2.2/160 `% of the total world's energy production.

```{r}
data("energy_by_country")
d<-energy_by_country

d %>% group_by(Year) %>% summarise(total=sum(value)/1000) -> ttl
d %>% filter(Year==2017) %>% filter(Entity=="United Kingdom") %>% arrange(value) %>% 
  mutate(name = factor(name, name)) %>% mutate(percent=100*value/sum(value)) %>%
  
  
ggplot(aes(x=name, y=value, label=paste(round(percent,1), "%"))) + geom_col() +  geom_label() +coord_flip() + ylab("Terrawatt hours") +ggtitle("UK energy production in 2017")



```


The same calculations can be run to find the area needed to produce all the UK's energy from direct solar.

```{r}
sqmt<-2.2 * 10^12 / 200
sqkm<-sqmt/1000000
tsqkm<-sqkm /1000

```


The ball park area of solar panels that would meet the current UK energy needs is thus `r tsqkm` thousand square km. This is around half the area of Wales or about 4% of the total land area of the UK. The polygon shows an illustrative area of the South of England that could provide the UK's energy if totally covered by solar panels. 



```{r}

UK<-rnaturalearth::ne_countries(country = 'united kingdom', scale=10, ret="sf")
UK<-st_transform(UK,3857)
r<-sqrt(tsqkm*1000) * 1000
poly<-st_geometry(st_centroid(UK)) + c(100000, -500000) # Move to a more central area
poly<-st_as_sfc(st_bbox(st_buffer(poly,r/2)))



```




```{r}

qtm(UK) + qtm(poly, fill="red")
```

This is quite a remarkably small area. Although PVAs are relatively inefficient in the UK, the total energy they could generate can still meet the UKs needs. Focussing only on deserts as a source of solar energy missed this key point. When David Mackay wrote his book concentrated solar power (CSP) was cheaper than PVA based power. Now PVA is around half the cost of CSP and falling. CSP would never be cost efficient in the UK, but PVA can be.

Of course if any attempt were actually to be made to generate all our power from solar panels they would in reality have to be dispersed across the country and would certainly not be all concentrated in this rectangle. 
Around 6% of the UK is urbanised i.e. around `r 0.06* 250 ` thousand square km, so there is at least the potential to use some of this space for solar. The area of solar capacity would be about `r perp<-round ( (10*10^9)/(6*10^7),1);perp` square meters per person or `r perh<-round ( (10*10^9)/(2*10^7),1);perh` square meters per household, which is much more than the available area on roofing and car parking spaces.  A solar panel installation on a south facing roof can generate most of a households electricity, however it cannot generate anything near the energy required to heat the house itself unless combined with a very efficient heat pump boiler.  
Some of the more optimistic claims about solar are very misleading. For example the following statement was made about 125 hectare site at Parley. "On a typical summer's day the Chapel Lane Solar Farm is now meeting the electricity needs of 60,000 households or three quarters of homes in Bournemouth." This is not really a fair statement at all, as the plant does not operate at this capacity year round. Electricity needs do not equate to more than 1/10 of total energy needs. A household uses between 10 and 20 thousand kWh per year, so the solar farm can in reality only cover the total annual energy consumption of around 12 thousand households at best. The population of Bournemouth and Poole combined is over465 thousand, so to cover their entire energy needs would use an area of around `r round(perp * 465 * 10^3/10^4,0) ` hectares i.e. `r round(perp * 465 * 10^3/10^4 /125,0) ` more installations of the size of Chapel Lane.  Nevertheless, although a large area,  it is around the same area as the urban sprawl of Bournemouth and Poole itself. So it is not infeasible to expect direct solar energy to make a substantial contribution to local energy needs even in the UK, if all the available opportunities are exploited. 

```{r}
data("parley")


mapviewOptions(basemaps =c("Esri.WorldImagery","OpenStreetMap"))
mapview(parley, alpha.regions = 0,alpha=0) %>% extras()
```


## Conclusions for the UK

In the case of the UK it is clearly going to be challenging to convert to using only direct solar. There are problems of available space and low levels of incoming radiation.  However solar is much more feasible as an option that intuition would suggest.  Productive crop land should certainly not be converted to solar farms. Unproductive areas of countryside such as lowland heaths are also much too valuable in terms of biodiversity and landscape values. However all south facing roofs should be fitted with panels and all options for using car parks, roads and other paved areas taken up. If this was done quickly it would be quite possible to produce all household electricity and to power all the country's electric vehicles using direct solar. Drax power station could be closed for good and the insanely inefficient burning of imported woodchips stopped.


## Carbon neutral by 2050?

If direct solar capture is a viable option, why does it still make up such a minute proportion of the current energy production? The reason in part is that panels have only just come down to a price that makes solar economically viable. At the time that David Mackay was writing his book prices were around four times more than they are now. PVAs are now available for as little as 200 pounds per square meter. As the demand grows efficiencies of scale will increase, lowering the price a little more. However if the demand rises too fast prices may also rise due to supply shortages. At present the growth in solar energy production at the global scale appears approximately exponential.

```{r}

global_energy %>% filter(name=="Solar") %>% group_by(Year) %>% filter(Year> 2000) %>% summarise(total=sum(value)/1000) -> sol

mod<- lm(data=sol,log10(total)~ Year)

ggplot(sol, aes(x=Year,y=total)) + geom_point() + ylab("Kwh * 10^12") + geom_line(aes(y=10^predict(mod))) + ggtitle("Global direct solar electricty production with fitted exponential growth curve")

```

The recent data points fall slightly below the fitted line, so at a global level the exponential model may be rather over optimistic. However the basic trend is more or less exponential. The key point about any exponential growth process is that you hardly notice that it is happening at first. If it can be extrapolated over longer periods of time then the results suddenly become very dramatic. Although true exponential growth in PVA production is unlikely if the cost of direct solar falls well below the cost of other forms of energy then the uptake will accelerate very rapidly.  This is now becoming a realistic proposition. 

```{r}
d<- data.frame(Year=2000:2020)
d$solar<-10^predict(mod,newdata=d)

ggplot(d, aes(x=Year,y=solar)) + geom_line() + ylab("Kwh * 10^12") + geom_point(data=sol, aes(x=Year,y=total))+ ggtitle("Extrapolated exponential growth in global solar energy production")
```

The process of exponential growth if it runs it course would lead to energy production from direct solar reaching the total current world energy production by 2032!



```{r}
d<- data.frame(Year=2000:2032)
d$solar<-10^predict(mod,newdata=d)

ggplot(d, aes(x=Year,y=solar)) + geom_line() + ylab("Kwh * 10^12") + geom_point(data=sol, aes(x=Year,y=total)) + geom_hline(yintercept = 160,col="red") + ggtitle("Extrapolated exponential growth in global solar energy production to 2032")
```


This is interesting to note,however it is clearly still totally unrealistic.  Exponential growth never continues unchecked. 

## Modelling increase in direct solar energy production as a logistic growth curve

The exponential model cannot be credible for any process that is naturally limited through some form of carrying capacity. The integrated form of a logistic equation can be used to represent the process.

$n_i= \frac{K}{1+\frac{K-n_1}{n_1}e^{-r*i}}$

In order to fit this model in R I used a very simple Bayesian approach in Jags. There is no need for too much statistical sophistication. The data only represent the very start of the process. The errors in any extrapolation will not be the result of a poorly fitting model. They are much more likely to arise through a misformed model. So keep the code simple. The priors for K can be a simple proposed upper and lower bound. 

```{r}

logistic_mod<-"
model {
 
  ## step through observations
  for (i in 1:N) {
     mu[i]<- K/(1+((K-n1)/n1)*exp(-r*i))
     n[i] ~ dnorm(mu[i],tau)
  }
  ## aux variables
  ## priors
  r ~ dunif(0,10) ## Keep an uninformative prior for r and let the data find the value
  K ~ dunif(lowK,highK)  ## Fix the final K to lie between two bounds
  tau~ dgamma(0.005,0.005)
}
"

```

The model can be fit quickly by running a single chain. There are no convergence problems.

```{r, message= FALSE, results='hide'}

dat<-list(
  N=length(sol$Year),
  n=sol$total,
   n1=sol$total[1],
  lowK=120,
  highK=160) 


mod <- jags.model(textConnection(logistic_mod), data = dat, n.chains = 1)
update(mod, 10000)

mod_sim <- coda.samples(model = mod, variable.names = c("r","K"), n.iter = 10000)
#summary(mod_sim)
#plot(mod_sim)
```


```{r}
ms <-ggs(mod_sim) 
ms %>% spread(Parameter, value) -> ms
#ms
    
i<-1:50

pred<-function(i, mt=ms, n1=sol$total[1]){
      pred<- ms$K/(1+((ms$K-n1)/n1)*exp(-ms$r*i))
      return(list(quantile(pred,c(0.025,0.5,0.975))))
}
    
pred_mod<-data.frame(i=i,do.call("rbind",sapply(i,pred)))
names(pred_mod)<-c("i","lwr","mid","upr")

ms <-ggs(mod_sim) 
ms %>% spread(Parameter, value) -> ms

ggplot(pred_mod,aes(x=i+2000,y=mid)) + geom_line() + geom_line(aes(y=lwr),col="blue") +  geom_line(aes(y=upr),col="red") + ylab("Kwh * 10¹²") + xlab("Year") + ggtitle("Extrapolated logistic growth in global solar energy production")
```

This model predicts a conversion to solar by around 2040. Once again, this is very unrealistic as the model assumes a complete refocussing of the entire energy industry towards making the transition. This is very unlikely to happen even if the market conditions for PVAs are highly favourable. Fossil fuel producers are large players their influence over market conditions is likely to slow down the transition.

## China

China is the great panda shaped elephant in the room. The internet is full of stories regarding China's vast solar farms. A large proportion of the world supply of PVA panels are manufactured in China. Unless China makes a rapid transition to clean energy there is little prospect of restricting climate change to within safe bounds.


![](panda.png)

### China's current energy production

The interesting point to note about China's current energy production is the heavy reliance on coal.  This leads to severe local pollution that has direct and noticeable impacts on human health and well being. 


```{r}
d<-energy_by_country

d %>% group_by(Year) %>% summarise(total=sum(value)/1000) -> ttl
d %>% filter(Year==2018) %>% filter(Entity=="China") %>% arrange(value) %>% 
  mutate(name = factor(name, name)) %>% mutate(percent=100*value/sum(value)) %>%
  
  
ggplot(aes(x=name, y=value, label=paste(round(percent,1), "%"))) + geom_col() +  geom_label() +coord_flip() + ylab("Terrawatt hours") +ggtitle("Energy production in China 2018")

```

The one positive impact of China's current reliance on highly polluting coal is that the negative effects are experienced by the whole urban population, including the politicians and decision makers. So, there is a very real stimulus to de-carbonise. Western China consists of very large areas of mainly barren and unpopulated desert with high solar potential. The Chinese government have made ambitious plans to substitute coal for solar and this has already resulted in a rapid expansion. 

```{r}
energy_by_country %>% filter(name=="Solar") %>% filter(Entity=="China")  %>% group_by(Year) %>% filter(Year> 2000) %>% summarise(total=sum(value)/1000) -> sol

mod<- lm(data=sol,log10(total)~ Year)
ggplot(sol, aes(x=Year,y=total)) + geom_point() + ylab("Kwh * 10^12") + geom_line(aes(y=10^predict(mod))) + ggtitle("China's direct solar electricty production with fitted exponential growth curve")


```

In the case of China the exponential growth curve actually falls below the data points. There are reports that the increase in capacity in China even took the government's central planners by surprise. If this process follows the logistic model there would be real grounds for optimism.


```{r, results='hide'}
dat<-list(
  N=length(sol$Year),
  n=sol$total,
   n1=sol$total[1],
  lowK=40,
  highK=60) 


mod <- jags.model(textConnection(logistic_mod), data = dat, n.chains = 1)
update(mod, 10000)

mod_sim <- coda.samples(model = mod, variable.names = c("r","K"), n.iter = 10000)

ms <-ggs(mod_sim) 
ms %>% spread(Parameter, value) -> ms
#ms
    
i<-1:50

pred<-function(i, mt=ms, n1=sol$total[1]){
      pred<- ms$K/(1+((ms$K-n1)/n1)*exp(-ms$r*i))
      return(list(quantile(pred,c(0.025,0.5,0.975))))
}
    
pred_mod<-data.frame(i=i,do.call("rbind",sapply(i,pred)))
names(pred_mod)<-c("i","lwr","mid","upr")

ms <-ggs(mod_sim) 
ms %>% spread(Parameter, value) -> ms


ggplot(pred_mod,aes(x=i+2000,y=mid)) + geom_line() + geom_line(aes(y=lwr),col="blue") +  geom_line(aes(y=upr),col="red") + ylab("Kwh * 10¹²") + xlab("Year") + ggtitle("Extrapolated logistic growth in China's solar energy production")
```

If the current trend in the Chinese solar expansion continues in the form of a exponential process mediated by the carrying capacity constraint (i.e. as a logistic growth curve) then China could be carbon neutral before the rest of the world! This is an astonishing, and frankly unbelievable, prediction. All predictions based on extrapolations of current trends are of necessity wrong. So this is not going to happen. However the fact that it is even thinkable is a cause for great optimism. 

## Could all this actually happen?

If the right mechanisms are put in place there are no physical or environmental constraints to preventing a transition to a world energy production model based around direct solar. This contrasts with almost all other potential "solutions" to the emissions problem. Hydro electric and bio-fuels can be  considered as sustainable energy sources, but both have potentially grave environmental consequences. The realisable potential of wind is  limited, even in the UK. Most of the world's continental land area is not suitable for wind power.  So direct PVA solar has to be considered as the only viable alternative to nuclear at a global scale.



The key to ensuring that the potential for exponential growth is realised must lie in price. If the price of a kWh of electricity is lower when generated by PVAs than by all other sources then the transition will probably happen. It may not be as rapid as the very optimistic models suggest, but there will be an inevitable impetus to move towards direct solar.

   
------------------------------------------

```{r}


d<-global_energy
d %>% filter(Year >1899) %>% filter(name %in% c("Crude.oil", "Natural.gas","Coal")) %>% group_by(Year) %>% summarise(fossil=sum(value), n=n()) -> glb

mod<- lm(data=glb,log10(fossil)~ Year)
ggplot(glb,aes(x=Year,y=fossil)) + geom_point() +  geom_line(aes(y=10^predict(mod)), col="red")


```



```{r}

d<-global_energy
d %>% filter(Year >1939) %>% filter(name %in% c("Crude.oil", "Natural.gas","Coal")) %>% group_by(Year) %>% summarise(fossil=sum(value), n=n()) -> glb

logistic_mod<-"
model {
 
  ## step through observations
  for (i in 2:N) {
     mu[i]<- K/(1+((K-n1)/n1)*exp(-r*year[i]))
     n[i] ~ dnorm(mu[i],tau)
  }
  ## aux variables
  ## priors
  r ~ dunif(0,100) ## Keep an uninformative prior for r and let the data find the value
  K ~ dunif(lowK,highK)  ## Fix the final K to lie between two bounds
  tau~ dgamma(0.005,0.005)
}
"

dat<-list(
  N=length(glb$Year),
  year= glb$Year-1939,
  n=glb$fossil,
  n1=glb$fossil[1],
  lowK=120000,
  highK=200000) 


mod <- jags.model(textConnection(logistic_mod), data = dat, n.chains = 1)
update(mod, 10000)

mod_sim <- coda.samples(model = mod, variable.names = c("r","K"), n.iter = 10000)

ms <-ggs(mod_sim) 
ms %>% spread(Parameter, value) -> ms
    
year<- 1:120

pred<-function(year, mt=ms, n1=glb$fossil[1]){
      pred<- ms$K/(1+((ms$K-n1)/n1)*exp(-ms$r*year))
      return(list(quantile(pred,c(0.025,0.5,0.975))))
}
    
pred_mod<-data.frame(year=year+1939,do.call("rbind",sapply(year,pred)))
names(pred_mod)<-c("year","lwr","mid","upr")


ggplot(data=pred_mod,aes(x=year,y=mid)) + geom_point(data=glb,aes(x=Year,y=fossil)) +  geom_line(aes(y=mid), col="black") + geom_line(aes(y=lwr), col="red")  + geom_line(aes(y=upr), col="red")
```





```{r}


energy_by_country %>% filter(name=="Coal.") %>% filter(Entity=="China")  %>% group_by(Year) %>% filter(Year> 2000) %>% summarise(total=sum(value)/1000) -> sol

mod<- lm(data=sol,log10(total)~ Year)
ggplot(sol, aes(x=Year,y=total)) + geom_point() + ylab("Kwh * 10^12") + geom_smooth(col="red", se=FALSE) + ggtitle("China's coal consumption")
```

