# Right-to-Left Shunt

#### Right-to-left shunt fraction

Estimated using an arterial blood gas measurement after inspiring 100% oxygen for about 20 minutes.

library (ggplot2)
library(reshape2) #to melt
library(plotly)

#### Main function

Calculates the $$\frac{Q_s}{Q_t}$$ shunt fraction

rl.shunt <- function (po2, pco2, temp, altitude){
if (missing(temp)) {temp <- 37}
if (missing(altitude)) {altitude <- 1300} #MCS altitude
p.water <- 47 * exp((temp-37)/18.4)
altitude <- altitude * 0.333
p.atm <- 760 * exp(-altitude/7000)
pA.o2 <- p.atm - p.water - pco2
aag <- pA.o2 - po2
# Qs/Qt = 100 * ( .0031 * AaG) / ((.0031 * AaG) + 5)
return(100 * ( .0031 * aag) / ((.0031 * aag) + 5))
}

rl.shunt(205, 22, 37, 1300)
## [1] 21.44926
rl.shunt(205, 22) #OK to drop temp and altitude, short form works 
## [1] 21.44926
rl.shunt(100, 22) #25.4
## [1] 25.27066
rl.shunt(460, 22) #10
## [1] 10.31088
rl.shunt(560, 22) #5
## [1] 5.029849

#### Heat map

o2range <- seq(200,600,20)
co2range <- seq(20, 40, 1)
sm <- data.frame(cbind (sapply(co2range, rl.shunt, po2 = o2range)))
rownames(sm) <- paste0(o2range)   #"pO2=",
colnames(sm) <- paste0(co2range)  #"pCO2=",
m <- as.matrix(sm)
df <- melt(m)    #melting a dataframe only returns colnames, so need a matrix
colnames(df) <- c("pO2", "pCO2", "value")
head(df)
##   pO2 pCO2    value
## 1 200   20 21.71613
## 2 220   20 20.94877
## 3 240   20 20.16621
## 4 260   20 19.36800
## 5 280   20 18.55367
## 6 300   20 17.72272
g <- ggplot(df, aes(x = pCO2, y = pO2, fill = value)) +
scale_fill_gradient(high = "firebrick", low = "darkgreen")
g +  geom_contour(aes(z=value),
bins = 16,
binwidth=1,
position = "identity")

g <- g +  geom_tile(color = "gray",
lwd = .2,
linetype = 1)

#  guides(fill = guide_colourbar(title = "Shunt fraction")) #legend title
g

ggplotly(g, tooltip= "value")

# save the widget
# library(htmlwidgets)
# saveWidget(pp, file=paste0( getwd(), "/HtmlWidget/ggplotlyHeatmap.html"))

#### Changes in pCO2 do not seem to influence the calculations.

Or at least thatâ€™s what the heat map suggests. Letâ€™s confirm

shunt.df <- data.frame(rl.shunt(22, seq(200,600,10)))
ggplot(data.frame(po2=seq(50, 600, 10)), aes(x=po2)) +
stat_function(fun = rl.shunt,
args=list(pco2=20, temp=37, altitude=1300),
color="firebrick", size=1) +
stat_function(fun = rl.shunt,
args=list(pco2=30, temp=37, altitude=1300),
color="steelblue", size=1) +
stat_function(fun = rl.shunt,
args=list(pco2=40, temp=37, altitude=1300),
color="orange", size=1) +
scale_y_continuous(limits = c(0, 30), breaks = seq(0,30,2)) +
scale_x_continuous(limits = c(50,600), breaks = seq(50, 600, 50)) +
labs(y="Shunt fraction [%]")