|
| 1 | +#!/usr/bin/python |
| 2 | +# |
| 3 | +# Autofocosing routines. |
| 4 | +# |
| 5 | +# You will need: scipy matplotlib sextractor |
| 6 | +# This should work on Debian/ubuntu: |
| 7 | +# sudo apt-get install python-matplotlib python-scipy python-pyfits sextractor |
| 8 | +# |
| 9 | +# If you would like to see sextractor results, get DS9 and pyds9: |
| 10 | +# |
| 11 | +# http://hea-www.harvard.edu/saord/ds9/ |
| 12 | +# |
| 13 | +# Please be aware that current sextractor Ubuntu packages does not work |
| 14 | +# properly. The best workaround is to install package, and the overwrite |
| 15 | +# sextractor binary with one compiled from sources (so you will have access |
| 16 | +# to sextractor configuration files, which program assumes). |
| 17 | +# |
| 18 | +# (C) 2002-2008 Stanislav Vitek |
| 19 | +# (C) 2002-2010 Martin Jelinek |
| 20 | +# (C) 2009-2010 Markus Wildi |
| 21 | +# (C) 2010-2014 Petr Kubanek, Institute of Physics <kubanek@fzu.cz> |
| 22 | +# (C) 2010 Francisco Forster Buron, Universidad de Chile |
| 23 | +# |
| 24 | +# This program is free software; you can redistribute it and/or |
| 25 | +# modify it under the terms of the GNU General Public License |
| 26 | +# as published by the Free Software Foundation; either version 2 |
| 27 | +# of the License, or (at your option) any later version. |
| 28 | +# |
| 29 | +# This program is distributed in the hope that it will be useful, |
| 30 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 31 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 32 | +# GNU General Public License for more details. |
| 33 | +# |
| 34 | +# You should have received a copy of the GNU General Public License |
| 35 | +# along with this program; if not, write to the Free Software |
| 36 | +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
| 37 | + |
| 38 | +from rts2 import scriptcomm |
| 39 | +from rts2 import sextractor |
| 40 | +from scottSock import scottSock |
| 41 | +sepPresent = False |
| 42 | +try: |
| 43 | + import sep |
| 44 | + sepPresent = True |
| 45 | +except Exception as ex: |
| 46 | + pass |
| 47 | + |
| 48 | +import os |
| 49 | +from pylab import * |
| 50 | +from scipy import * |
| 51 | +from scipy import optimize |
| 52 | +import numpy |
| 53 | +import pickle |
| 54 | + |
| 55 | +LINEAR = 0 |
| 56 | +"""Linear fit""" |
| 57 | +P2 = 1 |
| 58 | +"""Fit using 2 power polynomial""" |
| 59 | +P4 = 2 |
| 60 | +"""Fit using 4 power polynomial""" |
| 61 | +H3 = 3 |
| 62 | +"""Fit using general Hyperbola (three free parameters)""" |
| 63 | +H2 = 4 |
| 64 | +"""Fit using Hyperbola with fixed slope at infinity (two free parameters)""" |
| 65 | + |
| 66 | +class Focusing (scriptcomm.Rts2Comm): |
| 67 | + """Take and process focussing data.""" |
| 68 | + def getTriestmp(self, pathway="/home/rts2obs/rts2images"): |
| 69 | + focusfiles = [x for x in os.listdir(pathway) if "foc" in x] |
| 70 | + tries = {} |
| 71 | + for f in focusfiles: |
| 72 | + num = f.split('_')[2].split(".")[0] |
| 73 | + tries[float(num)] = f |
| 74 | + |
| 75 | + return tries |
| 76 | + |
| 77 | + def __init__(self,exptime = 10,step=20,attempts=10,filterGalaxies=False): |
| 78 | + scriptcomm.Rts2Comm.__init__(self) |
| 79 | + self.log('I', 'This is a test') |
| 80 | + self.exptime = exptime |
| 81 | + self.step = step |
| 82 | + self.focuser = "F0" |
| 83 | + self.attempts = attempts |
| 84 | + |
| 85 | + # if |offset| is above this value, try linear fit |
| 86 | + self.linear_fit = self.step * self.attempts / 2.0 |
| 87 | + # target FWHM for linear fit |
| 88 | + self.linear_fit_fwhm = 3.5 |
| 89 | + self.filterGalaxies = filterGalaxies |
| 90 | + |
| 91 | + def doFit(self,fit): |
| 92 | + b = None |
| 93 | + errfunc = None |
| 94 | + fitfunc_r = None |
| 95 | + p0 = None |
| 96 | + |
| 97 | + # try to fit.. |
| 98 | + # this function is for flux.. |
| 99 | + #fitfunc = lambda p, x: p[0] * p[4] / (p[4] + p[3] * (abs(x - p[1])) ** (p[2])) |
| 100 | + |
| 101 | + # prepare fit based on its type.. |
| 102 | + if fit == LINEAR: |
| 103 | + fitfunc = lambda p, x: p[0] + p[1] * x |
| 104 | + errfunc = lambda p, x, y: fitfunc(p, x) - y # LINEAR - distance to the target function |
| 105 | + p0 = [1, 1] |
| 106 | + fitfunc_r = lambda x, p0, p1: p0 + p1 * x |
| 107 | + elif fit == P2: |
| 108 | + fitfunc = lambda p, x: p[0] + p[1] * x + p[2] * (x ** 2) |
| 109 | + errfunc = lambda p, x, y: fitfunc(p, x) - y # P2 - distance to the target function |
| 110 | + p0 = [1, 1, 1] |
| 111 | + fitfunc_r = lambda x, p0, p1, p2 : p0 + p1 * x + p2 * (x ** 2) |
| 112 | + elif fit == P4: |
| 113 | + fitfunc = lambda p, x: p[0] + p[1] * x + p[2] * (x ** 2) + p[3] * (x ** 3) + p[4] * (x ** 4) |
| 114 | + errfunc = lambda p, x, y: fitfunc(p, x) - y # P4 - distance to the target function |
| 115 | + p0 = [1, 1, 1, 1, 1] |
| 116 | + fitfunc_r = lambda x, p0, p1: p0 + p1 * x + p2 * (x ** 2) + p3 * (x ** 3) + p4 * (x ** 4) |
| 117 | + elif fit == H3: |
| 118 | + fitfunc = lambda p, x: sqrt(p[0] ** 2 + p[1] ** 2 * (x - p[2])**2) |
| 119 | + errfunc = lambda p, x, y: fitfunc(p, x) - y # H3 - distance to the target function |
| 120 | + p0 = [400., 3.46407715307, self.fwhm_MinimumX] # initial guess based on real data |
| 121 | + fitfunc_r = lambda x, p0, p1, p2 : sqrt(p0 ** 2 + p1 ** 2 * (x - p2) ** 2) |
| 122 | + elif fit == H2: |
| 123 | + fitfunc = lambda p, x: sqrt(p[0] ** 2 + 3.46407715307 ** 2 * (x - p[1])**2) # 3.46 based on H3 fits |
| 124 | + errfunc = lambda p, x, y: fitfunc(p, x) - y # H2 - distance to the target function |
| 125 | + p0 = [400., self.fwhm_MinimumX] # initial guess based on real data |
| 126 | + fitfunc_r = lambda x, p0, p1 : sqrt(p0 ** 2 + 3.46407715307 ** 2 * (x - p1) ** 2) |
| 127 | + else: |
| 128 | + raise Exception('Unknow fit type {0}'.format(fit)) |
| 129 | + |
| 130 | + self.fwhm_poly, success = optimize.leastsq(errfunc, p0[:], args=(self.focpos, self.fwhm)) |
| 131 | + |
| 132 | + b = None |
| 133 | + |
| 134 | + if fit == LINEAR: |
| 135 | + b = (self.linear_fit_fwhm - self.fwhm_poly[0]) / self.fwhm_poly[1] |
| 136 | + elif fit == H3: |
| 137 | + b = self.fwhm_poly[2] |
| 138 | + self.log('I', 'found minimum FWHM: {0}'.format(abs(self.fwhm_poly[0]))) |
| 139 | + self.log('I', 'found slope at infinity: {0}'.format(abs(self.fwhm_poly[1]))) |
| 140 | + elif fit == H2: |
| 141 | + b = self.fwhm_poly[1] |
| 142 | + self.log('I', 'found minimum FWHM: {0}'.format(abs(self.fwhm_poly[0]))) |
| 143 | + else: |
| 144 | + b = optimize.fmin(fitfunc_r,self.fwhm_MinimumX,args=(self.fwhm_poly), disp=0)[0] |
| 145 | + self.log('I', 'found FWHM minimum at offset {0}'.format(b)) |
| 146 | + return b |
| 147 | + |
| 148 | + def tryFit(self,defaultFit): |
| 149 | + """Try fit, change to linear fit if outside allowed range.""" |
| 150 | + b = self.doFit(defaultFit) |
| 151 | + if (abs(b - numpy.average(self.focpos)) >= self.linear_fit): |
| 152 | + self.log('W','cannot do find best FWHM inside limits, trying H2 fit - best fit is {0}, average focuser position is {1}'.format(b, numpy.average(self.focpos))) |
| 153 | + b = self.doFit(H2) |
| 154 | + if (abs(b - numpy.average(self.focpos)) >= self.linear_fit): |
| 155 | + self.log('W','cannot do find best FWHM inside limits, trying linear fit - best fit is {0}, average focuser position is {1}'.format(b, numpy.average(self.focpos))) |
| 156 | + b = self.doFit(LINEAR) |
| 157 | + return b,LINEAR |
| 158 | + return b,H2 |
| 159 | + return b,defaultFit |
| 160 | + |
| 161 | + |
| 162 | + def doFitOnArrays(self,fwhm,focpos,defaultFit): |
| 163 | + self.fwhm = array(fwhm) |
| 164 | + self.focpos = array(focpos) |
| 165 | + self.fwhm_MinimumX = 0 |
| 166 | + min_fwhm=fwhm[0] |
| 167 | + for x in range(0,len(fwhm)): |
| 168 | + if fwhm[x] < min_fwhm: |
| 169 | + self.fwhm_MinimumX = x |
| 170 | + min_fwhm = fwhm[x] |
| 171 | + return self.tryFit(defaultFit) |
| 172 | + |
| 173 | + def findBestFWHM(self,tries,defaultFit=P2,min_stars=95,ds9display=False,threshold=2.7,deblendmin=0.03): |
| 174 | + # X is FWHM, Y is offset value |
| 175 | + self.focpos=[] |
| 176 | + self.fwhm=[] |
| 177 | + fwhm_min = None |
| 178 | + self.fwhm_MinimumX = None |
| 179 | + keys = list(tries.keys()) |
| 180 | + keys.sort() |
| 181 | + sextr = sextractor.Sextractor(threshold=threshold,deblendmin=deblendmin) |
| 182 | + for k in keys: |
| 183 | + try: |
| 184 | + sextr.runSExtractor(tries[k]) |
| 185 | + fwhm,fwhms,nstars = sextr.calculate_FWHM(min_stars,self.filterGalaxies) |
| 186 | + except Exception as ex: |
| 187 | + self.log('W','offset {0}: {1}'.format(k,ex)) |
| 188 | + continue |
| 189 | + self.log('I','offset {0} fwhm {1} with {2} stars'.format(k,fwhm,nstars)) |
| 190 | + focpos.append(k) |
| 191 | + fwhm.append(fwhm) |
| 192 | + if (fwhm_min is None or fwhm < fwhm_min): |
| 193 | + fwhm_MinimumX = k |
| 194 | + fwhm_min = fwhm |
| 195 | + return focpos,fwhm,fwhm_min,fwhm_MinimumX |
| 196 | + |
| 197 | + def __sepFindFWHM(self,tries): |
| 198 | + from astropy.io import fits |
| 199 | + import math |
| 200 | + import traceback |
| 201 | + focpos=[] |
| 202 | + fwhm=[] |
| 203 | + fwhm_min=None |
| 204 | + fwhm_MinimumX=None |
| 205 | + keys = list(tries.keys()) |
| 206 | + keys.sort() |
| 207 | + ln2=math.log(2) |
| 208 | + for k in keys: |
| 209 | + try: |
| 210 | + fwhms=[] |
| 211 | + ff=fits.open(tries[k]) |
| 212 | + # loop on images.. |
| 213 | + for i in range(1,len(ff)-1): |
| 214 | + data=ff[i].data |
| 215 | + bkg=sep.Background(numpy.array(data,numpy.float)) |
| 216 | + sources=sep.extract(data-bkg, 5.0 * bkg.globalrms) |
| 217 | + self.log('I','bkg gobalrms {}'.format(bkg.globalrms)) |
| 218 | + |
| 219 | + for s in sources: |
| 220 | + fwhms.append(2 * math.sqrt(ln2 * (s[15]**2 + s[16]**2))) |
| 221 | + |
| 222 | + |
| 223 | + im_fwhm=numpy.median(fwhms) |
| 224 | + # find median from fwhms measurements.. |
| 225 | + |
| 226 | + self.log('I','median fwhm {}'.format(numpy.median(fwhms))) |
| 227 | + self.log('I','offset {0} fwhm {1} with {2} stars'.format(k,im_fwhm,len(fwhms))) |
| 228 | + focpos.append(k) |
| 229 | + fwhm.append(im_fwhm) |
| 230 | + if (fwhm_min is None or im_fwhm < fwhm_min): |
| 231 | + fwhm_MinimumX = k |
| 232 | + fwhm_min = im_fwhm |
| 233 | + except Exception as ex: |
| 234 | + self.log('W','offset {0}: {1} {2}'.format(k,ex,traceback.format_exc())) |
| 235 | + |
| 236 | + self.log('I','pickling') |
| 237 | + fd = open( "rts2.pkl", 'w' ) |
| 238 | + pickle.dump(sources, fd) |
| 239 | + fd.close() |
| 240 | + return focpos,fwhm,fwhm_min,fwhm_MinimumX |
| 241 | + |
| 242 | + |
| 243 | + def findBestFWHM(self,tries,defaultFit=H3,min_stars=15,ds9display=False,threshold=2.7,deblendmin=0.03): |
| 244 | + # X is FWHM, Y is offset value |
| 245 | + self.focpos=[] |
| 246 | + self.fwhm=[] |
| 247 | + self.fwhm_min = None |
| 248 | + self.fwhm_MinimumX = None |
| 249 | + if sepPresent: |
| 250 | + self.focpos,self.fwhm,self.fwhm_min,self.fwhm_MinimumX = self.__sepFindFWHM(tries) |
| 251 | + else: |
| 252 | + self.focpos,self.fwhm,self.fwhm_min,self.fwhm_MinimumX = self.__sexFindFWHM(tries,threshold,deblendmin) |
| 253 | + self.focpos = array(self.focpos) |
| 254 | + self.fwhm = array(self.fwhm) |
| 255 | + |
| 256 | + return self.tryFit(defaultFit) |
| 257 | + |
| 258 | + def beforeReadout(self): |
| 259 | + self.current_focus = self.getValueFloat('FOC_POS',self.focuser) |
| 260 | + if (self.num == self.attempts): |
| 261 | + self.setValue('FOC_TOFF',0,self.focuser) |
| 262 | + else: |
| 263 | + self.off += self.step |
| 264 | + self.setValue('FOC_TOFF',self.off,self.focuser) |
| 265 | + |
| 266 | + def takeImages(self): |
| 267 | + self.setValue('exposure',self.exptime) |
| 268 | + self.setValue('SHUTTER','LIGHT') |
| 269 | + self.off = -1 * self.step * (self.attempts / 2) |
| 270 | + self.setValue('FOC_TOFF',self.off,self.focuser) |
| 271 | + tries = {} |
| 272 | + # must be overwritten in beforeReadout |
| 273 | + self.current_focus = None |
| 274 | + |
| 275 | + for self.num in range(1,self.attempts+1): |
| 276 | + self.log('I','starting {0}s exposure on offset {1}'.format(self.exptime,self.off)) |
| 277 | + img = self.exposure(self.beforeReadout,'%b/foc_%N_{0}.fits'.format(self.num)) |
| 278 | + |
| 279 | + tries[self.current_focus] = img |
| 280 | + |
| 281 | + self.log('I','all focusing exposures finished, processing data') |
| 282 | + |
| 283 | + return self.findBestFWHM(tries) |
| 284 | + |
| 285 | + def run(self): |
| 286 | + self.focuser = self.getValue('focuser') |
| 287 | + # send to some other coordinates if you wish so, or disable this for target for fixed coordinates |
| 288 | + #self.altaz (89,90) |
| 289 | + b,fit = self.takeImages() |
| 290 | + if fit == LINEAR: |
| 291 | + self.setValue('FOC_DEF',b,self.focuser) |
| 292 | + b,fit = self.takeImages() |
| 293 | + |
| 294 | + self.setValue('FOC_DEF',b,self.focuser) |
| 295 | + |
| 296 | + def plotFit(self,b,ftype): |
| 297 | + """Plot fit graph.""" |
| 298 | + fitfunc = None |
| 299 | + |
| 300 | + if ftype == LINEAR: |
| 301 | + fitfunc = lambda p, x: p[0] + p[1] * x |
| 302 | + elif ftype == P2: |
| 303 | + fitfunc = lambda p, x: p[0] + p[1] * x + p[2] * (x ** 2) |
| 304 | + elif ftype == P4: |
| 305 | + fitfunc = lambda p, x: p[0] + p[1] * x + p[2] * (x ** 2) + p[3] * (x ** 3) + p[4] * (x ** 4) |
| 306 | + elif ftype == H3: |
| 307 | + fitfunc = lambda p, x: sqrt(p[0] ** 2 + p[1] ** 2 * (x - p[2]) ** 2) |
| 308 | + elif ftype == H2: |
| 309 | + fitfunc = lambda p, x: sqrt(p[0] ** 2 + 3.46407715307 ** 2 * (x - p[1]) ** 2) # 3.46 based on HYPERBOLA fits |
| 310 | + else: |
| 311 | + raise Exception('Unknow fit type {0}'.format(ftype)) |
| 312 | + |
| 313 | + x = linspace(self.focpos.min() - 1, self.focpos.max() + 1) |
| 314 | + |
| 315 | + plot (self.focpos, self.fwhm, "r+", x, fitfunc(self.fwhm_poly, x), "r-") |
| 316 | + |
| 317 | + show() |
| 318 | + |
| 319 | + |
| 320 | +def to_dataserver( fname, outfile='test.fits', clobber=True ): |
| 321 | + |
| 322 | + fitsfd = fits.open( fname ) |
| 323 | + |
| 324 | + |
| 325 | + width = 0 |
| 326 | + height = 0 |
| 327 | + for ext in fitsfd: |
| 328 | + if hasattr( ext, 'data' ): |
| 329 | + if ext.data is not None: |
| 330 | + width+=ext.data.shape[0] |
| 331 | + height+=ext.data.shape[1] |
| 332 | + |
| 333 | + fitsfd.close() |
| 334 | + fsize = os.stat(fname).st_size |
| 335 | + |
| 336 | + fd = open(fname, 'rb') |
| 337 | + |
| 338 | + |
| 339 | + if clobber: |
| 340 | + clobber_char = '!' |
| 341 | + else: |
| 342 | + clobber_char = '' |
| 343 | + meta = " {} {}{} 1 {} {} 0".format( fsize, clobber_char, '/home/bigobs/data/rts2'+outfile, width, height ) |
| 344 | + meta = meta + (256-len(meta))*' ' |
| 345 | + |
| 346 | + data = meta+fd.read() |
| 347 | + lendata = len(data) |
| 348 | + soc = scottSock( '10.30.1.1', 6543 ) |
| 349 | + |
| 350 | + counter = 0 |
| 351 | + socsize = 1024 |
| 352 | + buffsize = 0 |
| 353 | + while buffsize < len(data): |
| 354 | + sent = soc.send( data[buffsize:buffsize+1024] ) |
| 355 | + buffsize+=sent |
| 356 | + |
0 commit comments