import pandas as pd
import numpy as np
from numpy import genfromtxt


def read_data(data_file):
    data = genfromtxt(data_file, delimiter=',')
    points = data[:, 1:3]
    temps = data[:, 3:]
    return points, temps


def add_power_spped(power, speed, points):
    powers = power * np.ones(points.shape[0])
    speeds = speed * np.ones(points.shape[0])
    points = np.append(points, powers.reshape(points.shape[0], 1), axis=1)
    points = np.append(points, speeds.reshape(points.shape[0], 1), axis=1)
    return points


def normalize_temps(temps):
    temps_mean = np.zeros(100)
    temps_std = np.zeros(100)
    for i in range(100):
        temps_mean[i] = temps[:,i].mean()
        temps_std[i] = temps[:,i].std()
        if temps_std[i] == 0:
            temps[:,i] = temps[:,i] - temps_mean[i]
        else:
            temps[:,i] = (temps[:,i] - temps_mean[i]) / temps_std[i]
    return temps, temps_mean, temps_std


def normalize_points(points, type = 'multi'):
    points_mean = np.zeros(points.shape[1])
    points_std = np.zeros(points.shape[1])
    # Normalizing the points
    if type == 'multi':
        for i in range(points.shape[1]):
            points_mean[i] = points[:, i].mean()
            points_std[i] = points[:, i].std()
            points[:, i] = (points[:, i] - points_mean[i]) / points_std[i]
        return points, points_mean, points_std
    else:
        for i in range(points.shape[1] - 2):
            points_mean[i] = points[:, i].mean()
            points_std[i] = points[:, i].std()
            points[:, i] = (points[:, i] - points_mean[i]) / points_std[i]
        return points, points_mean, points_std


def normalize_data(points, temps):
    temps, temps_mean, temps_std = normalize_temps(temps=temps)
    points, points_mean, points_std = normalize_points(points=points)
    return points, temps

# Example:
data_path = 'T__2_q260_v1300_data.csv'
power = 260
speed = 1300
points, temps = read_data(data_file=data_path)
points = add_power_spped(power=power, speed=speed, points=points)
