#!/usr/bin/env python

from embodied_ising import ising
from embodied_ising import food
from embodied_ising import CriticalLearning
import numpy as np
import matplotlib.pyplot as plt
from sys import argv

import pickle

# --- CONSTANTS ----------------------------------------------------------------+
settings = {}

# ENVIRONMENT SETTINGS
settings['pop_size'] = 50  # number of organisms
settings['numKill'] = int(settings['pop_size'] / 1.66)
settings['food_num'] = 100  # number of food particles
settings['food_radius'] = 0.03
settings['org_radius'] = 0.05

# SIMULATION SETTINGS
settings['TimeSteps'] = 5000  # number of timesteps for dh, dJ calculations
settings['evolution_rate'] = 1e10  # number of generations to skip to kill/mate

settings['dt'] = 0.04  # simulation time step      (dt)
settings['dr_max'] = 90  # max rotational speed      (degrees per second)
settings['v_max'] = 0.5  # max velocity              (units per second)
settings['dv_max'] = 0.05  # max acceleration (+/-)    (units per second^2)

settings['x_min'] = -4.0  # arena eastern border
settings['x_max'] = 4.0  # arena western border
settings['y_min'] = -4.0  # arena southern border
settings['y_max'] = 4.0  # arena northern border

settings['save_data'] = True
settings['plot'] = False  # plot final generation?
settings['TimeStepsGrowth'] = 9999  # increases TimeSteps for N iterations, if 'plot' = False, turn 'True' after some
# iterations. Also begins saving figures after this many iterations if 'plot' setting is 'False'
settings['plotLive'] = False  # live updates of figures
settings['frameSkip'] = 5

settings['size'] = 27
settings['nSensors'] = 3
settings['nMotors'] = 4
settings['learningrate'] = 0.01  # 0.01
# how many hidden neurons are not connected to each other
settings['numDisconnectedNeurons'] = int((settings['size'] - settings['nSensors'] - settings['nMotors']) / 1.2)
# how should organisms repopulate, duplicate or mate?
settings['mateDupRatio'] = 0.5

settings['LoadIsings'] = False
settings['loadfile'] = 'sim-20180130-051810'
settings['iter'] = '114'

Iterations = 1003


# --- MAIN ---------------------------------------------------------------------+

def run(settings):
    size = settings['size']
    nSensors = settings['nSensors']
    nMotors = settings['nMotors']
    # LOAD ISING CORRELATIONS
    # filename = 'correlations-ising2D-size400.npy'
    filename2 = 'correlations-ising-generalized-size83.npy'
    settings['Cdist'] = np.load(filename2)

    # --- POPULATE THE ENVIRONMENT WITH FOOD ---------------+
    foods = []
    for i in range(0, settings['food_num']):
        foods.append(food(settings))

    # --- POPULATE THE ENVIRONMENT WITH ORGANISMS ----------+
    if settings['LoadIsings']:
        loadfile = 'save/' + settings['loadfile'] + '/isings/gen[' + settings['iter'] + ']-isings.pickle'
        startstr = 'Loading simulation:' + loadfile + ' (' + str(settings['TimeSteps']) + \
                   ' timesteps) x (' + str(Iterations) + ' iterations)'
        print(startstr)
        isings = pickle.load(open(loadfile, 'rb'))
    else:
        startstr = 'Starting simulation: (' + str(settings['TimeSteps']) + \
                   ' timesteps) x (' + str(Iterations) + ' iterations)'
        print(startstr)
        isings = []
        for i in range(0, settings['pop_size']):
            isings.append(ising(settings, size, nSensors, nMotors, name='gen[0]-org[' + str(i) + ']'))

    # --- CYCLE THROUGH EACH GENERATION --------------------+
    CriticalLearning(isings, foods, settings, Iterations)

    pass


# --- RUN ----------------------------------------------------------------------+

run(settings)

# --- END ----------------------------------------------------------------------+
