# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python [conda env:ts-rasterv2]
#     language: python
#     name: conda-env-ts-rasterv2-py
# ---
# ## Feature extraction
# This documents show how to extract important timeseries charcterstics from raster files.
# +
import os.path
import matplotlib.pyplot as plt
# %matplotlib inline
from rasterio.plot import show
import tsraster
import tsraster.prep as tr
from tsraster.calculate import calculateFeatures
from tsraster.calculate import features_to_array
# -
# connect to the data directory
path = "../docs/img/temperature/"
# read the images and convert the arrays to a time-series dataframe 
rasters = tr.image_to_series(path)
# Lets take a look at the time-series data
rasters.head(10)
# Accordingly, each pixel is identified by *id*. Since there are 9 bands (3 images per year), **tsraster** assigns each 9 first pixels the id number 1 and differentiate each by their respective year and month. Hence, the *time* column organizes and orders pixels by time. The *value* column represent the pixel value
# We can summerize the data and examine its pattern.
rasters.describe()
# Let's go ahead and extract features
# +
fc_parameters = {
    "mean": None,
    "maximum": None,
    "minimum":None,
    # example: pass multiple calls 
    "quantile":[{"q": 0.15}, {"q": 0.95}]
}

ts_features = calculateFeatures(path,
                                parameters=fc_parameters, 
                                reset_df=True)
# -
# The feature extraction swift through all bands and calculate values such maximum, minimum and mean, median. 
# In this instance, 4 features of temprature data are generated for 9 rasters representing 3 months of 3 years of data.
# Let's take a look at the summary of these features.
ts_features.describe()
# Next, convert these features to array, visualize or create a tiff
# +
# first, get the original dimension/shape of image 
og_rasters = tr.image_to_array(path)
rows, cols, nums = og_rasters.shape

# convert df to matrix array
matrix_features = ts_features.values
num_of_layers = matrix_features.shape[1]

f2Array = matrix_features.reshape(rows, cols, num_of_layers)
print(f2Array.shape)
# -
# visualize features
# +
fig, ax = plt.subplots(2,2,figsize=(16,10))
for i in range(0,f2Array.shape[2]):
    img = f2Array[:,:,i]
    i = i+1
    plt.subplot(1,5,i)
    plt.imshow(img, cmap="Greys")
# -