#!/usr/bin/python
#
# Autofocosing routines.
#
# You will need: scipy matplotlib sextractor
# This should work on Debian/ubuntu:
# sudo apt-get install python-matplotlib python-scipy python-pyfits sextractor
#
# If you would like to see sextractor results, get DS9 and pyds9:
#
# http://hea-www.harvard.edu/saord/ds9/
#
# Please be aware that current sextractor Ubuntu packages does not work
# properly. The best workaround is to install package, and the overwrite
# sextractor binary with one compiled from sources (so you will have access
# to sextractor configuration files, which program assumes).
#
# (C) 2002-2008 Stanislav Vitek
# (C) 2002-2010 Martin Jelinek
# (C) 2009-2010 Markus Wildi
# (C) 2010-2014 Petr Kubanek, Institute of Physics <kubanek@fzu.cz>
# (C) 2010      Francisco Forster Buron, Universidad de Chile
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

from rts2 import scriptcomm
from rts2 import sextractor
from scottSock import scottSock
sepPresent = False
try:
	import sep
	sepPresent = True
except Exception as ex:
	pass

import os
from pylab import *
from scipy import *
from scipy import optimize
import numpy
import pickle

LINEAR = 0
"""Linear fit"""
P2 = 1
"""Fit using 2 power polynomial"""
P4 = 2
"""Fit using 4 power polynomial"""
H3 = 3
"""Fit using general Hyperbola (three free parameters)"""
H2 = 4
"""Fit using Hyperbola with fixed slope at infinity (two free parameters)"""

class Focusing (scriptcomm.Rts2Comm):
	"""Take and process focussing data."""
	def getTriestmp(self, pathway="/home/rts2obs/rts2images"):
		focusfiles = [x for x in os.listdir(pathway) if "foc" in x]
		tries = {}
		for f in focusfiles:
			num = f.split('_')[2].split(".")[0]
			tries[float(num)] = f

		return tries
 
	def __init__(self,exptime = 10,step=20,attempts=10,filterGalaxies=False):
		scriptcomm.Rts2Comm.__init__(self)
		self.log('I', 'This is a test')
		self.exptime = exptime
		self.step = step
		self.focuser = "F0"
		self.attempts = attempts

		# if |offset| is above this value, try linear fit
		self.linear_fit = self.step * self.attempts / 2.0
		# target FWHM for linear fit
		self.linear_fit_fwhm = 3.5
		self.filterGalaxies = filterGalaxies

	def doFit(self,fit):
		b = None
		errfunc = None
		fitfunc_r = None
		p0 = None

		# try to fit..
		# this function is for flux.. 
		#fitfunc = lambda p, x: p[0] * p[4] / (p[4] + p[3] * (abs(x - p[1])) ** (p[2]))

		# prepare fit based on its type..
		if fit == LINEAR:
			fitfunc = lambda p, x: p[0] + p[1] * x
			errfunc = lambda p, x, y: fitfunc(p, x) - y # LINEAR - distance to the target function
			p0 = [1, 1]
			fitfunc_r = lambda x, p0, p1: p0 + p1 * x
		elif fit == P2:
			fitfunc = lambda p, x: p[0] + p[1] * x + p[2] * (x ** 2)
			errfunc = lambda p, x, y: fitfunc(p, x) - y # P2 - distance to the target function