Water guide: Difference between revisions

From Opasnet
Jump to navigation Jump to search
mNo edit summary
 
(110 intermediate revisions by 3 users not shown)
Line 1: Line 1:
[[op_fi:Vesiopas]]
[[op_fi:Vesiopas]]
'''Water guide''' is a model for calculating health risks of contaminated raw water in a waterworks. There is a [[:op_fi:Vesiopas|Finnish version]] that is more flexible about the input values.
[[Category:Drinking water]]
[[Category:Open model]]
[[Category:Model]]
[[Category:Water guide]]
[[Category:Research project]]
[[Category:Contains R code]]
[[File:Water risk assessment.png|thumb|500px]]


<rcode live=1
 
name="answer"
'''Water guide - An assessment of the health impacts of water quality''' addresses the potential microbiological health risks of drinking water. These microbiological risks are due to the contamination of raw water with microbes that cause potential health problems for people using tap water, as well as the efficiency of drinking water treatment, which can be insufficient for removing harmful microbes from drinking water. The assessment will be used to determine, how high the health risk is from certain microbes in raw water. The assessment is based on a mathematical Water guide -model, which can be found below.
 
== Question ==
 
How to assess the microbiological risks of drinking water as well as their health effects? Information of water treatment plants must be possible to use as raw data.
 
==Answer==
 
<rcode graphics=1
name="answer1"
label="Run model"
variables="
variables="
name:RaakaLuokka|description:Classification of raw water|type:selection|
name:rawclass|description:Classification of raw water|type:selection|
options:
options:
'Pintavesi - Vähäinen kuormitus';Surface water - low contamination;
'Surface water - low contamination';Surface water - low contamination;
'Pintavesi - Keskisuuri kuormitus';Surface water - medium contamination;
'Surface water - medium contamination';Surface water - medium contamination;
'Pintavesi - Suuri kuormitus';Surface water - high contamination;
'Surface water - high contamination';Surface water - high contamination;
'Pohjavesi - Puhdas';Ground water - clean;
'Ground water - clean';Ground water - clean;
'Pohjavesi - Pintavesikuormitus';Gound water - surface water contamination|
'Ground water - surface water contamination';Ground water - surface water contamination;
        'Hand input';I will give microbe concentrations of raw water by hand|
        default:'Hand input'|


category:Situation|
category:Situation|


name:Vaestonkoko|default:10000|description:Size of the exposed population|
name:total_population|default:10000|description:Size of the exposed population|
 
        name:rawconsumption|default:0.25|description:The amount (in liters) of unboiled tap water consumed per person per day|
 
name:Campylo|description:Campylobacter concentration (microbes/l)|default:0|
category:Microbe concentrations of raw water|
category_conditions:rawclass;'User'|
name:E.coli|description:''E.coli'' O157:H7 concentration (microbes/l)|default:0|
name:Rota|description:Rotavirus concentration (microbes/l)|default:0|
name:Noro|description:Norovirus concentration (microbes/l)|default:0|
        name:Sapo|description:Sapovirus concentration (microbes/l)|default:0|
name:Crypto|description:Cryptosporidium concentration (microbes/l)|default:0|
name:Giardia|description:Giardia concentration (microbes/l)|default:0|
name:Puhdistus|description:Water cleaning methods in use|type:checkbox|
name:treatment|description:Water cleaning methods in use|type:checkbox|
options:
options:
1;Traditional cleaning;
'Coagulation and flotation';Coagulation and flotation;
2;Well working cleaning;
'Slow sand filtration';Slow sand filtration;
3;Enhanced cleaning;
'Limestone filtration';Limestone filtration;
4;Slow sand filtration;
'Active carbon filtration';Active carbon filtration|
5;Lime stone filtration;
6;Active carbon filtration;
7;UV filtration;
8;Ozone treatment|
default:4;5|
category:Water cleaning: Cleaning process and chlorination|
category:Water cleaning: Cleaning process and chlorination|
name:IKlooriAnnos|default:0|description:Chlorine dose (mg/l)
name:chlorinedose|default:0|description:Chlorine dose (mg/l)|
        name:ozonedose|default:0|description:Ozone dose (mg/l)|
        name:uvdose|default:0|description:UV dose (mW/cm^2)|
        name:uvtime|default:0|description:UV time (s)
"
"
>
>
# This is code Op_en6177/ on page [[Water guide]]
library(OpasnetUtils)
library(OpasnetUtils)
library(reshape2)
library(ggplot2)


# Nämä arvot kysytään käyttäjältä täysverisessä mallissa
objects.latest("Op_en6177", code_name="waterguide") # [[Water guide]] fetch the whole model
Kampylo <- 'Luokituksen mukainen'
 
Ecoli <- 'Luokituksen mukainen'
# Create ovariables from user input data
Rota <- 'Luokituksen mukainen'
RawClass <- Ovariable("RawClass", data=data.frame(RawWaterClass = rawclass, Result=1))
Noro <- 'Luokituksen mukainen'
Treatment <- Ovariable("Treatment", data=data.frame(TreatmentMethod=c(treatment, "None"), Result=1))
Crypto <- 'Luokituksen mukainen'
ChlorineDose <- Ovariable("ChlorineDose", data=data.frame(Result=chlorinedose))
Giardia <- 'Luokituksen mukainen'
UVdose <- Ovariable("UVdose", data=data.frame(Result=uvdose))
Kaupunki <- 'Custom'
UVtime <- Ovariable("UVtime", data=data.frame(Result=uvtime))
IVedenkulutus <- 1153
OzoneDose <- Ovariable("OzoneDose", data=data.frame(Result=ozonedose))
RawConsumption <- Ovariable("RawConsumption", data=data.frame(Result=rawconsumption))
IRaakaPitoisuus <- list(Kampylo, Ecoli, Rota, Noro, Crypto, Giardia)
# divide the given population size to different age groups based on age distribution of all of Finland
population <- Ovariable("population",
  dependencies=data.frame(
    Name=c("total_population")
    ),
  formula=function (...) {
    population2 <- Ovariable(
      "population2",
      ddata="Op_en2949", subset="Population"
    )
    population2 <- EvalOutput(population2)
    population <- population2/oapply(population2, cols = "Age", FUN=sum) * total_population
    return(population)
  }
)


# Vedenkulutus


if (!is.na(suppressWarnings(as.numeric(IVedenkulutus)))) {
# if the raw concentrations were chosen to be given by hand, put them into an ovariable
InpVedenkulutus = data.frame(VedenkulutusResult = IVedenkulutus)
# if some raw water class was chosen, this isn't done, and instead the data for microbe concentrations for that class is used
InpVedenkulutus = Ovariable("Vedenkulutus", output = InpVedenkulutus)
if (rawclass == "Hand input") {
  RawConcentration <- Ovariable(
    "RawConcentration",
    data=data.frame(
      Pathogen=c(
        "campylobacter",
        "E.coli O157:H7",
        "rotavirus",
        "norovirus",
        "sapovirus",
        "cryptosporidium",
        "giardia"),
      Result=c(
        Campylo,
        E.coli,
        Rota,
        Noro,
        Sapo,
        Crypto,
        Giardia)
    )
  )
}
}


# Patogeenien pitoisuudet
BoDattr <- EvalOutput(BoDattr, verbose=FALSE, forceEval=TRUE)
# calculate the number of cases
cases <- BoDattr/case_burden
 
cat("Pathogen concentrations in the raw water, microbes/l.\n")
oprint(summary(RawConcentration))
cat("Exposure to people, number of microbes ingested in a day with drinking water.\n")
oprint(summary(exposure))
cat("Disease burden, DALYs caused per day (DALY = disability adjusted life years) \n")
oprint(summary(BoDattr, marginals=c("Response","Exposure_agent")))
cat("Number of illness cases caused daily by pathogens in drinking water. \n")
oprint(summary(cases, marginals=c("Response","Exposure_agent")))
 
cat("exposure \n")
colnames(exposure@output)[exposure@marginal]
cat("MicrobeLogDecrease \n")
colnames(MicrobeLogDecrease@output)[MicrobeLogDecrease@marginal]
cat("OzoneEfficiency \n")
colnames(OzoneEfficiency@output)[OzoneEfficiency@marginal]
 
label <- oapply(BoDattr, c("Exposure_agent", "Iter"), sum)
label <- oapply(unkeep(label, sources=TRUE), NULL, mean, "Iter")@output$BoDattrResult
ggplot(
  oapply(unkeep(BoDattr, sources=TRUE), NULL, mean, "Iter")@output,
  aes(x=Exposure_agent, weight=BoDattrResult, fill=Response)) +
    geom_bar() +
    coord_flip() + theme_gray(base_size=24)+
    labs(
    title="Disease burden of waterborne microbes",
    subtitle=paste("in a population of", format(total_population, scientific = F)),
    y = "Disease burden (DALY/day)",
    x = "Pathogen") +
  annotate("text", x = c(1:6), y = label, label = round(label,2), size=6)
 
label2 <- oapply(cases, c("Exposure_agent", "Iter"), sum)
label2 <- oapply(unkeep(label2, sources=TRUE), NULL, mean, "Iter")@output$Result
ggplot(
  oapply(unkeep(cases, sources=TRUE), NULL, mean, "Iter")@output,
  aes(x=Exposure_agent, weight=Result, fill=Response)) +
  geom_bar() +
  coord_flip() +
  theme_gray(base_size=24)+
  labs(
    title="Ilnesses caused by waterborne microbes",
    subtitle=paste("in a population of", format(total_population, scientific = F)),
    y = "Cases of illness",
    x = "Pathogen") +
  annotate("text", x = c(1:6), y = label2, label = round(label2,2), label=6)
 
# cases as percent of beachgoers
cases_percent <- cases*100/total_population
label3 <- oapply(cases_percent, c("Exposure_agent", "Iter"), sum)
label3 <- oapply(unkeep(label3, sources=TRUE), NULL, mean, "Iter")@output$Result
ggplot(
  oapply(unkeep(cases_percent, sources=TRUE), NULL, mean, "Iter")@output,
  aes(x=Exposure_agent, weight=Result, fill=Response)) +
  geom_bar() +
  coord_flip() +
  theme_gray(base_size=24)+
  labs(
    title="Proportion of the population that gets ill daily",
    subtitle=paste("in a population of", format(total_population, scientific = F)),
    y = "Proportion of population (%)",
    x = "Pathogen") +
  annotate("text", x = c(1:6), y = label3, label = round(label3,2), label=6)
 
cat(paste("In Finland, the illness cases due to drinking water should be on average less than 0.01% of the population per year, or 1 case for every 10 000 people. The WHO guidelines give a target of less than 10^-6 DALY per person per year, or 0.01 DALYs per 10 000 people. The graphs here show the case burdens and numbers of cases for each of the pathogens that are caused in one day in a population of", total_population, ", with the average daily cold water consumption of", rawconsumption, "liters per person. \n"))
 
</rcode>
The result page opens in a new tab by pressing the Run model -box. It will take approximately 40 seconds for the model to run, after which the results will appear on the result page.
 
=== User instructions for the Water guide -model ===
 
{{greenbox|
 
'''1. Choose classification of raw water'''
*Ground water - Clean: clean ground water
*Ground water - Surface water load: f.ex. shore infiltration
*Surface water - Low load: relatively clean surface water
*Surface water - Medium load: f.ex. low waste water load
*Surface water - High load: f.ex. waste water load
 
'''OR'''
 
Choose 'I will determine microbe concentration by hand'. Write pathogen concentrations in their respective boxes.
 
'''2. State the concumption of drinking water''' per 24 h in liters per day per person (default 1.153 l/d).
 
'''3. State the population size of target area.''' (default 100000)
 
'''4. Choose treatment processes used.''' Obs! You can choose multiple options. If none of the first six treatment processes are used, choose "None of the above cleaning methods". If neither UV nor ozone is used, choose "None of the above disinfection methods".
 
'''5. Choose whether chlorination is used or not''' by giving the chlorine dose used (mg/l). If there is no chlorination, the dose will be 0 mg/l (default 0 mg/l). The model only calculates the effect of chlorine on the water in treatment plants, and ignores any further cleansing effects residual chlorine may have after the water moves onward to the pipe network.


objects.latest("Op_fi2655", "muuttuja") # RaakaPitoisuus, customoitia varten
'''6. You can see the results in a new tab by pressing 'Run model'''' This opens a new tab, in which the results will appear after the model is done running. This takes approximately 45 seconds.
}}


