#!/usr/bin/env python
#
# Data Quality Checker also known as DQC
#
# Read the README.md for more detailed information
#
#       Barcelona Supercomputing Center - Centro Nacional de Supercomputacion
#       Earth Sciences Department - Computational Earth Sciences
#
#     Authors:
#       Joan Sala Calero (joan.sala@bsc.es)
#       Jesus Pena Izquierdo (jesus.pena@bsc.es)

import numpy as np

"""
Producing a list of statistical estimators (on the data)
Stats needed for the boxplot
"""
def get_basic_stats(Min, Max, x, b):

    # Stats from histogram (more efficient, almost same result)
    q1, Med, q3 = quantiles_from_hist(b, x)
    IQR = q3 - q1

    return [Min, Max, Med, q1, q3, IQR]

"""
Get approximate statistical indicators from histogram
- This function computes the position of the quantiles given in the list quantiles.
- It linearly interpolates from the histogram to the corresponding values (i.e. no discretization issue)  
"""
def quantiles_from_hist(xm, nx, quantiles=[0.25, 0.5, 0.75]):

    dx = np.diff(xm)[0]  # xbin length
    N = np.sum(nx)  # total number of elements
    rx_cumsum = np.cumsum(nx) / N  # density distribution

    x_q = np.array([])
    for qi in quantiles:
        i_qi1 = np.argwhere(rx_cumsum > qi)[0].item()
        i_qi0 = i_qi1 - 1

        rx_qi0 = rx_cumsum[i_qi0]
        rx_qi1 = rx_cumsum[i_qi1]

        drx_qi01 = rx_qi1 - rx_qi0
        drx_qi = qi - rx_qi0
        k_drx_qi = drx_qi / drx_qi01

        x_qi = xm[i_qi0] + dx * (k_drx_qi + 1 / 2)
        x_q = np.append(x_q, x_qi)

    return x_q

