#!/usr/bin/python
#
# rescaleData.py
#

import sys
import FEL_INPUT
import FEL_OUTPUT

import data_statistics as D  # previously generated by reportStatistics.py


def rescale(array, mean, stddev):
  for j in range(len(array)):
    row = array[j]
    for i in range(len(row)):
      value = row[i]
      scaledValue = (value - mean[i]) / stddev[i]
      row[i] = scaledValue
    array[j] = row
  return array



def write_array(file, array, name):
  file.write(name + " = numpy.array([\n")
  for row in array:
    file.write("  [ ")
    for value in row:
      file.write(str(value) + ", ")
    file.write("], \\\n")
  file.write("])\n\n")


def readStatisticsFile(file):
  input_mins = []
  input_maxs = []
  output_mins = []
  output_maxs = []
  for line in file:
    words = line.strip().split(' ')
    if len(words) != 5: continue
    if words[1] == 'min':
      if words[0].startswith('input'):
        input_mins.append(float(words[2]))
        input_maxs.append(float(words[4]))
      else:
        output_mins.append(float(words[2]))
        output_maxs.append(float(words[4]))
  return min(input_mins[0], input_mins[1]), max(input_maxs[0], input_maxs[1]), min(output_mins[0], output_mins[1]), max(output_maxs[0], output_maxs[1])


def findRange(array):
  minx = 9999999
  maxx = -minx
  for row in array:
    for value in row:
      minx = min(minx, value)
      maxx = max(maxx, value)
  return minx, maxx



fel_input = open("FEL_INPUT_SCALED.py", "w")
fel_input.write("import numpy\n")
fel_output = open("FEL_OUTPUT_SCALED.py", "w")
fel_output.write("import numpy\n")

fel_input.write("fields = " + str(FEL_INPUT.fields) + "\n\n")
fel_output.write("fields = " + str(FEL_INPUT.fields) + "\n\n")

train_x = rescale(FEL_INPUT.train_x, D.total_input_mean, D.total_input_stddev)
write_array(fel_input, train_x, "train_x")
train_y = rescale(FEL_OUTPUT.train_y, D.total_output_mean, D.total_output_stddev)
write_array(fel_output, train_y, "train_y")
test_x = rescale(FEL_INPUT.test_x, D.total_input_mean, D.total_input_stddev)
write_array(fel_input, test_x, "test_x")
test_y = rescale(FEL_OUTPUT.test_y, D.total_output_mean, D.total_output_stddev)
write_array(fel_output, test_y, "test_y")

fel_input.close()
fel_output.close()