RaakaPitoisuus <- EvalOutput(RaakaPitoisuus)
== Rationale ==


temp <- RaakaPitoisuus@output
[[File:Water guide.png|750px]]


temp <- temp[as.character(temp$Raakavesilähde) == RaakaLuokka, ]
:''The model has been translated from Analytica to R. You can find the original model here (page in Finnish, link to the model code at the top): [[:op_fi:Tiedosto:Vesiopas.ANA]]. If the user does not give concentrations for the pathogens, the values on page [[Pathogen concentrations in raw water]] will be used.


temp <- merge(
Health-based quality requirements and recommendations have been implanted on the quality of household water. In Finland, the ministry of social affairs and health is responsible for the legislation of the quality, and monitoring it is the responsibility of municipal health protection officials. Upholding and developing good water quality require high-standard research and cooperation between different parties. Ground waters and artificial ground waters are usually not disinfected. The chemicals and microbes in raw water and byproducts of disinfection produced in household water production can present health risks to the people using the household water. Water leaving the treatment plant can stay in the pipes for a long time. If the circumstances are favourable for microbial growth, the water can become low in quality and even detrimental to health while in the pipe network.
temp,  
 
data.frame(
Household water is produced from either ground or surface water. The problems of these types of waters as raw water are different. Using surface water always requires establishing an actual treatment plant and the associated knowledge, skills, technologies and educated monitoring personnel. Ground water on the other hand doesn't require very complex treatment, so not many treatment plant personnel are needed, and there is less monitoring. Additionally today there are many treatment plants that produce artificial ground water. The qualities of artificial ground water can be similar to good ground waters, but the quality of the water is often only be equal to medium quality surface water.
Patogeeni = c("Kampylobakteeri","E.coli O157:H7","Rotavirus","Norovirus","Cryptosporidium","Giardia"),  
 
TempResult = suppressWarnings(as.numeric(IRaakaPitoisuus))
Treatment of ground water usually includes increasing the pH and and hardness of water. This can be done using different techniques, of which the use of calcium hydroxide and carbon dioxide to regulate pH are the most common. Sometimes also precipitation of iron or manganese is required using strong oxidisers such as permanganate or chlorine. Low quality ground water is also disinfected.
)
 
In order to make surface water drinkable, it has to be heavily treated. The hardest thing is to precipitate the humus. This is done by using not only different precipitation chemicals, also for example adjust pH and breaking down the humus with strong oxidisers such as ozone. On top of that, the precipitated chemicals (such as salts of aluminium and iron) need to be removed and water hardness raised so that the pipelines don't disintegrate over time. Also, the population has to be protected from the [https://en.wikipedia.org/wiki/Microorganism microbes] always present in surface waters, so the water needs to be disinfected to remove pathogens.
 
The quality of water is also affected by the condition of the pipelines and the water spends in them. If there is a lot of coagulation in the pipelines, these dregs include not only different inorganic compounds but also a large amout of bacterial mass. The coagulates in the pipelines and their qualities have started to be researched in Finland only recently.
 
The purpose of risk assessment is to produce information of the true size of the risk for decision-making. Risk assessment is a scientific process in which experts hold a key role. Because there are any kinds of risks to study, risk assessment processes can be very different. In environmental health risk assessment consists of four steps:
# Identifying the danger (does the variable researched pose a danger to humans?)
# Assessing the exposure-response function (how big a dose results in how big a response?)
# Assessing exposure (how much are humans exposed?)
# Characterising the risk (how high is the health risk?)<ref>http://wanda.uef.fi/tkk/avoin/ymp_terveys/</ref>
 
All water treatment plants should periodically do risk assessment on on the household water they produce. It is done to identify actions to be taken in different crisis situations and prepare plans for different problematic situations and possible damage. Different treatment plants and for example vacation centers need different kinds of plans and implementations.
 
=== Dependencies ===
 
{| {{prettytable}}
|+ '''Pages containing the data and codes used by the model
! Page !! What data or code the page has !! What is it used for !! Other observations
|----
| Op_en2949 [[Population of Finland]] || Data on the age distribution of Finns || Age distribution is used, because susceptibility to diseases and their severity changes with age. The burden of disease and cases of illness are calculated for each age group, then summed. ||
|----
| Op_en7956 [[Drinking water chlorination efficiency]] || Log-decrease in pathogens due to chlorination, with different doses || The code on this page uses the data on the page and user-given dose for chlorine to calculate the case-specific decrease in pathogens due to chlorination. This is summed with log-decrease of other treatment and disinfection methods to produce the total log-decrease in pathogens from water treatment. || The model only takes into account any decrease in pathogens that happens in water treatment plants. Any further effect residual chlorine has after it enters the pipes is not included.
|----
| Op_en7955 [[Drinking water disinfection efficiency]] || Log-decreases of pathogens due to ozonization and UV || If the user has chosen one or both of these disinfection methods, the decrease from the chosen one(s) is summed with the decrease due to chlorination and other treatment methods to produce the total log-decrease in pathogens from water treatment. || Currently the qualities of water, such as turbidity, are not taken into account in the efficiency of disinfection methods. The dose for both methods is also set.
|----
| Op_en7954; [[Drinking water treatment efficiency]] || Log-decreases of pathogens due to different treatment methods. These methods are traditional cleaning, well working cleaning, enhanced cleaning, slow sand filtration, limestone filtration and active carbon filtration. || If the user has chosen one of multiple of these treatment methods, the decrease of pathogens they produce is summed with the decreases due to chlorination and other disinfection methods to produce the total log-decrease in pathogens from water treatment. ||
|----
| Op_en7953 [[Pathogen concentrations in raw water]] || The concentrations of pathogens of different raw water classes || If the user has chosen one of the raw water classes, the amounts of pathogens in that class and the total log-decrease of pathogens from treatment are used to calculate the amount of pathogens left in drinking water. If the user has given pathogen concentrations by hand, those values are used instead of the data on this page. ||
|----
| Op_en7947 [[Case burden of waterborne microbes]] || Case burdens of different pathogens, or how severe and long-lasting the diseases caused by them are || This data is used to calculate the health detriments caused by the pathogens in drinking water. ||
|----
| Op_en7957 [[Health impacts of waterborne microbes]] || Doesn't contain data, only code || These codes use water consumption given by the user, total decrease in pathogens and the pathogen concentrations in raw water to calculate the exposure to pathogens experienced by one individual, or how many of each pathogen an individual swallows daily with drinking water. ||
|----
| Op_en7948 [[ERF of waterborne microbes]] || Describes the exposure-response functions for the pathogens || These functions tell, how likely an individual is to get sick with different exposures. This and the exposure are used to estimate the cases of illness. ||
|----
| Op_en2261 [[HIA]] || Code that combines all of the above || The code on the page uses exposure, exposure-response functions and the case burdens to calculate the total burdens caused by pathogens in drinking water. From here it is also possible to calculate the number of people getting ill from drinking water. These are the final results of the model. ||
|}
 
 
Table of decisions used in drawing plotly graphs.
 
<t2b name="Decisions" index="Decision,Option,Variable,Cell,Change,Description" unit="-">
Adjust|Ground - none|RawConcentration|RawWaterClass: Ground water - surface water contamination|Remove||
Adjust|Ground - none|RawConcentration||||
</t2b>
Well, this doesn't work at all.
 
=== Calculations ===
 
==== Initiate model ====
 
<rcode name="waterguide" label="Initiate Water guide model" embed=0 graphics=1>
# This is code Op_en6177/waterguide on page [[Water guide]]
library(OpasnetUtils)
library(ggplot2)
 
openv.setN(1)
 
# Create ovariables from user input data
RawClass <- Ovariable("RawClass", data=data.frame(RawWaterClass = 'Surface water - low contamination', Result=1))
population <- Ovariable("population", data=data.frame(Result=10000))
Treatment <- Ovariable("Treatment", data=data.frame(TreatmentMethod=c('None'), Result=1))
ChlorineDose <- Ovariable("ChlorineDose", data=data.frame(Result=0))
 
objects.latest("Op_en7957", code_name="exposure")
#exposure <- EvalOutput(exposure)
 
objects.latest("Op_en7947", code_name="caseburden")
#case_burden <- EvalOutput(case_burden)
 
incidence <- 1 # Number per 1py # Potentially everyone can get the disease. PAF is the fraction of this that actually occurs
 
ERF <- Ovariable(
  "ERF",
  dependencies=data.frame(Name="ERF_micr",Ident="Op_en7948/ERF_micr2"),
  formula = function(...) return(ERF_micr)
)
)
temp$RaakaPitoisuusResult <- ifelse(
 
is.na(temp$TempResult),  
objects.latest("Op_en2261", code_name="BoDattr2") # [[Health impact assessment]] BoDattr
temp$RaakaPitoisuusResult,
BoDattr <- EvalOutput(BoDattr, verbose=TRUE)
temp$TempResult
 
oprint(summary(BoDattr, marginals=c("Response","Exposure_agent")))
 
objects.store(list=setdiff(ls(), "wiki_username"))
cat("The whole model stored (", setdiff(ls(), "wiki_username"), ").\n")
 
ggplot(
  oapply(unkeep(BoDattr, sources=TRUE), NULL, mean, "Iter")@output,
  aes(x=Exposure_agent, weight=BoDattrResult, fill=Response)) +
  geom_bar() +
  coord_flip() +
  labs(
    title="Disease burden of waterborne microbes",
    subtitle=paste("in a population of", sum(result(population))),
    y = "Disease burden (DALY/incident)"
  )
 
if(FALSE) {
  ######################## Diagnostics
 
  objects.latest("Op_en6007", code_name="diagnostics")
  oprint(showLoctable())
  oprint(showind())
 
  ################ Insight network
 
  gr <- scrape(type="assessment")
  objects.latest("Op_en3861", "makeGraph") # [[Insight network]]
  gr <- makeGraph(gr)
  #export_graph(gr, "ruori.svg")
  #render_graph(gr)
}
</rcode>
 
==== Plotly test ====
 
<rcode label="Code does not work in Opasnet">
library(OpasnetUtils)
library(ggplot2)
library(plotly)
 
 
objects.latest("Op_en6177", code_name="waterguide") # [[Water guide]] fetch the whole model
 
total_population <- 10000
 
# Create ovariables from user input data
RawClass <- Ovariable("RawClass", data=data.frame(RawWaterClass = "Surface water - high contamination", Result=1))
Treatment <- Ovariable("Treatment", data=data.frame(TreatmentMethod=c("None"), Result=1))
RawConsumption <- Ovariable("RawConsumption", data=data.frame(Result=0.8))
# divide the given population size to different age groups based on age distribution of all of Finland
population <- Ovariable("population",
                        dependencies=data.frame(
                          Name=c("total_population")
                        ),
                        formula=function (...) {
                          population2 <- Ovariable(
                            "population2",
                            ddata="Op_en2949", subset="Population"
                          )
                          population2 <- EvalOutput(population2)
                          population <- population2/oapply(population2, cols = "Age", FUN=sum) * total_population
                          return(population)
                        }
)
)
RaakaPitoisuus@output <- temp[, !colnames(temp) %in% c("TempResult", "Raakavesilähde")]


temp <- rep(FALSE,9) # vaihtoehdot + klooraus joka on mallin rakenteesta johtuen aina epätosi
temp[Puhdistus] <- TRUE
Puhdistus <- temp


if (!is.na(suppressWarnings(as.numeric(IKlooriAnnos)))) if (IKlooriAnnos > 0) {
 
InpKlooriAnnos <- Ovariable("KlooriAnnos", output = data.frame(KlooriAnnosResult = IKlooriAnnos))
# create data
aval <- list()
for(step in seq(0, 1, 0.1)){
  ChlorineDose <- Ovariable("ChlorineDose", data=data.frame(Result=step))
  BoDattr <- EvalOutput(BoDattr, verbose=FALSE, forceEval=TRUE)
  plotdata <- oapply(unkeep(BoDattr, sources=TRUE), NULL, mean, "Iter")
  plotdata <- oapply(plotdata, FUN=sum, cols="Age")
  # creates a loist of lists, each list containing the data for the grapsh with one of the chlorine doses
  aval[[((step+0.1)*10)]] <-list(visible = FALSE,
                      name = paste0('dose = ', step),
                      x=plotdata@output$BoDattrResult,
                      y=plotdata@output$Exposure_agent,
                      response=plotdata@output$Response)
}
}
aval[1][[1]]$visible = TRUE # the figure with clorine dose 0 is set to visible
# this bit is to move the first dose to be the last, because the figure is for some reason
# draws the last to be the first, and I don't understand, but like this they're in the right
# order in the picture
aval <- aval[c(2:length(aval), 1)]
# create steps and plot all traces
steps_micro <- list()
p <- plot_ly(type = 'bar', orientation = "h")
for (i in 1:length(aval)) {
  p <- add_trace(p, # add bars to bar graph p
                x=aval[i][[1]]$x, # x (DALYs) on x
                y=aval[i][[1]]$y, # y (exposure agent) on y
                visible = aval[i][[1]]$visible, # visibility was set earlier
                text = aval[i][[1]]$response,
                type="bar",
                hoverinfo = "text+x", # what the info shown when mouse on top of it says
                orientation="h")
 
  step <- list(args = list('visible', rep(FALSE, length(aval))), # set all steps to not visible
              method = 'restyle',
              label= (i-1)/10) # Sets the text label to appear on the slider
  step$args[[2]][i] = TRUE  # set data on i step to be visible when step i is chosen
  steps_micro[[i]] = step # make a list with all the steps
# add slider control to plot
p <- p %>%
  layout(sliders = list(list(active = 0, #Determines which button (by index starting from 0) is considered active.
                            currentvalue = list(prefix = "Chlorine dose (mg/l): "), # the text under the graph that tells what the slider values mean
                            steps = steps_micro)),
        barmode = 'stack', # stacked plot instead of each disease its own bar
        title = paste('Burdens of disease of drinking water in a population of', total_population),
        xaxis = list(title ="DALY"),
        yaxis = list(title =""))
p
</rcode>
==== Another plotly test ====
<rcode label="Run on own computer">
library(OpasnetUtils)
library(ggplot2)
library(plotly)
objects.latest("Op_en6177", code_name="waterguide") # [[Water guide]] fetch the whole model


# Käsitellään puhdistusmenetelmät käsin tätä mallia varten
total_population <- 10000


riippuvuudet <- data.frame(
# Create ovariables from user input data
Name = c("RaakaPitoisuus", "Desinfiointi", "PuhdistusTeho", "KloorausTeho"),
RawClass <- Ovariable("RawClass", data=data.frame(RawWaterClass = "Surface water - high contamination", Result=1))
Ident = c("Op_fi2655/muuttuja", "Op_fi2993/muuttuja", "Op_fi2656/muuttuja", "Op_fi2667/tehokkuus")
)


objects.latest("Op_fi2993", "muuttuja") # Desinfiointi
Treatment <- Ovariable("Treatment", data=data.frame(TreatmentMethod=c("None"), Result=1))


objects.latest("Op_fi2656", "muuttuja") # PuhdistusTeho
ChlorineDose <- Ovariable("ChlorineDose", data=data.frame(Chlorine=c("None","Low","High"), Result=c(0, 0.5, 1)))


PuhdistusTeho <- EvalOutput(PuhdistusTeho)
RawConsumption <- Ovariable("RawConsumption", data=data.frame(Result=0.8))
Desinfiointi <- EvalOutput(Desinfiointi)


Puhdistus <- data.frame(
# divide the given population size to different age groups based on age distribution of all of Finland
Käytössä = Puhdistus,
population <- Ovariable(
Puhdistusmenetelmä = c("Perinteinen puhdistus", "Hyvin toimva puhdistus",  
  "population",
"Tehostettu puhdistus" ,"Hidas hiekkasuodatus", "Kalkkikivisuodatus",  
  dependencies=data.frame(
"Aktiivihiilisuodatus", "UV", "Otsonointi", "Klooraus")
    Name=c("total_population")
  ),
  formula=function (...) {
    population2 <- Ovariable(
      "population2",
      ddata="Op_en2949", subset="Population"
    )
    population2 <- EvalOutput(population2)
    population <- population2/oapply(population2, cols = "Age", FUN=sum) * total_population
    return(population)
  }
)
)


PuhdistusTeho@output <- merge(PuhdistusTeho@output, Puhdistus[1:6,]) # Vedenkäsittelymenetelmät
BoDattr <- EvalOutput(BoDattr)#, verbose=FALSE), forceEval=TRUE)


Desinfiointi@output <- merge(Desinfiointi@output, Puhdistus[7:9,]) # Desinfiointimenetelmät
plotdata <- oapply(unkeep(BoDattr, sources=TRUE), NULL, mean, "Iter")
plotdata <- oapply(plotdata, FUN=sum, cols="Age")


PuhdistusTeho@output$PuhdistusTehoResult <- ifelse(
PuhdistusTeho@output$Käytössä,
PuhdistusTeho@output$PuhdistusTehoResult,
0
)
Desinfiointi@output$DesinfiointiResult <- ifelse(
Desinfiointi@output$Käytössä,
Desinfiointi@output$DesinfiointiResult,
0
)


# Poistetaan "Käytössä" kolumin
plot_ly(plotdata@output, x = ~BoDattrResult, y = ~Exposure_agent,
PuhdistusTeho@output <- PuhdistusTeho@output[, !colnames(PuhdistusTeho@output) == "Käytössä"]
        type = 'bar',
Desinfiointi@output <- Desinfiointi@output[, !colnames(Desinfiointi@output) == "Käytössä"]
        orientation = "h", # bars vertically or horizontally
        color = ~Response, # what to use as a basis for colored groups
        colors=c("sandybrown", "gray50", "darkorchid1", "aquamarine1", "firebrick1",
                "cornflowerblue", "gold1", "chocolate3")) %>% # the colors used
  # in the order that the diseases appear in the table. not level order. table order.
  layout(barmode = 'stack', # stacked plot instead of each disease its own bar
        title = paste('Burdens of disease of drinking water in a population of', total_population),
        xaxis = list(title ="DALY"),
        yaxis = list(title =""))


objects.latest("Op_fi1759", "muuttuja") # Vaste


Vaste <- EvalOutput(Vaste, substitute = TRUE)
steps <- list()
pl <- plot_ly()
for(i in levels(ChlorineDose$Chlorine)) { # add data for each slider step (=each chlorine level)
  tmp <- plotdata[plotdata$Chlorine==i , ] # Slice rows for each chlorine level at a time
  pl <- add_trace( # Add a separate dataset for each step
    pl,
    x = tmp$Exposure_agent,
    y = tmp$BoDattrResult,
    name = tmp$Response,
    type = "bar",
    #    orientation = "h",
    visible = i==levels(ChlorineDose$Chlorine)[1] # Make only the first dataset visible by default SOMETHING STRANGE HERE
   
  )
  step <- list(
    args = list('visible', i==levels(ChlorineDose$Chlorine)), # Make all datasets invisible in this step except this one
    label = i,
    value = match(i,levels(ChlorineDose$Chlorine)),
    method = 'restyle' # I suppose this means that the graph is retyled when the step changes
  )
  steps[[match(i,levels(ChlorineDose$Chlorine))]] <- step
}


#################################################################################
pl %>% layout(
  sliders = list(list(
    active = 0, # Make the first step active by default (counting starts from 0 in plotly)
    currentvalue = list(prefix = "Chlorine: "),
    steps = steps
  )),
  barmode="stack"
)


dose.response = Vaste@output


Pathogen <- c("Kampylobakteeri","E.coli O157:H7","Rotavirus","Norovirus","Cryptosporidium","Giardia")
# calculate the number of cases
cases <- BoDattr/case_burden


vaesto <- opbase.data("Op_fi2652")[,c("Ikä","Result")]
cases <- oapply(unkeep(cases, sources=TRUE), NULL, mean, "Iter")
colnames(vaesto) <- c("Age", "Osuus")
cases <- oapply(cases, FUN=sum, cols="Age")


vaesto$Populaatio <- vaesto$Osuus * Vaestonkoko
plot_ly(cases@output, x = ~Result, y = ~Exposure_agent,
        type = 'bar', orientation = 'h',
        color = ~Response, width = 3,
        colors=c("sandybrown", "gray50", "darkorchid1", "aquamarine1", "firebrick1",
                "cornflowerblue", "gold1", "chocolate3")) %>%
  layout(barmode = 'stack',
        title = paste('Cases of disease from drinking water in a population of', total_population),
        xaxis = list(title ="tautitapaukset"),
        yaxis = list(title =""))


odotettu.elinika <- 81
###############


colnames(dose.response)[colnames(dose.response) == "Patogeeni"] <- "Pathogen"
doses <- c("None","Low","High")
colnames(dose.response)[colnames(dose.response) == "VasteResult"] <- "P.inf"
plotdata <- data.frame(
colnames(dose.response)[colnames(dose.response) == "AltistuminenResult"] <- "Exp.pat"
  Exposure_agent = rep(c("Noro","Ecoli"),each=3),
  Response = c("Gastroenteritis","Fever"),
  Chlorine = doses,
  BoDattrResult = c(3,2,1,6,5,4)
)


P.ill.g.inf <- data.frame(Pathogen, P.ill.g.inf = c(0.33, 1 - (270 / 1540), 0.9, 0.7, 0.71, 1)) # todennäköisyys sairastua kun saa infektion
steps <- list()
pl <- plot_ly()
for(i in doses) { # add data for each slider step (=each chlorine level)
  tmp <- plotdata[plotdata$Chlorine==i , ] # Slice rows for each chlorine level at a time
  pl <- add_trace( # Add a separate dataset for each step
    pl,
    x = tmp$Exposure_agent,
    y = tmp$BoDattrResult,
    color = tmp$Response,
name = tmp$Chlorine,
    type = "bar",
    #    orientation = "h",
    visible = i==doses[1] # Make only the first dataset visible by default SOMETHING STRANGE HERE
   
  )
  step <- list(
    args = list('visible', i==dose), # Make all datasets invisible in this step except this one
    label = i,
    value = match(i,doses),
    method = 'restyle' # I suppose this means that the graph is retyled when the step changes
  )  
  steps[[match(i,doses)]] <- step
}


# Kampylobakteeri, DALYt per infektio
pl %>% layout(
  sliders = list(list(
    active = 0, # Make the first step active by default (counting starts from 0 in plotly)
    currentvalue = list(prefix = "Chlorine: "),
    steps = steps
  )),
  barmode="stack"
)
</rcode>


P.treat.g.ill.Kamp.Gastr <- data.frame(Pathogen = Pathogen[c(1,1,1)], Outcome = "Gastroenteritis", ill.treat = c("Untreated",
==== Plotly with two sliders ====
    "General practitioner", "Hospitalised", "Unspecified")[c(1,2,3)], P.treat.g.ill = c(0.7627, 0.2373, 0.0097))


P.treat.ill.g.inf.Kamp.Gastr <- merge(P.treat.g.ill.Kamp.Gastr, P.ill.g.inf)
<rcode label="Run on own computer" name="plotlydata">
P.treat.ill.g.inf.Kamp.Gastr$P.treat.ill.g.inf <- P.treat.ill.g.inf.Kamp.Gastr$P.ill.g.inf *
# This is code Op_en6177/plotlydata on page [[Water guide]]
    P.treat.ill.g.inf.Kamp.Gastr$P.treat.g.ill
library(OpasnetUtils)
library(ggplot2)
library(plotly)


duration.ill.treat.Kamp.Gastr <- data.frame(Outcome = c("Gastroenteritis"), ill.treat = c("Untreated", "General practitioner",
openv.setN(100)
    "Hospitalised", "Unspecified")[c(1,2,3)], dur.ill = c(5.1 / 365, 8.4 / 365, 14.39 / 365))


severity.ill.treat.Kamp.Gastr <- data.frame(Outcome = c("Gastroenteritis"), ill.treat = c("Untreated", "General practitioner",
objects.latest("Op_en6177", code_name="waterguide") # [[Water guide]] fetch the whole model
    "Hospitalised", "Unspecified")[c(1,2,3)], sev.ill = c(0.067, 0.393, 0.393))


daly.ill.treat.Kamp.Gastr <- merge(P.treat.ill.g.inf.Kamp.Gastr, duration.ill.treat.Kamp.Gastr)
total_population <- 10000
daly.ill.treat.Kamp.Gastr <- merge(daly.ill.treat.Kamp.Gastr, severity.ill.treat.Kamp.Gastr)
 
daly.ill.treat.Kamp.Gastr$dalys <- daly.ill.treat.Kamp.Gastr$P.treat.ill.g.inf * daly.ill.treat.Kamp.Gastr$dur.ill *  
# Create ovariables
    daly.ill.treat.Kamp.Gastr$sev.ill
RawConsumption <- Ovariable("RawConsumption", data=data.frame(Result=0.8))
# divide the given population size to different age groups based on age distribution of all of Finland
population <- Ovariable("population",
                        dependencies=data.frame(
                          Name=c("total_population")
                        ),
                        formula=function (...) {
                          population2 <- Ovariable(
                            "population2",
                            ddata="Op_en2949", subset="Population"
                          )
                          population2 <- EvalOutput(population2)
                          population <- population2/oapply(population2, cols = "Age", FUN=sum) *
                            total_population
                          return(population)
                        }
)




P.death.g.ill.Gastr <- 0.0004
ChlorineDose <- Ovariable("ChlorineDose",
P.death.g.inf.Gastr <- P.death.g.ill.Gastr * P.ill.g.inf$P.ill.g.inf[P.ill.g.inf$Pathogen == "Kampylobakteeri"]
                          data=data.frame(ClDose=seq(0,0.5,0.1),
death.Gastr.life.lost <- 13.2
                                          Result=seq(0,0.5,0.1)))
daly.death.Kamp.Gastr <- P.death.g.inf.Gastr * death.Gastr.life.lost


## GBS Kamp.
# Making the dataframes used in plots----


P.gbs.g.ill <- 2e-004
treatment <- list(c("None"),
P.gbs.g.inf <- P.gbs.g.ill * P.ill.g.inf$P.ill.g.inf[P.ill.g.inf$Pathogen == "Kampylobakteeri"]
                  c("Slow sand filtration"),
dur.sev.factor.gbs <- data.frame(Outcome = c("Clinical GBS", "Residual GBS"), dur.sev.factor = c(0.29, 5.8)) # duration * severity * fraction?
                  c("Slow sand filtration"),
daly.Kamp.gbs <- data.frame(dur.sev.factor.gbs$Outcome, dalys = dur.sev.factor.gbs$dur.sev.factor * P.gbs.g.inf)
                  c("None"),
                  c("None"),
                  c("Slow sand filtration"),
                  c("Slow sand filtration", "Active carbon filtration"))
uvct <- c(0,0,10,0,10,10,10)
rawclass <- c(rep("Ground water - clean", 3), rep("Surface water - high contamination", 4))
labels <- c("Ground - none", "Ground - sand", "Ground - sand+uv", "Surface - none",
          "Surface - uv", "Surface - sand+uv", "Surface - sand+carbon+uv")


P.death.g.gbs <- 0.08 / 3 # triangular 0.01, 0.02, 0.05
plotdata_illness <- data.frame(matrix(ncol=5, nrow=0))
P.death.g.inf.gbs <- P.death.g.gbs * P.gbs.g.inf
colnames(plotdata_illness) <- c("Response", "ClDose", "RawWaterClass", "BoDattrResult", "label")
death.gbs.life.lost <- 18.7
plotdata_age <- data.frame(matrix(ncol=5, nrow=0))
daly.death.Kamp.gbs <- P.death.g.inf.gbs * death.gbs.life.lost
colnames(plotdata_age) <- c("ClDose", "RawWaterClass", "Age", "BoDattrResult", "label")
plotdata_path <- data.frame(matrix(ncol=5, nrow=0))
colnames(plotdata_path) <- c("Exposure_agent", "ClDose", "RawWaterClass", "BoDattrResult", "label")
plotdata_path_gastro <- data.frame(matrix(ncol=6, nrow=0))
colnames(plotdata_path_gastro) <- c("Exposure_agent", "Response", "ClDose", "RawWaterClass", "BoDattrResult", "label")


## reactive arthritis Kamp.
for(i in 1:length(treatment)){
  RawClass <- Ovariable("RawClass", data=data.frame(RawWaterClass = rawclass[i], Result=1))
  Treatment <- Ovariable("Treatment", data=data.frame(TreatmentMethod=treatment[[i]], Result=1))
  UVCT <- Ovariable("UVCT", data=data.frame(Result=uvct[i]))
  BoDattr <- EvalOutput(BoDattr, forceEval=TRUE)
  plotdata <- oapply(BoDattr, c("Response","Exposure_agent","ClDose","RawWaterClass", "Iter", "Age"), sum)
  plotdata <- oapply(plotdata, FUN=mean, cols="Iter")
 
  cases <- BoDattr/case_burden
  casedata <- oapply(cases, c("Response","Exposure_agent","ClDose","RawWaterClass", "Iter", "Age"), sum)
  casedata <- oapply(casedata, FUN=mean, cols="Iter")
 
  plotdata_illness <- rbind(plotdata_illness, data.frame(
    oapply(plotdata, FUN=sum, cols=c("Exposure_agent", "Age"))@output,
    label = labels[i]))
  plotdata_age <- rbind(plotdata_age, data.frame(
    oapply(plotdata, FUN=sum, cols=c("Exposure_agent", "Response"))@output,
    label = labels[i]))
  plotdata_path <- rbind(plotdata_path, data.frame(
    oapply(plotdata, FUN=sum, cols=c("Response", "Age"))@output,
    label = labels[i]))
 
  plotdata_path_gastro <- rbind(plotdata_path_gastro, data.frame(
    oapply(casedata, FUN=sum, cols=c("Age"))@output,
    label = labels[i]))


P.arth.g.ill <- 0.02 # triangluar 0.01, 0.02, 0.03
 
P.arth.g.inf <- P.arth.g.ill * P.ill.g.inf$P.ill.g.inf[P.ill.g.inf$Pathogen == "Kampylobakteeri"]
}
duration.arth <- 6 / 52
severity.arth <- 0.21
daly.Kamp.arth <- P.arth.g.inf * duration.arth * severity.arth


# E.coli
# SUOMENNOKSET, JOS HALUTAAN SUOMENKIELISET KUVAT
levels(plotdata_illness$Response) <- c("kliininen Guillian-Barrén oireyhtymä", "kuolema",
                                      "loppuvaiheen munuaistauti", "gastroenteriitti",
                                      "hemolyyttis-ureeminen oireyhtymä", "suolistoverenvuoto",
                                      "reaktiivinen niveltulehdus",
                                      "Guillian-Barrén jäännösoireet")
levels(plotdata_path$Exposure_agent) <- c("kampylobakteeri", "kryptosporidium", "E. coli O157:H7",
                                          "giardia", "norovirus", "rotavirus")
levels(plotdata_illness$label) <- c("pohjavesi - ei puhdistusta", "pohjavesi - hiekka",
                                    "pohjavesi - hiekka+uv", "pintavesi - ei puhdistusta",
                                    "pintavesi - uv", "pintavesi - hiekka+uv",
                                    "pintavesi - hiekka+aktiivihiili+uv")
levels(plotdata_path$label) <- c("pohjavesi - ei puhdistusta", "pohjavesi - hiekka",
                                "pohjavesi - hiekka+uv", "pintavesi - ei puhdistusta", "pintavesi - uv",
                                "pintavesi - hiekka+uv", "pintavesi - hiekka+aktiivihiili+uv")
levels(plotdata_age$label) <- c("pohjavesi - ei puhdistusta", "pohjavesi - hiekka",
                                "pohjavesi - hiekka+uv", "pintavesi - ei puhdistusta", "pintavesi - uv",
                                "pintavesi - hiekka+uv", "pintavesi - hiekka+aktiivihiili+uv")


P.wd.g.ill <- 0.53 # watery diarrhea
### DALYS CAUSED BY DISEASE ----
P.wd.g.inf <- P.wd.g.ill * P.ill.g.inf$P.ill.g.inf[P.ill.g.inf$Pathogen == "E.coli O157:H7"]
severity.wd <- 0.067
duration.wd <- 3.4 / 365
daly.wd.Ecoli <- P.wd.g.inf * severity.wd * duration.wd


P.hc.g.ill <- 0.47
illness_data <- plotdata_illness
P.hc.g.inf <- P.hc.g.ill * P.ill.g.inf$P.ill.g.inf[P.ill.g.inf$Pathogen == "E.coli O157:H7"]
colnames(illness_data) <- c("response", "cldose", "rawclass", "result", "label")
severity.hc <- 0.39
duration.hc <- 5.6 / 365
daly.hc.Ecoli <- P.hc.g.inf * severity.hc * duration.hc


P.death.g.ill.Ecoli <- 0.00027
illness_data$visible <- F
P.death.g.inf.Ecoli <- P.death.g.ill.Ecoli * P.ill.g.inf$P.ill.g.inf[P.ill.g.inf$Pathogen == "E.coli O157:H7"]
illness_data$visible[illness_data$label==levels(illness_data$label)[1]] = T # clean ground water visible
age.death.Ecoli <- 81 - 13.2
daly.death.Ecoli <- P.death.g.inf.Ecoli * (odotettu.elinika - age.death.Ecoli)


## Haemolytic uraemic syndrome (HUS)
# create steps and plot all traces
buttons_water1 <- list()
illness_plot <- plot_ly()
for (i in 1:length(treatment)) {
  illness_plot <- add_trace(illness_plot, # add traces to illness_plot
                            type = "scatter",
                            x=illness_data$result[illness_data$label==levels(illness_data$label)[i]], # x (BoD) on x
                            y=illness_data$response[illness_data$label==levels(illness_data$label)[i]], # y (exposure agent) on y
                            visible = illness_data$visible[illness_data$label==levels(illness_data$label)[i]], # is this trace visible
#                            text = aval$pathogen[aval$rawclass==levels(aval$rawclass)[i]], # text to be used as a label
                            mode="markers",
                            marker = list(size=10, # marker size
                                          colorscale = list(list(0, 'rgba(200,200,200,0.2)'), list(1, 'rgba(0,181,204,1)')), # sets the colors used when color=0 and color=1
                                          color = c(rep(1, 8), # the first 17 markers use color 1
                                                    rep(0, 8*5))),
#                                          opacity = c(rep(1, 8), # the first 17 markers use color 1
#                                                      rep(0.05, 8*5))), # the rest use color 0
                            hoverinfo = "x", # what is the info shown when mouse on top of marker
                            showlegend=F)


P.hus.g.ill <- 0.01
  bw <- list(args = list('visible', rep(FALSE, length(treatment))), # set all steps to not visible
P.hus.g.inf <- P.hus.g.ill * P.ill.g.inf$P.ill.g.inf[P.ill.g.inf$Pathogen == "E.coli O157:H7"]
              method = 'restyle',
severity.hus <- 0.93
              label= levels(illness_data$label)[i]) # Sets the text label to appear on the menu
duration.hus <- 21 / 365
  bw$args[[2]][i] = TRUE  # set data on i+1 step to be visible when step i is chosen
daly.hus.Ecoli <- P.hus.g.inf * severity.hus * duration.hus
  buttons_water1[[i]] = bw # make a list with all the steps


P.death.g.hus <- 0.04
steps_cl1 <- list(list(args = list('marker.color', # marker color is changed
P.death.hus.g.inf <- P.death.g.hus * P.hus.g.inf
                                  array(c(rep(1, 8), rep(0, 8*5)), dim=c(1, 102))), # these are the new markers with color 1 and 0
age.death.hus.Ecoli <- 81 - 26.2
                      method = 'restyle', # restyling the markers
daly.death.hus.Ecoli <- P.death.hus.g.inf * (odotettu.elinika - age.death.hus.Ecoli)
                      label = "0"), # label on the slider
                  list(args = list('marker.color',
                                  array(c(rep(0, 8), rep(1, 8), rep(0, 8*4)), dim=c(1, 102))),
                      method = 'restyle',
                      label = "0.1"),
                  list(args = list('marker.color',
                                  array(c(rep(0, 8*2), rep(1, 8), rep(0, 8*3)), dim=c(1, 102))),
                      method = 'restyle',
                      label = "0.2"),
                  list(args = list('marker.color',
                                  array(c(rep(0, 8*3), rep(1, 8), rep(0, 8*2)), dim=c(1, 102))),
                      method = 'restyle',
                      label = "0.3"),
                  list(args = list('marker.color',
                                  array(c(rep(0, 8*4), rep(1, 8), rep(0, 8)), dim=c(1, 102))),
                      method = 'restyle',
                      label = "0.4"),
                  list(args = list('marker.color',
                                  array(c(rep(0, 8*5), rep(1, 8)), dim=c(1, 102))),
                      method = 'restyle',
                      label = "0.5")
)


## End Stage Renal Disease (ESRD)
# add slider control to plot
illness_plot <- illness_plot %>%
  layout(sliders = list(list(active = 0, #Determines which button (by index starting from 0) is active.
                            currentvalue = list(prefix = "Klooriannos mg/l:"), #suomeksi
#                            currentvalue = list(prefix = "Chlorine dose: "), # in English
                            # the text under the graph that tells what the slider values mean
                            steps = steps_cl1)),
        updatemenus = list(list(active = 0,
                                buttons = buttons_water1,
                                y = -0.15,
                                x = -0.1,
                                direction = "up")),
#        title = paste('Burdens of disease of drinking water in a population of', total_population), # in English
        title = paste("Juomaveden aiheuttama tautitaakka", total_population, "hengen populaatiossa"), # suomeksi
        xaxis = list(title ="DALY"),
        yaxis = list(title =""))


P.esrd.g.hus <- 0.118
illness_plot
P.esrd.g.inf <- P.hus.g.inf * P.esrd.g.hus
severity.duration.hus <- 8.7 # severity * duration
daly.esrd.Ecoli <- P.esrd.g.inf * severity.duration.hus


P.death.g.esrd <- 0.0252
#
P.death.esrd.g.inf <- P.esrd.g.inf * P.death.g.esrd
age.death.esrd.Ecoli <- 81 - 34
daly.death.esrd.Ecoli <- P.death.esrd.g.inf * (odotettu.elinika - age.death.esrd.Ecoli)


# Rotavirus
### DALYS BY AGE GROUP ----


P.treat.g.ill.Rotavirus <- data.frame(Pathogen = "Rotavirus", ill.treat = c("Untreated",  
# a data frame with the relevant columns
    "General practitioner", "Hospitalised")[rep(1:3, each = 82)], Age = rep(0:81, 3), P.treat.g.ill = c(rep(0.82,5),
age_data <- plotdata_age
    rep(0.95, 10), rep(0.99, 50), rep(0.97, 17), rep(0.137, 5), rep(0.0244, 5), rep(0.0511, 5), rep(0.0127, 50),
colnames(age_data) <- c("cldose", "rawclass", "age", "result", "label")
    rep(0.0299, 17), rep(0.0416, 5), rep(0.0213, 5), rep(0, 72)))


P.treat.ill.g.inf.Rotavirus <- merge(P.treat.g.ill.Rotavirus, P.ill.g.inf)
age_data$visible <- F
P.treat.ill.g.inf.Rotavirus$P.treat.g.inf <- P.treat.ill.g.inf.Rotavirus$P.ill.g.inf * P.treat.ill.g.inf.Rotavirus$P.treat.g.ill
age_data$visible[age_data$label==levels(age_data$label)[1]] = T # ground water + none visible


duration.ill.treat.Rotavirus <- data.frame(ill.treat = c("Untreated", "General practitioner","Hospitalised"), dur.ill = c(4.9 / 365,  
# ordering the age groups to be in the right order
    7.1 / 365, 7.7 / 365))
age_data$age <- factor(age_data$age, levels(age_data$age)[c(1,4,2,3,5,6)])
age_data <- age_data[order(as.numeric(age_data$age)),]


severity.ill.treat.Rotavirus <- data.frame(ill.treat = c("Untreated", "General practitioner", "Hospitalised"), sev.ill = c(0.067,
    0.393, 0.393))


daly.ill.treat.Rotavirus <- merge(P.treat.ill.g.inf.Rotavirus, duration.ill.treat.Rotavirus)
# create steps and plot all traces
daly.ill.treat.Rotavirus <- merge(daly.ill.treat.Rotavirus, severity.ill.treat.Rotavirus)
buttons_water2 <- list()
daly.ill.treat.Rotavirus$dalys <- daly.ill.treat.Rotavirus$P.treat.g.inf * daly.ill.treat.Rotavirus$dur.ill *
age_plot <- plot_ly()
    daly.ill.treat.Rotavirus$sev.ill
for (i in 1:length(treatment)) {
  age_plot <- add_trace(age_plot, # add traces to age_plot
                        type = "scatter",
                        x=age_data$result[age_data$label==levels(age_data$label)[i]], # x (BoD) on x
                        y=age_data$age[age_data$label==levels(age_data$label)[i]], # y (exposure agent) on y
                        visible = age_data$visible[age_data$label==levels(age_data$label)[i]], # is this trace visible
#                        text = aval$pathogen[aval$rawclass==levels(aval$rawclass)[i]], # text to be used as a label
                        mode="markers",
                        marker = list(size=10, # marker size
                                      colorscale = list(list(0, 'rgba(200,200,200,0.2)'), list(1, 'rgba(0,181,204,1)')), # sets the colors used when color=0 and color=1
                                      color = c(rep(c(1,0,0,0,0,0), 6))),
                        hoverinfo = "x", # what is the info shown when mouse on top of marker
                        showlegend=F)
 
  bw <- list(args = list('visible', rep(FALSE, length(treatment))), # set all steps to not visible
            method = 'restyle',
            label= levels(age_data$label)[i]) # Sets the text label to appear on the menu
  bw$args[[2]][i] = TRUE  # set data on i+1 step to be visible when step i is chosen
  buttons_water2[[i]] = bw # make a list with all the steps




P.death.Rotavirus <- data.frame(Age = 0:81, P.death.g.ill = c(rep(2.13e-005, 5), rep(0, 77)))
steps_cl2 <- list(list(args = list('marker.color', # marker color is changed
P.death.Rotavirus$P.death.g.inf <- P.death.Rotavirus$P.death.g.ill * P.ill.g.inf$P.ill.g.inf[P.ill.g.inf$Pathogen == "Rotavirus"]
                                  array(c(rep(c(1,0,0,0,0,0), 6)), dim=c(1, 36))), # these are the new markers with color 1 and 0
P.death.Rotavirus$Life.lost <- odotettu.elinika - P.death.Rotavirus$Age
                      method = 'restyle', # restyling the markers
daly.death.Rotavirus <- data.frame(Age = P.death.Rotavirus$Age, dalys = P.death.Rotavirus$P.death.g.inf * P.death.Rotavirus$Life.lost)
                      label = "0"), # label on the slider
                  list(args = list('marker.color',
                                  array(c(rep(c(0,1,0,0,0,0), 6)), dim=c(1, 36))),
                      method = 'restyle',
                      label = "0.1"),
                  list(args = list('marker.color',
                                  array(c(rep(c(0,0,1,0,0,0), 6)), dim=c(1, 36))),
                      method = 'restyle',
                      label = "0.2"),
                  list(args = list('marker.color',
                                  array(c(rep(c(0,0,0,1,0,0), 6)), dim=c(1, 36))),
                      method = 'restyle',
                      label = "0.3"),
                  list(args = list('marker.color',
                                  array(c(rep(c(0,0,0,0,1,0), 6)), dim=c(1, 36))),
                      method = 'restyle',
                      label = "0.4"),
                  list(args = list('marker.color',
                                  array(c(rep(c(0,0,0,0,0,1), 6)), dim=c(1, 36))),
                      method = 'restyle',
                      label = "0.5")
)


# Norovirus


P.treat.g.ill.Norovirus <- data.frame(Pathogen = "Norovirus", ill.treat = c("Untreated",  
# add slider control to plot
    "General practitioner", "Hospitalised")[rep(1:3, each = 82)], Age = rep(0:81, 3), P.treat.g.ill = c(rep(0.94876706,5),  
age_plot <- age_plot %>%
    rep(0.9902, 5), rep(0.98239, 5), rep(0.98434, 51), rep(0.992741, 16), rep(0.0448,5), rep(8.6e-003, 5), rep(0.0154, 5),  
  layout(sliders = list(list(active = 0, #Determines which button (by index starting from 0) is active.
    rep(0.0137, 51), rep(6.17e-003, 16), rep(6.43e-003,5), rep(1.2e-003, 5), rep(2.21e-003, 5), rep(1.96e-003, 51),  
                            currentvalue = list(prefix = "Klooriannos mg/l:"), #suomeksi
    rep(8.85e-004, 16)))
#                            currentvalue = list(prefix = "Chlorine dose: "), #in English
                            steps = steps_cl2)),
        updatemenus = list(list(active = 0,
                                y = -0.15,
                                x = -0.1,
                                direction = "up",
                                buttons = buttons_water2)),
        title = paste("Juomaveden aiheuttama tautitaakka", total_population, "hengen populaatiossa"), # suomeksi
#        title = paste('Burdens of disease of drinking water in a population of', total_population), # in English
        xaxis = list(title ="DALY"),
        yaxis = list(title =""))


P.treat.ill.g.inf.Norovirus <- merge(P.treat.g.ill.Norovirus, P.ill.g.inf)
age_plot
P.treat.ill.g.inf.Norovirus$P.treat.g.inf <- P.treat.ill.g.inf.Norovirus$P.ill.g.inf * P.treat.ill.g.inf.Norovirus$P.treat.g.ill


duration.ill.treat.Norovirus <- data.frame(ill.treat = c("Untreated", "General practitioner","Hospitalised"), dur.ill = c(3.8 / 365,
#
    5.73 / 365, 7.23 / 365))


severity.ill.treat.Norovirus <- data.frame(ill.treat = c("Untreated", "General practitioner", "Hospitalised"), sev.ill = c(0.067,
### DALYS CAUSED BY PATHOGEN ----
    0.393, 0.393))


daly.ill.treat.Norovirus <- merge(P.treat.ill.g.inf.Norovirus, duration.ill.treat.Norovirus)
# a data frame with the relevant columns
daly.ill.treat.Norovirus <- merge(daly.ill.treat.Norovirus, severity.ill.treat.Norovirus)
pathogen_data <- plotdata_path
daly.ill.treat.Norovirus$dalys <- daly.ill.treat.Norovirus$P.treat.g.inf * daly.ill.treat.Norovirus$dur.ill *
colnames(pathogen_data) <- c("pathogen", "cldose", "rawclass", "result", "label")
    daly.ill.treat.Norovirus$sev.ill


P.death.Norovirus <- data.frame(Age = 0:81, P.death.g.ill = c(rep(2.94e-006, 5), rep(0, 61), rep(2.04e-004, 16)))
pathogen_data$visible <- F
P.death.Norovirus$P.death.g.inf <- P.death.Norovirus$P.death.g.ill * P.ill.g.inf$P.ill.g.inf[P.ill.g.inf$Pathogen == "Norovirus"]
pathogen_data$visible[pathogen_data$label==levels(pathogen_data$label)[1]] = T # ground water + none visible
P.death.Norovirus$Life.lost <- odotettu.elinika - P.death.Norovirus$Age
daly.death.Norovirus <- data.frame(Age = P.death.Norovirus$Age, dalys = P.death.Norovirus$P.death.g.inf * P.death.Norovirus$Life.lost)


# Cryptosporidium
#levels(pathogen_data$rawclass) <- c("clean", "almost", "high", "low", "medium")
#pathogen_data$rawclass <- factor(pathogen_data$rawclass, levels(pathogen_data$rawclass)[c(2,4,5,3,1)])
#pathogen_data$visible[pathogen_data$rawclass==levels(pathogen_data$rawclass)[1]] = T # clean ground water visible


P.treat.g.ill.Crypt <- data.frame(Pathogen = "Cryptosporidium", ill.treat = c("Untreated",  
# create steps and plot all traces
    "General practitioner", "Hospitalised")[rep(1:3, each = 82)], Age = rep(0:81, 3), P.treat.g.ill = c(rep(0.9175730049999999,5),  
buttons_water3 <- list()
    rep(0.80937, 5), rep(0.6810499999999999, 5), rep(0.9774191, 50), rep(0.94706, 17), rep(0.082,5), rep(0.188, 5), rep(0.316, 5),
pathogen_plot <- plot_ly()
    rep(0.0209, 50), rep(0.0367, 17), rep(4.26e-004,5), rep(2.63e-003, 5), rep(2.95e-003, 5), rep(1.66e-003, 50), rep(0.0146, 17)))
for (i in 1:length(treatment)) {
pathogen_plot <- add_trace(pathogen_plot, # add traces to illness_plot
                            type = "scatter",
                            x=pathogen_data$result[pathogen_data$label==levels(pathogen_data$label)[i]], # x (BoD) on x
                            y=pathogen_data$pathogen[pathogen_data$label==levels(pathogen_data$label)[i]], # y (exposure agent) on y
                            visible = pathogen_data$visible[pathogen_data$label==levels(pathogen_data$label)[i]], # is this trace visible
                            mode="markers",
                            marker = list(size=10, # marker size
                                          colorscale = list(list(0, 'rgba(200,200,200,0.2)'), list(1, 'rgba(0,181,204,1)')), # sets the colors used when color=0 and color=1
                                          color = c(rep(1, 6), # the first 17 markers use color 1
                                                    rep(0, 6*5))), # the rest use color 0
                            hoverinfo = "x", # what is the info shown when mouse on top of marker
                            showlegend=F)
 
  bw <- list(args = list('visible', rep(FALSE, length(treatment))), # set all steps to not visible
            method = 'restyle',
            label= levels(pathogen_data$label)[i]) # Sets the text label to appear on the menu
  bw$args[[2]][i] = TRUE  # set data on i+1 step to be visible when step i is chosen
  buttons_water3[[i]] = bw # make a list with all the steps


P.treat.ill.g.inf.Crypt <- merge(P.treat.g.ill.Crypt, P.ill.g.inf)
P.treat.ill.g.inf.Crypt$P.treat.g.inf <- P.treat.ill.g.inf.Crypt$P.ill.g.inf * P.treat.ill.g.inf.Crypt$P.treat.g.ill


duration.ill.treat.Crypt <- data.frame(ill.treat = c("Untreated", "General practitioner","Hospitalised"), dur.ill = c(3.5 / 365,  
steps_cl3 <- list(list(args = list('marker.color', # marker color is changed
    7 /365, 18.4 / 365))
                                  array(c(rep(1, 6), rep(0, 6*5)), dim=c(1, 36))), # these are the new markers with color 1 and 0
                      method = 'restyle', # restyling the markers
                      label = "0"), # label on the slider
                  list(args = list('marker.color',
                                  array(c(rep(0, 6), rep(1, 6), rep(0, 6*4)), dim=c(1, 36))),
                      method = 'restyle',
                      label = "0.1"),
                  list(args = list('marker.color',
                                  array(c(rep(0, 6*2), rep(1, 6), rep(0, 6*3)), dim=c(1, 36))),
                      method = 'restyle',
                      label = "0.2"),
                  list(args = list('marker.color',
                                  array(c(rep(0, 6*3), rep(1, 6), rep(0, 6*2)), dim=c(1, 36))),
                      method = 'restyle',
                      label = "0.3"),
                  list(args = list('marker.color',
                                  array(c(rep(0, 6*4), rep(1, 6), rep(0, 6)), dim=c(1, 36))),
                      method = 'restyle',
                      label = "0.4"),
                  list(args = list('marker.color',
                                  array(c(rep(0, 6*5), rep(1, 6)), dim=c(1, 36))),
                      method = 'restyle',
                      label = "0.5")
)


severity.ill.treat.Crypt <- data.frame(ill.treat = c("Untreated", "General practitioner", "Hospitalised"), sev.ill = c(0.067,
    0.393, 0.393))


daly.ill.treat.Crypt <- merge(P.treat.ill.g.inf.Crypt, duration.ill.treat.Crypt)
# add slider control to plot
daly.ill.treat.Crypt <- merge(daly.ill.treat.Crypt, severity.ill.treat.Crypt)
pathogen_plot <- pathogen_plot %>%
daly.ill.treat.Crypt$dalys <- daly.ill.treat.Crypt$P.treat.g.inf * daly.ill.treat.Crypt$dur.ill *
  layout(sliders = list(list(active = 0, #Determines which button (by index starting from 0) is active.
    daly.ill.treat.Crypt$sev.ill
                            currentvalue = list(prefix = "Klooriannos mg/l:"), # suomeksi
#                            currentvalue = list(prefix = "Chlorine dose: "), # in English                              # the text under the graph that tells what the slider values mean
                            steps = steps_cl3)),
        updatemenus = list(list(active = 0,
                                y = -0.15,
                                x = -0.1,
                                direction = "up",
                                buttons = buttons_water3)),
        title = paste("Juomaveden aiheuttama tautitaakka", total_population, "hengen populaatiossa"), # suomeksi
#        title = paste('Burdens of disease of drinking water in a population of', total_population), # in English
        xaxis = list(title ="DALY"),
        yaxis = list(title =""))


P.death.Crypt <- data.frame(Age = 0:81, P.death.g.ill = c(rep(9.95e-007, 5), rep(0, 10), rep(2.09e-005, 50), rep(1.64e-003, 17)))
P.death.Crypt$P.death.g.inf <- P.death.Crypt$P.death.g.ill * P.ill.g.inf$P.ill.g.inf[P.ill.g.inf$Pathogen == "Cryptosporidium"]
P.death.Crypt$Life.lost <- odotettu.elinika - P.death.Crypt$Age
daly.death.Crypt <- data.frame(Age = P.death.Crypt$Age, dalys = P.death.Crypt$P.death.g.inf * P.death.Crypt$Life.lost)


# Giardia
pathogen_plot


P.treat.g.ill.Giardia <- data.frame(Pathogen = "Giardia", ill.treat = c("Untreated",
    "General practitioner", "Hospitalised")[rep(1:3, each = 82)], Age = rep(0:81, 3), P.treat.g.ill = c(rep(0.9376,5),
    rep(0.91034, 5), rep(0.72642, 5), rep(0.92486, 50), 0.54596, rep(0.5365, 16), rep(0.0609,5), rep(0.0852, 5), rep(0.272, 5),
    rep(0.0721, 50), rep(0.451, 17), rep(1.5e-003,5), rep(4.46e-003, 5), rep(1.58e-003, 5), rep(3.04e-003, 51), rep(0.0125, 16)))


P.treat.ill.g.inf.Giardia <- merge(P.treat.g.ill.Giardia, P.ill.g.inf)
### DALYs BY PATHOGEN, ONLY GASTROENTERITIS ----
P.treat.ill.g.inf.Giardia$P.treat.g.inf <- P.treat.ill.g.inf.Giardia$P.ill.g.inf * P.treat.ill.g.inf.Giardia$P.treat.g.ill


duration.ill.treat.Giardia <- data.frame(ill.treat = c("Untreated", "General practitioner","Hospitalised"), dur.ill = c(10 / 365,  
# a data frame with the relevant columns
    10 /365, 30 / 365))
pathogen_gastro_data <- plotdata_path_gastro[plotdata_path_gastro$Response == "gastroenteritis",]
colnames(pathogen_gastro_data) <- c("response", "pathogen", "cldose", "rawclass", "result", "label")


severity.ill.treat.Giardia <- data.frame(ill.treat = c("Untreated", "General practitioner", "Hospitalised"), sev.ill = c(0.067,
pathogen_gastro_data$visible <- F
    0.393, 0.393))
pathogen_gastro_data$visible[pathogen_gastro_data$label==levels(pathogen_gastro_data$label)[1]] = T # ground water + none visible


daly.ill.treat.Giardia <- merge(P.treat.ill.g.inf.Giardia, duration.ill.treat.Giardia)
#levels(pathogen_data$rawclass) <- c("clean", "almost", "high", "low", "medium")
daly.ill.treat.Giardia <- merge(daly.ill.treat.Giardia, severity.ill.treat.Giardia)
#pathogen_data$rawclass <- factor(pathogen_data$rawclass, levels(pathogen_data$rawclass)[c(2,4,5,3,1)])
daly.ill.treat.Giardia$dalys <- daly.ill.treat.Giardia$P.treat.g.inf * daly.ill.treat.Giardia$dur.ill *
#pathogen_data$visible[pathogen_data$rawclass==levels(pathogen_data$rawclass)[1]] = T # clean ground water visible
    daly.ill.treat.Giardia$sev.ill


# yhteenveto DALYistä
# create steps and plot all traces
buttons_water3 <- list()
path_gastro_plot <- plot_ly()
for (i in 1:length(treatment)) {
  path_gastro_plot <- add_trace(path_gastro_plot, # add traces to illness_plot
                            type = "scatter",
                            x=pathogen_gastro_data$result[pathogen_gastro_data$label==levels(pathogen_gastro_data$label)[i]], # x (BoD) on x
                            y=pathogen_gastro_data$pathogen[pathogen_gastro_data$label==levels(pathogen_gastro_data$label)[i]], # y (exposure agent) on y
                            visible = pathogen_gastro_data$visible[pathogen_gastro_data$label==levels(pathogen_gastro_data$label)[i]], # is this trace visible
                            mode="markers",
                            marker = list(size=10, # marker size
                                          colorscale = list(list(0, 'rgba(200,200,200,0.2)'), list(1, 'rgba(0,181,204,1)')), # sets the colors used when color=0 and color=1
                                          color = c(rep(1, 6), # the first 17 markers use color 1
                                                    rep(0, 6*5))), # the rest use color 0
                            hoverinfo = "x", # what is the info shown when mouse on top of marker
                            showlegend=F)
 
  bw <- list(args = list('visible', rep(FALSE, length(treatment))), # set all steps to not visible
            method = 'restyle',
            label= levels(pathogen_gastro_data$label)[i]) # Sets the text label to appear on the menu
  bw$args[[2]][i] = TRUE  # set data on i+1 step to be visible when step i is chosen
  buttons_water3[[i]] = bw # make a list with all the steps


Health.effects <- vaesto[,c("Age","Populaatio")]


Health.effects$Untreated.Gastr.Kamp <- daly.ill.treat.Kamp.Gastr[daly.ill.treat.Kamp.Gastr$ill.treat == "Untreated", c("dalys")]
steps_cl3 <- list(list(args = list('marker.color', # marker color is changed
Health.effects$GP.Gastr.Kamp <- daly.ill.treat.Kamp.Gastr[daly.ill.treat.Kamp.Gastr$ill.treat == "General practitioner", c("dalys")]
                                  array(c(rep(1, 6), rep(0, 6*5)), dim=c(1, 36))), # these are the new markers with color 1 and 0
Health.effects$Hospitalised.Gastr.Kamp <- daly.ill.treat.Kamp.Gastr[daly.ill.treat.Kamp.Gastr$ill.treat == "Hospitalised", c("dalys")]
                      method = 'restyle', # restyling the markers
Health.effects$Death.Gastr.Kamp <- daly.death.Kamp.Gastr
                      label = "0"), # label on the slider
                  list(args = list('marker.color',
                                  array(c(rep(0, 6), rep(1, 6), rep(0, 6*4)), dim=c(1, 36))),
                      method = 'restyle',
                      label = "0.1"),
                  list(args = list('marker.color',
                                  array(c(rep(0, 6*2), rep(1, 6), rep(0, 6*3)), dim=c(1, 36))),
                      method = 'restyle',
                      label = "0.2"),
                  list(args = list('marker.color',
                                  array(c(rep(0, 6*3), rep(1, 6), rep(0, 6*2)), dim=c(1, 36))),
                      method = 'restyle',
                      label = "0.3"),
                  list(args = list('marker.color',
                                  array(c(rep(0, 6*4), rep(1, 6), rep(0, 6)), dim=c(1, 36))),
                      method = 'restyle',
                      label = "0.4"),
                  list(args = list('marker.color',
                                  array(c(rep(0, 6*5), rep(1, 6)), dim=c(1, 36))),
                      method = 'restyle',
                      label = "0.5")
)


Health.effects$Clinical.GBS.Kamp <- daly.Kamp.gbs$dalys[1]
Health.effects$Residual.GBS.Kamp <- daly.Kamp.gbs$dalys[2]
Health.effects$Death.GBS.Kamp <- daly.death.Kamp.gbs


Health.effects$Arth.Kamp <- daly.Kamp.arth
# Add marker line
line <- list(
  type = "line",
  line = list(color = "red"),
  xref = "x",
  yref = "y"
)
lines <- list()
line[c("x0", "x1")] <- 1
line["y0"] <- -0.5
line["y1"] <- 5.5
lines <- c(lines, list(line))


Health.effects$WD.Ecoli <- daly.wd.Ecoli
# add slider control to plot
Health.effects$HC.Ecoli <- daly.hc.Ecoli
path_gastro_plot <- path_gastro_plot %>%
Health.effects$Death.Ecoli <- daly.death.Ecoli
  layout(sliders = list(list(active = 0, #Determines which button (by index starting from 0) is active.
                            currentvalue = list(prefix = "Klooriannos mg/l:"), # suomeksi
#                            currentvalue = list(prefix = "Chlorine dose: "), # in English the text under the graph that tells what the slider values mean
                            steps = steps_cl3)),
        updatemenus = list(list(active = 0,
                                y = -0.15,
                                x = -0.1,
                                direction = "up",
                                buttons = buttons_water3)),
        shapes = lines,
        title = paste("Juomaveden päivässä aiheuttamat suolistotautitapaukset", total_population, "hengen populaatiossa"), # suomeksi
#        title = paste('Number of gastroenteritis cases caused daily by drinking water in a population of', total_population), # in English
        xaxis = list(title ="Tautitapaukset"),
        yaxis = list(title =""))


Health.effects$HUS.Ecoli <- daly.hus.Ecoli
Health.effects$Death.HUS.Ecoli <- daly.death.hus.Ecoli


Health.effects$ESRD.Ecoli <- daly.esrd.Ecoli
path_gastro_plot
Health.effects$Death.ESRD.Ecoli <- daly.death.esrd.Ecoli


Health.effects <- merge(Health.effects, daly.ill.treat.Rotavirus[daly.ill.treat.Rotavirus$ill.treat == "Untreated", c("Age", "dalys")])
colnames(Health.effects)[ncol(Health.effects)] <- "Untreated.Rotavirus"
Health.effects <- merge(Health.effects, daly.ill.treat.Rotavirus[daly.ill.treat.Rotavirus$ill.treat == "General practitioner", c("Age", "dalys")])
colnames(Health.effects)[ncol(Health.effects)] <- "GP.Rotavirus"
Health.effects <- merge(Health.effects, daly.ill.treat.Rotavirus[daly.ill.treat.Rotavirus$ill.treat == "Hospitalised", c("Age", "dalys")])
colnames(Health.effects)[ncol(Health.effects)] <- "Hospitalised.Rotavirus"
Health.effects <- merge(Health.effects, daly.death.Rotavirus)
colnames(Health.effects)[ncol(Health.effects)] <- "Death.Rotavirus"


Health.effects <- merge(Health.effects, daly.ill.treat.Norovirus[daly.ill.treat.Norovirus$ill.treat == "Untreated", c("Age", "dalys")])
#
colnames(Health.effects)[ncol(Health.effects)] <- "Untreated.Norovirus"
Health.effects <- merge(Health.effects, daly.ill.treat.Norovirus[daly.ill.treat.Norovirus$ill.treat == "General practitioner", c("Age", "dalys")])
colnames(Health.effects)[ncol(Health.effects)] <- "GP.Norovirus"
Health.effects <- merge(Health.effects, daly.ill.treat.Norovirus[daly.ill.treat.Norovirus$ill.treat == "Hospitalised", c("Age", "dalys")])
colnames(Health.effects)[ncol(Health.effects)] <- "Hospitalised.Norovirus"
Health.effects <- merge(Health.effects, daly.death.Norovirus)
colnames(Health.effects)[ncol(Health.effects)] <- "Death.Norovirus"


Health.effects <- merge(Health.effects, daly.ill.treat.Crypt[daly.ill.treat.Crypt$ill.treat == "Untreated", c("Age", "dalys")])
#### STEPS TO CHANGE SIZE ----
colnames(Health.effects)[ncol(Health.effects)] <- "Untreated.Crypt"
Health.effects <- merge(Health.effects, daly.ill.treat.Crypt[daly.ill.treat.Crypt$ill.treat == "General practitioner", c("Age", "dalys")])
colnames(Health.effects)[ncol(Health.effects)] <- "GP.Crypt"
Health.effects <- merge(Health.effects, daly.ill.treat.Crypt[daly.ill.treat.Crypt$ill.treat == "Hospitalised", c("Age", "dalys")])
colnames(Health.effects)[ncol(Health.effects)] <- "Hospitalised.Crypt"
Health.effects <- merge(Health.effects, daly.death.Crypt)
colnames(Health.effects)[ncol(Health.effects)] <- "Death.Crypt"


Health.effects <- merge(Health.effects, daly.ill.treat.Giardia[daly.ill.treat.Giardia$ill.treat == "Untreated", c("Age", "dalys")])
#steps_ch <- list(list(args = list('marker.size', array(c(rep(13, 17), rep(3, 17*5)), dim=c(1, 102))),
colnames(Health.effects)[ncol(Health.effects)] <- "Untreated.Giardia"
#                    method = 'restyle',
Health.effects <- merge(Health.effects, daly.ill.treat.Giardia[daly.ill.treat.Giardia$ill.treat == "General practitioner", c("Age", "dalys")])
#                    label = "0"),
colnames(Health.effects)[ncol(Health.effects)] <- "GP.Giardia"
#              list(args = list('marker.size', array(c(rep(3, 17), rep(13, 17), rep(3, 17*4)), dim=c(1, 102))),
Health.effects <- merge(Health.effects, daly.ill.treat.Giardia[daly.ill.treat.Giardia$ill.treat == "Hospitalised", c("Age", "dalys")])
#                    method = 'restyle',
colnames(Health.effects)[ncol(Health.effects)] <- "Hospitalised.Giardia"
#                    label = "0.1"),
#              list(args = list('marker.size', array(c(rep(3, 17*2), rep(13, 17), rep(3, 17*3)), dim=c(1, 102))),
#                    method = 'restyle',
#                    label = "0.2"),
#              list(args = list('marker.size', array(c(rep(3, 17*3), rep(13, 17), rep(3, 17*2)), dim=c(1, 102))),
#                    method = 'restyle',
#                    label = "0.3"),
#              list(args = list('marker.size', array(c(rep(3, 17*4), rep(13, 17), rep(3, 17)), dim=c(1, 102))),
#                    method = 'restyle',
#                    label = "0.4"),
#              list(args = list('marker.size', array(c(rep(3, 17*5), rep(13, 17)), dim=c(1, 102))),
#                    method = 'restyle',
#                    label = "0.5")
#)


Health.effects <- reshape(Health.effects, idvar = c("Age"), times = colnames(Health.effects)[-c(1,2)], timevar = "Outcome",
# Add this to the plot, if you use the size:
    varying = list(colnames(Health.effects)[-c(1,2)]), direction = "long")
colnames(Health.effects)[4] <- "P.daly.g.inf"
   
Health.effects$Pathogen <- NA
Health.effects$Pathogen[grep(".Kamp", Health.effects$Outcome)] <- Pathogen[1]
Health.effects$Pathogen[grep(".Ecoli", Health.effects$Outcome)] <- Pathogen[2]
Health.effects$Pathogen[grep(".Rotavirus", Health.effects$Outcome)] <- Pathogen[3]
Health.effects$Pathogen[grep(".Norovirus", Health.effects$Outcome)] <- Pathogen[4]
Health.effects$Pathogen[grep(".Crypt", Health.effects$Outcome)] <- Pathogen[5]
Health.effects$Pathogen[grep(".Giardia", Health.effects$Outcome)] <- Pathogen[6]


Health.effects <- merge(Health.effects, dose.response[,c("Pathogen", "P.inf")])
#                marker = list(size = c(rep(13, 17), rep(3, 17*5)),
Health.effects$DALYs <- (1 - (1 - Health.effects$P.inf * Health.effects$P.daly.g.inf)^365) * Health.effects$Populaatio
#                              color = 'rgba(128,0,128,0.7)'),


temp <- merge(dose.response, P.ill.g.inf)
# PUSH INDICATOR GRAPH ----
pushIndicatorGraph(illness_plot, 188)
pushIndicatorGraph(age_plot, 189)
pushIndicatorGraph(pathogen_plot, 190)


############# EXTRA ###########################################


MikrobienLogVähenemä <- combine(Desinfiointi, PuhdistusTeho, KloorausTeho, name = "MikrobienLogVähenemä")


MikrobienLogVähenemä@output[["Puhdistusmenetelmä"]][
</rcode>
MikrobienLogVähenemä@output[["MikrobienLogVähenemäSource"]] == "KloorausTehoFormula"
] <- "Klooraus"


#MikrobienLogVähenemä <- oapply(MikrobienLogVähenemä, cols = c("Puhdistusmenetelmä", "KlooriAnnosSource"), FUN = sum, na.rm = TRUE)
== See also ==


#MikrobienLogVähenemä@output <- fillna(MikrobienLogVähenemä@output, colnames(MikrobienLogVähenemä@output)[MikrobienLogVähenemä@marginal])
{{method|moderator = Päivi Meriläinen}}
*[[:op_fi:Juomaveden patogeenit]]
*[[:op_fi:Juomaveden patogeenien terveysvaikutukset]]


############# TULOKSET #########################################################################################################
*[[:op_fi:Arviointi pohjavesilaitoksen mikrobiologisista riskeistä]]
*[[:op_fi:Arviointi juomaveden kloorifenolien terveysvaikutuksista]]
*[[:heande:Kuovesi]]
* [[:op_fi:Mikrobien määrä juomavedessä]]
* [[:op_fi:Mikrobien määrä pohjavedessä]]
*[[Bathing water guide]]


#cat("Pathogen concentration in the raw water\n")
* WHO: [https://apps.who.int/iris/bitstream/handle/10665/246195/9789241565370-eng.pdf?sequence=1 Quantitative Microbial Risk Assessment: Application for Water Safety Management]
#oprint(RaakaPitoisuus) # Patogeenien konsentraatio raakavedessä
*http://www.fao.org/docrep/006/y4666e/y4666e06.htm#TopOfPage
*http://wiki.camra.msu.edu/index.php?title=Main_Page
*http://www.medicina.fi/index.php?option=com_content&view=article&id=48&Itemid=56#I
* [http://en.opasnet.org/en-opwiki/index.php?title=Water_guide&oldid=43130#Answer Archived model version]:
** Split version: a corrected model 19.7.2019.
** Old version: The original 2012 version that was the starting point for development
** New version: An intermediate version with bugs
** Model run 12.7.2019 [http://en.opasnet.org/en-opwiki/index.php?title=Special:RTools&id=kNQ3D6fOLcfq08II]


#cat("Pathogen log reduction in the treatment\n")
=== Municipality-specific data ===
#oprint(MikrobienLogVähenemä)


temp2 <- Vaste@output
* Op_fi2603 [[:op_fi:Arviointi juomaveden laadun terveysvaikutuksista/Kuopio]] (vedenpuhdistamon tietoja)
temp2$VasteResult <- temp2$VasteResult * 1000
*[[:heande:Polaris:Raakaveden patogeenipitoisuudet/Lahti]]
cat("Probability of infection caused by water pathogens for an individual (per mille per day)\n")
*[[:heande:Polaris:Raakaveden patogeenipitoisuudet/Mikkeli]]
oprint(temp2[,c("Patogeeni", "VasteResult")], digits = 4) # Patogeeneille altistuminen ja infektion todennäköisyys (vaste)
*[[:heande:Polaris:Raakaveden patogeenipitoisuudet/Kirkkonummi]]
*[[:heande:Polaris:Paikkakuntakohtaiset tiedot talousveden käsittelyyn/Lahti]]
*[[:heande:Polaris:Paikkakuntakohtaiset tiedot talousveden käsittelyyn/Mikkeli]]
*[[:heande:Polaris:Paikkakuntakohtaiset tiedot talousveden käsittelyyn/Kirkkonummi]]
*[[:heande:Polaris:Juomaveden desinfiointi/Lahti]]
*[[:heande:Polaris:Juomaveden desinfiointi/Mikkeli]]
*[[:heande:Polaris:Juomaveden desinfiointi/Kirkkonummi]]
*[[:heande:Polaris:Vedenkäsittelyn tehokkuus/Lahti]]
*[[:heande:Polaris:Vedenkäsittelyn tehokkuus/Mikkeli]]
*[[:heande:Polaris:Vedenkäsittelyn tehokkuus/Kirkkonummi]]


cat("Estimated health impact\n")
==References==


cat(sum((1 - (1 - temp$P.ill.g.inf * temp$P.inf)^365) * Vaestonkoko, na.rm = TRUE), " gastroenterisis cases per year\n")
<references/>


cat(sum(Health.effects$DALYs, na.rm = TRUE), " DALYs because of gastroenteritis \n")   
{{eracedu}}
</rcode>

Latest revision as of 14:33, 23 March 2020


Water guide - An assessment of the health impacts of water quality addresses the potential microbiological health risks of drinking water. These microbiological risks are due to the contamination of raw water with microbes that cause potential health problems for people using tap water, as well as the efficiency of drinking water treatment, which can be insufficient for removing harmful microbes from drinking water. The assessment will be used to determine, how high the health risk is from certain microbes in raw water. The assessment is based on a mathematical Water guide -model, which can be found below.

Question

How to assess the microbiological risks of drinking water as well as their health effects? Information of water treatment plants must be possible to use as raw data.

Answer

Situation

Classification of raw water:

Size of the exposed population:

The amount (in liters) of unboiled tap water consumed per person per day:

Microbe concentrations of raw water

Campylobacter concentration (microbes/l):

E.coli O157:H7 concentration (microbes/l):

Rotavirus concentration (microbes/l):

Norovirus concentration (microbes/l):

Sapovirus concentration (microbes/l):

Cryptosporidium concentration (microbes/l):

Giardia concentration (microbes/l):

Water cleaning: Cleaning process and chlorination

Water cleaning methods in use:
Coagulation and flotation
Slow sand filtration
Limestone filtration
Active carbon filtration

Chlorine dose (mg/l):

Ozone dose (mg/l):

UV dose (mW/cm^2):

UV time (s):

+ Show code

The result page opens in a new tab by pressing the Run model -box. It will take approximately 40 seconds for the model to run, after which the results will appear on the result page.

User instructions for the Water guide -model


1. Choose classification of raw water

  • Ground water - Clean: clean ground water
  • Ground water - Surface water load: f.ex. shore infiltration
  • Surface water - Low load: relatively clean surface water
  • Surface water - Medium load: f.ex. low waste water load
  • Surface water - High load: f.ex. waste water load

OR

Choose 'I will determine microbe concentration by hand'. Write pathogen concentrations in their respective boxes.

2. State the concumption of drinking water per 24 h in liters per day per person (default 1.153 l/d).

3. State the population size of target area. (default 100000)

4. Choose treatment processes used. Obs! You can choose multiple options. If none of the first six treatment processes are used, choose "None of the above cleaning methods". If neither UV nor ozone is used, choose "None of the above disinfection methods".

5. Choose whether chlorination is used or not by giving the chlorine dose used (mg/l). If there is no chlorination, the dose will be 0 mg/l (default 0 mg/l). The model only calculates the effect of chlorine on the water in treatment plants, and ignores any further cleansing effects residual chlorine may have after the water moves onward to the pipe network.

6. You can see the results in a new tab by pressing 'Run model' This opens a new tab, in which the results will appear after the model is done running. This takes approximately 45 seconds.

Rationale

The model has been translated from Analytica to R. You can find the original model here (page in Finnish, link to the model code at the top): op_fi:Tiedosto:Vesiopas.ANA. If the user does not give concentrations for the pathogens, the values on page Pathogen concentrations in raw water will be used.

Health-based quality requirements and recommendations have been implanted on the quality of household water. In Finland, the ministry of social affairs and health is responsible for the legislation of the quality, and monitoring it is the responsibility of municipal health protection officials. Upholding and developing good water quality require high-standard research and cooperation between different parties. Ground waters and artificial ground waters are usually not disinfected. The chemicals and microbes in raw water and byproducts of disinfection produced in household water production can present health risks to the people using the household water. Water leaving the treatment plant can stay in the pipes for a long time. If the circumstances are favourable for microbial growth, the water can become low in quality and even detrimental to health while in the pipe network.

Household water is produced from either ground or surface water. The problems of these types of waters as raw water are different. Using surface water always requires establishing an actual treatment plant and the associated knowledge, skills, technologies and educated monitoring personnel. Ground water on the other hand doesn't require very complex treatment, so not many treatment plant personnel are needed, and there is less monitoring. Additionally today there are many treatment plants that produce artificial ground water. The qualities of artificial ground water can be similar to good ground waters, but the quality of the water is often only be equal to medium quality surface water.

Treatment of ground water usually includes increasing the pH and and hardness of water. This can be done using different techniques, of which the use of calcium hydroxide and carbon dioxide to regulate pH are the most common. Sometimes also precipitation of iron or manganese is required using strong oxidisers such as permanganate or chlorine. Low quality ground water is also disinfected.

In order to make surface water drinkable, it has to be heavily treated. The hardest thing is to precipitate the humus. This is done by using not only different precipitation chemicals, also for example adjust pH and breaking down the humus with strong oxidisers such as ozone. On top of that, the precipitated chemicals (such as salts of aluminium and iron) need to be removed and water hardness raised so that the pipelines don't disintegrate over time. Also, the population has to be protected from the microbes always present in surface waters, so the water needs to be disinfected to remove pathogens.

The quality of water is also affected by the condition of the pipelines and the water spends in them. If there is a lot of coagulation in the pipelines, these dregs include not only different inorganic compounds but also a large amout of bacterial mass. The coagulates in the pipelines and their qualities have started to be researched in Finland only recently.

The purpose of risk assessment is to produce information of the true size of the risk for decision-making. Risk assessment is a scientific process in which experts hold a key role. Because there are any kinds of risks to study, risk assessment processes can be very different. In environmental health risk assessment consists of four steps:

  1. Identifying the danger (does the variable researched pose a danger to humans?)
  2. Assessing the exposure-response function (how big a dose results in how big a response?)
  3. Assessing exposure (how much are humans exposed?)
  4. Characterising the risk (how high is the health risk?)[1]

All water treatment plants should periodically do risk assessment on on the household water they produce. It is done to identify actions to be taken in different crisis situations and prepare plans for different problematic situations and possible damage. Different treatment plants and for example vacation centers need different kinds of plans and implementations.

Dependencies

Pages containing the data and codes used by the model
Page What data or code the page has What is it used for Other observations
Op_en2949 Population of Finland Data on the age distribution of Finns Age distribution is used, because susceptibility to diseases and their severity changes with age. The burden of disease and cases of illness are calculated for each age group, then summed.
Op_en7956 Drinking water chlorination efficiency Log-decrease in pathogens due to chlorination, with different doses The code on this page uses the data on the page and user-given dose for chlorine to calculate the case-specific decrease in pathogens due to chlorination. This is summed with log-decrease of other treatment and disinfection methods to produce the total log-decrease in pathogens from water treatment. The model only takes into account any decrease in pathogens that happens in water treatment plants. Any further effect residual chlorine has after it enters the pipes is not included.
Op_en7955 Drinking water disinfection efficiency Log-decreases of pathogens due to ozonization and UV If the user has chosen one or both of these disinfection methods, the decrease from the chosen one(s) is summed with the decrease due to chlorination and other treatment methods to produce the total log-decrease in pathogens from water treatment. Currently the qualities of water, such as turbidity, are not taken into account in the efficiency of disinfection methods. The dose for both methods is also set.
Op_en7954; Drinking water treatment efficiency Log-decreases of pathogens due to different treatment methods. These methods are traditional cleaning, well working cleaning, enhanced cleaning, slow sand filtration, limestone filtration and active carbon filtration. If the user has chosen one of multiple of these treatment methods, the decrease of pathogens they produce is summed with the decreases due to chlorination and other disinfection methods to produce the total log-decrease in pathogens from water treatment.
Op_en7953 Pathogen concentrations in raw water The concentrations of pathogens of different raw water classes If the user has chosen one of the raw water classes, the amounts of pathogens in that class and the total log-decrease of pathogens from treatment are used to calculate the amount of pathogens left in drinking water. If the user has given pathogen concentrations by hand, those values are used instead of the data on this page.
Op_en7947 Case burden of waterborne microbes Case burdens of different pathogens, or how severe and long-lasting the diseases caused by them are This data is used to calculate the health detriments caused by the pathogens in drinking water.
Op_en7957 Health impacts of waterborne microbes Doesn't contain data, only code These codes use water consumption given by the user, total decrease in pathogens and the pathogen concentrations in raw water to calculate the exposure to pathogens experienced by one individual, or how many of each pathogen an individual swallows daily with drinking water.
Op_en7948 ERF of waterborne microbes Describes the exposure-response functions for the pathogens These functions tell, how likely an individual is to get sick with different exposures. This and the exposure are used to estimate the cases of illness.
Op_en2261 HIA Code that combines all of the above The code on the page uses exposure, exposure-response functions and the case burdens to calculate the total burdens caused by pathogens in drinking water. From here it is also possible to calculate the number of people getting ill from drinking water. These are the final results of the model.


Table of decisions used in drawing plotly graphs.

Decisions(-)
ObsDecisionOptionVariableCellChangeDescriptionResult
1AdjustGround - noneRawConcentrationRawWaterClass: Ground water - surface water contaminationRemove
2AdjustGround - noneRawConcentration

Well, this doesn't work at all.

Calculations

Initiate model

+ Show code

Plotly test

+ Show code

Another plotly test

+ Show code

Plotly with two sliders

+ Show code

See also

Municipality-specific data

References