% Cell 1
\begin{nbCell}
# Enter the Collected Data
years = [1860, 1880, 1890, 1900, 1920, 1931, 1940, 1950, 1960, 1970, 1980, 1989];
adoption = [1, 7, 13, 15, 20, 51, 60, 71, 87, 96, 98, 100];
\end{nbCell}

% Cell 2
\begin{nbCell}
# Define Solution to Bass Model
# Note: * F has output in [0, 1]
#       * independent var. t; params p, q 
function F(t, p, q)
    e = exp(-(p+q)*t)
    return (1 - e)/(1 + (q/p)*e)
end
\end{nbCell}

% Cell 3
\begin{nbCell}
# Transform Data
# Note: * The "." applies subtraction to each element of years
T = years .- 1860  # Shift data so 1860 is beginning of time 
Y = adoption / 100 # Rescale adoption to values in [0, 1]
\end{nbCell}

% Cell 4
\begin{nbCell}
# Compute square error sqErr
# Note: * vectors: T, Fpq, Y
#       * scalars: p, q, E
#       * input: (p, q) is a tuple; note double set of parens, see appendix
function sqErr((p, q))
    Fpq = F.(T, p, q) # Apply F to each element t_i in T with params p, q
    E = sum(Fpq.*Fpq - 2*Fpq.*Y + Y.*Y)
    return E
end
\end{nbCell}

% Cell 5
\begin{nbCell}
# Minimize the square error
# Note: * optimize takes a function with vector input
#       * initial guess: p = .25, q = .5
using Optim
results = optimize(sqErr, [0.25, .5])
\end{nbCell}

% Cell 6
\begin{nbCell}
# Extract minimizing parameters from results object
(pMin, qMin) = Optim.minimizer(results)
\end{nbCell}

% Cell 7
\begin{nbCell}
# Plot data and fitted model on same set of axes
# Note: * We mult F by 100 to scale to 0 - 100 interval
#       * plot! modifies current plot instead of overwriting 
using Plots
plot(years, adoption, label="Collected Data")
Ffit = F.(T, pMin, qMin) * 100  
plot!(years, Ffit, label="Fitted Bass Model",
    legend=:right, xlabel="Year", ylabel="Adoption %",
    title="Flushing Toilet Technology Adoption in Society")
\end{nbCell}
