dir_roaming    = '/home/ckirst/Science/Projects/CElegans/Analysis/Roaming/Code'
dir_behaviour  = '/home/ckirst/Science/Projects/CElegans/Analysis/WormBehaviour/Code/'


os.chdir(dir_roaming);
import experiment as rexp

os.chdir(dir_behaviour);
import analysis.experiment as exp

fig_directory = '/home/ckirst/Science/Projects/CElegans/Analysis/WormBehaviour/Figures/StageDetection/'

import scripts.preprocessing.filenames as fn
strain = 'tph1'
nworms, exp_names, dir_names = fn.filenames(strain);

import analysis.plot as fplt;

import signalprocessing.peak_detection as pd
import scipy.signal as sig

def average(x, nbins):
  """Bin data using nbins windows"""
  n = len(x); 
  nm = n/nbins * nbins;
  x_mean = x[:nm];
  x_mean = x_mean.reshape([nm/nbins, nbins]);
  x_mean = np.nanmean(x_mean, axis = 1);
  x_mean = np.hstack([x_mean, [np.nanmean(x[nm:])]]);
  return x_mean;
"""

import os
import numpy as np

import matplotlib.pyplot as plt

import analysis.experiment as exp
import scripts.preprocessing.filenames as fn

#strain = 'daf7';
strain = 'n2'
strain = 'cat2'
strain = 'tdc1'

nworms, exp_names, dir_names = fn.filenames(strain=strain)

#%% Load Plate Images

import scipy.io
import glob


def find_plate(strain, wid=0, verbose=True, save=None, thresholds=[160, 175]):

    fns = np.sort(
        np.unique(glob.glob(os.path.join(dir_names[wid], 'Traj*.mat'))))
    img_plate = scipy.io.loadmat(fns[-1])['Trace']
    xy = exp.load(strain=strain, wid=wid, dtype='xy')

    ### Detect circles