import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from prosail_functions import *
plot_config()


def hspot ( h ):
    retval = []
    wv = np.arange(400, 2501)
    for theta_v in np.arange ( -80,80, 5):
        if theta_v < 0:
            raa = -180
            t = -theta_v
        else:
            raa = 0
            t = theta_v
        r = call_prosail ( 1.5, 45, 4, 0.1, 0.0143, 0.007, 4, 45, 4, 
                 1, h, 30, t, raa )[wv==865]
        retval.append ( r )
    return np.arange ( -80,80, 5), np.array(retval).squeeze()


plt.figure(figsize=(12,12))
x,y = hspot(0.01)

plt.plot(x,y,'-', label="0.01")
x,y = hspot(0.1)
plt.plot(x,y,'-', label="0.1")
x,y = hspot(0.5)
plt.plot(x,y,'-', label="0.5")
x,y = hspot(1)
plt.plot(x,y,'-', label="1")


plt.legend(loc='best')
pretty_axes()

w,s = prosail_sensitivity_ssa(x0=np.array([  2.5  ,  40.   ,   5.   ,   0.   ,   0.011,   0.005,   0.5  ,
        45.   ,   3.   ,   0.5   ,   0.01 ]))
plt.xlim ( 650, 890)

w,s = prosail_sensitivity_ssa(x0=np.array([  2.5  ,  40.   ,   5.   ,   0.   ,   0.011,   0.005,   8  ,
        45.   ,   3.   ,   0.5   ,   0.01 ]))
plt.xlim ( 650, 890)

w,s = prosail_sensitivity_ssa

"""
Explanation: Exploring a canopy RT model: PROSAIL
J Gómez-Dans (UCL & NCEO)
This implementation of PROSAIL
There are quite a few different versions of the SAIL model. This is probably the second simplest, as it assumes a single canopy layer, with a simple hotspot correction. The soil boundary is assumed to be Lambertian, and a combination of two soil spectra (typically one wet and one dry). Leaf optical properties are calculated with PROSPECT 5B (which you should already be familiar with). In total, we have 11 input parameters (as well as the illumination/acquisition geometry, controlled by the solar zenith angle, the view zenith angle and the relative azimuth angle). The input parameters are

$N$ (leaf layers)
$Cab$ (chlorophyll ab conc)
$Car$ (carotenoid conc)
$Cbrown$ (senescent pigment
$Cw$ (equivalent leaf water)
$Cm$ (dry matter conc)
LAI (leaf area index)
LIDF (the mean leaf angle)
RSOIL (soil brightness term)
PSOIL (soil moisture factor: 0 wet, 1 dry)
HOTSPOT (the value of the hotspot parameter, typically the ratio of leave size to canopy height)

The soil is assumed Lambertian, and made up of the linear combination of two spectra, $\rho_{s}^{d}$ and $\rho_{s}^{w}$, dry and wet, respectively. The soil spectrum is calculated as
$$
\rho_{s}=R\cdot\left(P\cdot\rho_{s}^{d} + \left(1-P\right)\cdot \rho_{s}^{w}\right).
$$
This version of PROSAIL uses a Campbell leaf angle distribution function. Rather than choosing discrete distributions, the Campbell function parameterises the LAD function with a single parameter, the mean leaf angle.
Sensitivity analysis
The aim of this exercise is to look at the sensitivity of PROSAIL to different parametes spectrally, in a way that is similar to what you did before with PROSPECT. Remember that this experiment is still a local sensitivity analysis experiment around $\mathbf{x_0}$, so make sure you consider different locations in parameter space. Also consider the effect of acquisition geometry.
You can use the function prosail_sensitivity_ssa, from prosail_functions. Remember that this function has extensive help on its syntax.

Where do parameters show the most/the least sensitivity spectrally?
Where do these sensitivities change with acquisition geometry?
End of explanation
"""


x,r,n = canopy_vi_expt( nuisance=["lai", "cab", "n", "cw"])


"""
Explanation: A trip to RED/NIR space
Perhaps the first thing you've heard about optical remote sensing is about the use of $NDVI$, the normalised difference vegetation index. This index has a long history in remote sensing, and one could say that it is broadly related to the amount of green vegetation. $NDVI$ is calculated using the red and NIR bands (typically, wavelenghts around 680 and 865 nm):
$$
NDVI=\frac{NIR-RED}{NIR+RED}.
$$
As it is a normalised quantity, NDVI goes between -1 and 1, but for vegetation, we usually find that it goes from $\sim$ 0.2 to 0.9.


$NDVI$ has been correlated to most things. Based on the sensitivity analysis you performed above, can you suggest some of these correlates?


$NDVI$ is often used as a proxy for LAI. You can use the provided function to explore the relationship beween the VI and LAI. What are your observations?

You can set a number of extra nuisance parameters to vary randomly. Discuss how the value of these different parameters affects the value of the calculated NDVI, and how it affects your retrieval of e.g. LAI. Relate this to your sensitivity analysis.
You can also change the soil brightness term. What do you observe? Can you explain the physics that give rise to what you observe?
Consider the SAVI index (Soil Adjusted Vegetation Index) $ SAVI = (1-L)\cdot(NIR - RED)/(NIR+RED+L)$, where $L=0.5$
What is the role of $L$?
End of explanation
"""


plt.figure(figsize=(12,12))

x, y, p0, p1 = mtci_experiment(nuisance=["lai","cw"])


x, y, p0, p1 = mtci_experiment

x, y, p0, p1 = mtci_experiment

from IPython.core.display import HTML

def css_styling():
    styles = open("custom.css", "r").read()
    return HTML(styles)
css_styling()

"""
Explanation: Exploring the MTCI (MERIS Terrestrial Chlorophyll Index)
The MTCI is a vegetation index that was developed for data from the MERIS sensor onboard the ENVISAT platform, and that relates surface reflectance to canopy chlorophyll content. The index is defined as the ratio of reflectance differences between MERIS bands 10 and 9 to reflectance differences between bands 9 and 8. 
$$
MTCI = \frac{R_{753}-R_{705}}{R_{705}-R_{681}},
$$
where $R_{x}$ indicated reflectance for a waveband whose centre wavelength is located at $x$. In this experiment, we will use PROSAIL to look at the robustness of such an index. We note that the bandwidth of these three bands is 7.5, 10 and 7.5 $nm$.

A first experiment will be to determine the strength of the relationship just sweeping over the chlorophyll concentration while keeping all other parameters fixed. Try different regions of parameters space (e.g. set x0 to some other value).
As a second experiment, add some nuisance parameters: e.g. add a random variation variation to other parameters other than $C_{ab}$. The variation in this parameters is controlled by the minvals and maxvals dictionaries. Comment on the results, and in particular, in the robustness of the regression.
A third experiment will also add some noise using the noise_level parameters. We can assume that noise_level is the standard deviation of some additive Gaussian noise. Values of 0.01 are probably optimistic for the type of atmospheric correction we typically get.
Finally, observe the changes in the $MTCI-C_{ab}$ relationship for different acquisition geometries.
End of explanation
"""


