diff --git a/.gitignore b/.gitignore index 78135c4..575a024 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,39 @@ +.py[cod] + +# C extensions +*.so + +# Packages +*.egg +*.egg-info +dist build -*.pyc \ No newline at end of file +eggs +parts +bin +var +sdist +develop-eggs +.installed.cfg +lib +lib64 +__pycache__ + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.tox +nosetests.xml + +# Translations +*.mo + +# Mr Developer +.mr.developer.cfg +.project +.pydevproject + +# Sublime Text +*.sublime* diff --git a/python/Centroid.py b/python/Centroid.py index d5b46b8..e4f5722 100644 --- a/python/Centroid.py +++ b/python/Centroid.py @@ -1,4 +1,5 @@ -from __future__ import division, absolute_import, print_function +from __future__ import division, absolute_import, print_function, unicode_literals + """Measure centroids. Note: as with all PyGuide routines, the coordinate system origin @@ -131,7 +132,7 @@ def _fmtList(alist): _MaxIter = 40 # max # of iterations _MinPixForStats = 20 # minimum # of pixels needed to measure med and std dev -class CentroidData: +class CentroidData(object): """Centroid data, including the following fields: flags; check before paying attention to the remaining data: diff --git a/python/Constants.py b/python/Constants.py index 54a7c13..b511536 100755 --- a/python/Constants.py +++ b/python/Constants.py @@ -1,4 +1,6 @@ from __future__ import division, absolute_import, print_function +from __future__ import unicode_literals + """Constants and parameters History: @@ -36,7 +38,7 @@ NaN = float("nan") # Misc -class CCDInfo: +class CCDInfo(object): """Info about the CCD - bias ccd bias (ADU) diff --git a/python/FakeData.py b/python/FakeData.py index 5889ac2..7c86c7d 100755 --- a/python/FakeData.py +++ b/python/FakeData.py @@ -1,4 +1,11 @@ -from __future__ import division, absolute_import, print_function +from __future__ import absolute_import, division, print_function, unicode_literals + +import numpy +import numpy.random + +from . import ImUtil + + """Generates fake ccd data History: @@ -12,12 +19,10 @@ 2005-05-16 ROwen Modified addNoise to take ccdInfo instead of 3 args. 2009-11-20 ROwen Modified to use numpy. """ + __all__ = ["fakeStar", "addNoise"] -import numpy -import numpy.random -from . import ImUtil _MaxValUInt16 = 2**16 - 1 diff --git a/python/FindStars.py b/python/FindStars.py index dfd9ba6..28be576 100755 --- a/python/FindStars.py +++ b/python/FindStars.py @@ -1,4 +1,6 @@ from __future__ import division, absolute_import, print_function +from __future__ import unicode_literals + """Find Stars. Note: as with all PyGuide routines, the coordinate system origin diff --git a/python/ImUtil.py b/python/ImUtil.py index 3e8dfca..2d3b098 100644 --- a/python/ImUtil.py +++ b/python/ImUtil.py @@ -1,4 +1,7 @@ from __future__ import division, absolute_import, print_function +from __future__ import unicode_literals + + """Image processing utilities. History: @@ -65,7 +68,7 @@ def getQuartile(sortedData, qnum): return ((sortedData[ind0] * ratios[0]) + (sortedData[ind0+1] * ratios[1])) / (ratios[0] + ratios[1]) -class ImStats: +class ImStats(object): """Information about an image (including the settings use to obtain that info). @@ -166,7 +169,7 @@ def skyStats( ) -class SubFrame: +class SubFrame(object): """Create a subframe and provide useful utility methods. Inputs: diff --git a/python/StarShape.py b/python/StarShape.py index 77b42f2..b34cb80 100755 --- a/python/StarShape.py +++ b/python/StarShape.py @@ -1,4 +1,8 @@ from __future__ import division, absolute_import, print_function +from __future__ import unicode_literals + + + """StarShape Fit a a star to a symmetrical double gaussian. @@ -102,7 +106,7 @@ # minimum radius _MinRad = 3.0 -class StarShapeData: +class StarShapeData(object): """Guide star fit data Attributes: diff --git a/python/Version.py b/python/Version.py index 55e4709..3c45cd8 100755 --- a/python/Version.py +++ b/python/Version.py @@ -1 +1,2 @@ +from __future__ import unicode_literals __version__ = "2.3.0" diff --git a/python/__init__.py b/python/__init__.py index 51c8f33..ebccca6 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -26,6 +26,7 @@ some of the subtleties. """ from __future__ import absolute_import +from __future__ import unicode_literals from .Version import __version__ from .Constants import * from .Centroid import * diff --git a/releaseNewVersion.py b/releaseNewVersion.py index 5b59a05..6fbd624 100755 --- a/releaseNewVersion.py +++ b/releaseNewVersion.py @@ -4,6 +4,9 @@ To use: ./releaseNewVersion.py """ +from __future__ import print_function +from __future__ import unicode_literals + from __future__ import with_statement import os import re @@ -18,7 +21,7 @@ import Version # noqa must come after modifying sys.path queryStr = "Version from %s.Version = %s; is this OK? (y/[n]) " % (PkgName, Version.__version__,) -versOK = raw_input(queryStr) +versOK = input(queryStr) if not versOK.lower() == "y": sys.exit(0) @@ -29,24 +32,24 @@ if versMatch: histVersStr = versMatch.groups()[0] if histVersStr == Version.__version__: - print "Version in VersionHistory.html matches" + print("Version in VersionHistory.html matches") break else: - print "Error: version in VersionHistory.html = %s != %s" % (histVersStr, Version.__version__) + print("Error: version in VersionHistory.html = %s != %s" % (histVersStr, Version.__version__)) sys.exit(0) -print "Status of git repository:" +print("Status of git repository:") subprocess.call(["git", "status"]) -versOK = raw_input("Is the git repository up to date? (y/[n]) ") +versOK = input("Is the git repository up to date? (y/[n]) ") if not versOK.lower() == "y": sys.exit(0) -print "Git repository OK" +print("Git repository OK") if UploadToPyPI: - print "Uploading to PyPI" + print("Uploading to PyPI") status = subprocess.call(["python", "setup.py", "sdist", "upload"]) if status != 0: - print "Build and upload failed!" + print("Build and upload failed!") diff --git a/scripts/doPyGuide.py b/scripts/doPyGuide.py index 1577d88..c278ff4 100755 --- a/scripts/doPyGuide.py +++ b/scripts/doPyGuide.py @@ -40,6 +40,7 @@ 2009-11-20 ROwen Modified to use numpy. Stop setting NUMERIX. """ +from __future__ import unicode_literals import sys import pyfits import PyGuide @@ -341,7 +342,7 @@ def showDef(): globalDict = globals() for paramName in FindParamNames: print("%s = %s" % (paramName, globalDict[paramName])) - print + print() def help(): print("""The following variables are available: diff --git a/setup.py b/setup.py index 4135bdc..6285b50 100755 --- a/setup.py +++ b/setup.py @@ -1,4 +1,5 @@ #!/usr/bin/env python + from distutils.core import setup, Extension import sys import os diff --git a/src/RadProfModule.c b/src/RadProfModule.c index bc68122..bdc7d2c 100644 --- a/src/RadProfModule.c +++ b/src/RadProfModule.c @@ -90,7 +90,7 @@ static PyObject *Py_radAsymm(PyObject *dumObj, PyObject *args) { if (!PyArg_ParseTuple(args, "OO(ii)i", &dataObj, &maskObj, &iCtr, &jCtr, &rad)) return NULL; - + // Convert arrays to well-behaved arrays of correct type and verify // These arrays MUST be decrefed before return. dataArry = (PyArrayObject *)PyArray_FROM_OTF(dataObj, NPY_FLOAT32, NPY_ARRAY_IN_ARRAY); @@ -109,7 +109,7 @@ static PyObject *Py_radAsymm(PyObject *dumObj, PyObject *args) { PyErr_Format(PyExc_ValueError, "%s: mask must be the same shape as data", ModName); goto errorExit; } - + // Call the C code totPts = radAsymm( PyArray_DIM(dataArry, 0), PyArray_DIM(dataArry, 1), @@ -184,7 +184,7 @@ static PyObject *Py_radAsymmWeighted(PyObject *dumObj, PyObject *args) { if (!PyArg_ParseTuple(args, "OO(ii)iddd", &dataObj, &maskObj, &iCtr, &jCtr, &rad, &bias, &readNoise, &ccdGain)) return NULL; - + // Convert arrays to well-behaved arrays of correct type and verify // These arrays MUST be decrefed before return. dataArry = (PyArrayObject *)PyArray_FROM_OTF(dataObj, NPY_FLOAT32, NPY_ARRAY_IN_ARRAY); @@ -203,7 +203,7 @@ static PyObject *Py_radAsymmWeighted(PyObject *dumObj, PyObject *args) { PyErr_Format(PyExc_ValueError, "%s: mask must be the same shape as data", ModName); goto errorExit; } - + // Call the C code totPts = radAsymmWeighted( PyArray_DIM(dataArry, 0), PyArray_DIM(dataArry, 1), @@ -288,11 +288,11 @@ static PyObject *Py_radProf(PyObject *dumObj, PyObject *args) { int iCtr, jCtr, rad, outLen, totPts; double totCounts; char ModName[] = "radProf"; - + if (!PyArg_ParseTuple(args, "OO(ii)iOOO", &dataObj, &maskObj, &iCtr, &jCtr, &rad, &meanObj, &varObj, &nPtsObj)) return NULL; - + // Convert arrays to well-behaved arrays of correct type and verify // These arrays MUST be decrefed before return. dataArry = (PyArrayObject *)PyArray_FROM_OTF(dataObj, NPY_FLOAT32, NPY_ARRAY_IN_ARRAY); @@ -317,7 +317,7 @@ static PyObject *Py_radProf(PyObject *dumObj, PyObject *args) { PyErr_Format(PyExc_ValueError, "%s: mask must be the same shape as data", ModName); goto errorExit; } - + // Check output arrays and compute outLen if (PyArray_NDIM(meanArry) != 1) { PyErr_Format(PyExc_ValueError, "%s: mean must be 1-dimensional", ModName); @@ -344,8 +344,8 @@ static PyObject *Py_radProf(PyObject *dumObj, PyObject *args) { PyErr_Format(PyExc_ValueError, "%s: output arrays are too short", ModName); goto errorExit; } - - + + // Call the C code totPts = radProf( PyArray_DIM(dataArry, 0), PyArray_DIM(dataArry, 1), @@ -402,10 +402,10 @@ static PyObject *Py_radIndByRadSq(PyObject *dumObj, PyObject *args) { char ModName[] = "radIndByRadSq"; PyArrayObject *radProfPyArray; npy_intp retArrDims[1]; - + if (!PyArg_ParseTuple(args, "i", &nElt)) return NULL; - + if (nElt < 0) { PyErr_Format(PyExc_ValueError, "%s: nPts < 0", ModName); return NULL; @@ -417,7 +417,7 @@ static PyObject *Py_radIndByRadSq(PyObject *dumObj, PyObject *args) { PyErr_Format(PyExc_MemoryError, "%s: insufficient memory", ModName); return NULL; } - + retArrDims[0] = nElt; radProfPyArray = (PyArrayObject *)PyArray_SimpleNew(1, retArrDims, NPY_INT32); npy_int32 *radProfData = (npy_int32 *)PyArray_DATA(radProfPyArray); @@ -446,10 +446,10 @@ static PyObject *Py_radSqByRadInd(PyObject *dumObj, PyObject *args) { char ModName[] = "radSqByRadInd"; PyArrayObject *radSqByRadIndPyArray; npy_intp retArrDims[1]; - + if (!PyArg_ParseTuple(args, "i", &nElt)) return NULL; - + if (nElt < 0) { PyErr_Format(PyExc_ValueError, "%s: nPts < 0", ModName); return NULL; @@ -458,7 +458,7 @@ static PyObject *Py_radSqByRadInd(PyObject *dumObj, PyObject *args) { retArrDims[0] = nElt; radSqByRadIndPyArray = (PyArrayObject *)PyArray_SimpleNew(1, retArrDims, NPY_INT32); npy_int32 *radSqByRadIndData = (npy_int32 *)PyArray_DATA(radSqByRadIndPyArray); - + int firstEnd = nElt < 3 ? nElt: 3; for (radInd = 0; radInd < firstEnd; ++radInd) { radSqByRadIndData[radInd] = radInd; @@ -508,12 +508,12 @@ static PyObject *Py_radSqProf(PyObject *dumObj, PyObject *args) { int iCtr, jCtr, rad, radSq, outLen, totPts; double totCounts; char ModName[] = "radSqProf"; - + if (!PyArg_ParseTuple(args, "OO(ii)iOOO", &dataObj, &maskObj, &iCtr, &jCtr, &rad, &meanObj, &varObj, &nPtsObj)) return NULL; - + // Convert arrays to well-behaved arrays of correct type and verify // These arrays MUST be decrefed before return. dataArry = (PyArrayObject *)PyArray_FROM_OTF(dataObj, NPY_FLOAT32, NPY_ARRAY_IN_ARRAY); @@ -528,7 +528,7 @@ static PyObject *Py_radSqProf(PyObject *dumObj, PyObject *args) { if (varArry == NULL) goto errorExit; nPtsArry = (PyArrayObject *)PyArray_FROM_OTF(nPtsObj, NPY_INT32, NPY_ARRAY_OUT_ARRAY); if (nPtsArry == NULL) goto errorExit; - + radSq = rad*rad; // Check the input arrays @@ -567,7 +567,7 @@ static PyObject *Py_radSqProf(PyObject *dumObj, PyObject *args) { PyErr_Format(PyExc_ValueError, "%s: output arrays are too short", ModName); goto errorExit; } - + // Call the C code totPts = radSqProf( PyArray_DIM(dataArry, 0), PyArray_DIM(dataArry, 1), @@ -622,7 +622,7 @@ int g_radProf_setup( int rad ) { int nElt, radSq; - + // compute nElt and make sure it is int enough for the initialization code nElt = MAX(rad*rad + 1, 3); @@ -630,23 +630,23 @@ int g_radProf_setup( // array is already int enough; bail out. return 1; } - + g_radProf_free(); - + g_radProf_radIndByRadSq = calloc(nElt, sizeof *g_radProf_radIndByRadSq); if (g_radProf_radIndByRadSq == NULL) { g_radProf_free(); return 0; } g_radProf_nElt = nElt; - + for (radSq = 0; radSq < 3; ++radSq) { g_radProf_radIndByRadSq[radSq] = radSq; } for (radSq = 3; radSq < nElt; ++radSq) { g_radProf_radIndByRadSq[radSq] = (int)(sqrt((double)(radSq)) + 1.5); } - + return 1; } @@ -680,9 +680,9 @@ int g_radAsymm_alloc( if (g_radAsymm_nElt >= nElt) { return 1; } - + g_radAsymm_free(); - + g_radAsymm_mean = calloc(nElt, sizeof *g_radAsymm_mean); g_radAsymm_var = calloc(nElt, sizeof *g_radAsymm_var); g_radAsymm_nPts = calloc(nElt, sizeof *g_radAsymm_nPts); @@ -746,12 +746,12 @@ int radAsymm( // initialize outputs *asymmPtr = 0.0; *totCountsPtr = 0.0; - + // reallocate working arrays if necessary if (!g_radAsymm_alloc(nElt)) { return -2; } - + // compute radial profile stats totPts = radProf ( inLenI, inLenJ, @@ -769,12 +769,12 @@ int radAsymm( // <0 indicates a problem, 0 indicates no valid points return totPts; } - + // asymm = sum(std dev^2) for (ind = 0; ind < nElt; ++ind){ *asymmPtr += g_radAsymm_var[ind] * (double) g_radAsymm_nPts[ind]; } - + return totPts; } @@ -840,12 +840,12 @@ int radAsymmWeighted( // initialize outputs *asymmPtr = 0.0; *totCountsPtr = 0.0; - + // reallocate working arrays if necessary if (!g_radAsymm_alloc(nElt)) { return -2; } - + // compute radial profile stats totPts = radProf ( inLenI, inLenJ, @@ -863,13 +863,13 @@ int radAsymmWeighted( // <0 indicates a problem, 0 indicates no valid points return totPts; } - + // force bias < smallest mean value, if necessary, // to prevent bogus bias from really messing up the results for (ind = 0; ind < nElt; ++ind) { if (g_radAsymm_mean[ind] < bias) bias = g_radAsymm_mean[ind]; } - + // asymm = sum(std dev^2) for (ind = 0; ind < nElt; ++ind) { nPts = g_radAsymm_nPts[ind]; @@ -879,7 +879,7 @@ int radAsymmWeighted( *asymmPtr += g_radAsymm_var[ind] / weight; } } - + return totPts; } @@ -913,7 +913,7 @@ Error Conditions: - If outLen < rad + 2, returns -1. - If insufficient memory to generate a working array, returns -2. -- If any value in g_radProf_radIndByRadSq[0:rad^2] > rad, returns -3. +- If any value in g_radProf_radIndByRadSq[0:rad^2] > rad, returns -3. Points off the data array are ignored. Thus the center need not be on the array. @@ -937,13 +937,13 @@ int radProf( int totPts; double d; char ModName[]="radProf"; - + // test inputs if (outLen < desOutLen) { printf("%s: outLen too small\n", ModName); return -1; } - + // set up index array if (!g_radProf_setup(rad)) { printf("%s: insufficient memory\n", ModName); @@ -975,7 +975,7 @@ int radProf( printf("radProf failed: outInd=%d, rad=%d\n", outInd, rad); return -3; } - + d = (double) data[ii][jj]; mean[outInd] += d; var[outInd] += d*d; @@ -993,7 +993,7 @@ int radProf( var[outInd] = (var[outInd]/(double)nPts[outInd]) - (mean[outInd]*mean[outInd]); } } - + return totPts; } @@ -1001,7 +1001,7 @@ int radProf( /* radSqProf ============================================================ Generate a radial profile as a function of radius squared. - + Inputs: - inLenI, inLenJ dimensions of data and mask - data data array [i,j] @@ -1045,12 +1045,12 @@ int radSqProf( int minJJ, maxJJ, minII, maxII; double d; int totPts; - + // test inputs if (outLen < desOutLen) { return -1; } - + // initialize outputs to 0 for(outInd=0; outInd= desOutLen) continue; - + d = (double) data[ii][jj]; mean[outInd] += d; var[outInd] += d*d; @@ -1103,12 +1103,34 @@ static PyMethodDef radProfMethods[] = { {NULL, NULL, 0, NULL} /* Sentinel */ }; -// Module initialization function -PyMODINIT_FUNC initradProf(void) { - PyObject *m; - m = Py_InitModule3("radProf", radProfMethods, radProfModule_doc); - if (m == NULL) - return; - import_array(); -} +#if PY_MAJOR_VERSION >= 3 + + static struct PyModuleDef pyguidemodule = { + PyModuleDef_HEAD_INIT, + "radProf", /* name of module */ + radProfModule_doc, /* module documentation, may be NULL */ + -1, /* size of per-interpreter state of the module, + or -1 if the module keeps state in global variables. */ + radProfMethods + }; + + // Module initialization function + PyMODINIT_FUNC PyInit_radProf(void) { + import_array(); + return PyModule_Create(&pyguidemodule); + } + +#else + + // Module initialization function + PyMODINIT_FUNC initradProf(void) { + PyObject *m; + m = Py_InitModule3("radProf", radProfMethods, radProfModule_doc); + if (m == NULL) + return; + + import_array(); + } + +#endif diff --git a/tests/Stats.py b/tests/Stats.py index b0c9ac7..b36d368 100755 --- a/tests/Stats.py +++ b/tests/Stats.py @@ -1,11 +1,13 @@ from __future__ import division, absolute_import, print_function +from __future__ import unicode_literals + import math -class Stats: +class Stats(object): def __init__(self): self.clear() - + def append(self, val): """Append a value to the data set. """ @@ -17,7 +19,7 @@ def append(self, val): self._minVal = val if self._maxVal is None or val > self._maxVal: self._maxVal = val - + def clear(self): """Clear the data. """ @@ -26,30 +28,30 @@ def clear(self): self._sumSq = 0.0 self._minVal = None self._maxVal = None - + def min(self): """Return the minimum value. """ self._checkPoints() return self._minVal - + def max(self): """Return the maximum value. """ self._checkPoints() return self._maxVal - + def mean(self): """Return the mean value. """ self._checkPoints() return self._sum / float(self._n) - + def nPoints(self): """Return the number of points. """ return self._n - + def var(self): """Return the variance: (sum(val^2) - mean^2) / N-1 @@ -61,13 +63,13 @@ def stdDev(self): """Return the stanard deviation: sqrt(var). """ return math.sqrt(self.var()) - + def rms(self): """Return the RMS value. """ self._checkPoints() return math.sqrt(self._sumSq / float(self._n)) - + def _checkPoints(self, minReq=1): """Check that we have enough data points. Raise a RuntimeError if we do not. @@ -82,7 +84,7 @@ def _checkPoints(self, minReq=1): if __name__ == "__main__": s = Stats() NaN = float("NaN") - + def printRes(): try: minVal = s.min() @@ -113,10 +115,10 @@ def printRes(): rms = s.rms() except RuntimeError: rms = NaN - + print ("%2d %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f" % \ (s.nPoints(), minVal, maxVal, mean, stdDev, var, rms)) - + print (" N min max mean stdDev var RMS") testVals = (1, 2, 3, 4, 5, 6, 7, 8, 9) printRes() diff --git a/tests/checkPyGuide.py b/tests/checkPyGuide.py index 903f29e..16815b5 100755 --- a/tests/checkPyGuide.py +++ b/tests/checkPyGuide.py @@ -5,6 +5,8 @@ 2004-08-06 ROwen 2007-01-23 ROwen Changed #!/usr/local/bin/python to #!/usr/bin/env python """ +from __future__ import print_function +from __future__ import unicode_literals # import modules that I don't want checked import numpy import scipy.ndimage @@ -13,4 +15,4 @@ import pychecker.checker import PyGuide -print "Done" +print("Done") diff --git a/tests/testCentroid.py b/tests/testCentroid.py index 2bbc884..36e835d 100755 --- a/tests/testCentroid.py +++ b/tests/testCentroid.py @@ -1,5 +1,14 @@ #!/usr/bin/env python -from __future__ import division, absolute_import, print_function +from __future__ import absolute_import, division, print_function, unicode_literals + + + +import numpy + +import PyGuide +import RO.DS9 + + """Test PyGuide.centroid with masked data. History: @@ -16,10 +25,6 @@ 2008-01-02 ROwen Added DoSmooth constant. 2009-11-20 ROwen Modified to use numpy. """ -import numpy -import PyGuide -import RO.DS9 - DoSmooth = True Sky = 1000, # sky level, in ADU CCDInfo = PyGuide.CCDInfo( @@ -76,11 +81,11 @@ ccdInfo = CCDInfo, doSmooth = DoSmooth, ) - + if not ctrData.isOK: print("centroid failed: %s" % (ctrData.msgStr,)) continue - + measCtr = ctrData.xyCtr nCounts = ctrData.counts nPts = ctrData.pix diff --git a/tests/testCentroidLong.py b/tests/testCentroidLong.py index 1ec3e5b..ea7f7ae 100755 --- a/tests/testCentroidLong.py +++ b/tests/testCentroidLong.py @@ -17,6 +17,10 @@ 2008-01-02 ROwen Added DoSmooth constant. 2009-11-20 ROwen Modified to use numpy. """ +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + import numpy import PyGuide from Stats import Stats @@ -44,36 +48,36 @@ MaskWidthsPerFWHM = (0.0, 0.5, 1.0, 1.5, 2.0) # fractions of a FWHM NumTries = 20 -print "Compare centroid actual error vs estimated error" -print "over a range of fake data" -print -print "Settings:" -print "Thresh =", Thresh -print "Sky =", Sky, "ADU" -print "Read Noise =", CCDInfo.readNoise, "e-" -print "CCD Gain =", CCDInfo.ccdGain, "e-/ADU" -print "Bias =", CCDInfo.bias, "ADU" -print "Amplitudes =", AmplValues, "ADU" -print "FWHMs =", FWHMValues, "pixels" -print "Mask Widths =", MaskWidthsPerFWHM, "fractions of a FWHM" -print "Num Ctrs =", NumTries, "number of centroids per star shape" -print "CCD Size =", ImWidth, "x", ImWidth, "pixels" -print -print "the equation being minimized is:" -print " sum(var(r) * numPts(r))" -print "though the final number reported is a normalized version:" -print " asymm = sum(var(r) * numPts(r)) / (pixNoise^2 * totPts)" -print "where" -print " pixNoise is the noise/pixel due to read noise and sky" -print " totPts = sum(numPts(r))" -print -print "The centroids are randomly distributed over" -print "a range of -FWHM/2, FWHM/2 with respect to the" -print "center of the CCD = the center of the slit." -print -print "The slit is along y so the error along y should be smaller than x." -print -print "fwhm ampl maskWid xErr yErr xUncert yUncert asymm totPix totCts rad msgs" +print("Compare centroid actual error vs estimated error") +print("over a range of fake data") +print() +print("Settings:") +print("Thresh =", Thresh) +print("Sky =", Sky, "ADU") +print("Read Noise =", CCDInfo.readNoise, "e-") +print("CCD Gain =", CCDInfo.ccdGain, "e-/ADU") +print("Bias =", CCDInfo.bias, "ADU") +print("Amplitudes =", AmplValues, "ADU") +print("FWHMs =", FWHMValues, "pixels") +print("Mask Widths =", MaskWidthsPerFWHM, "fractions of a FWHM") +print("Num Ctrs =", NumTries, "number of centroids per star shape") +print("CCD Size =", ImWidth, "x", ImWidth, "pixels") +print() +print("the equation being minimized is:") +print(" sum(var(r) * numPts(r))") +print("though the final number reported is a normalized version:") +print(" asymm = sum(var(r) * numPts(r)) / (pixNoise^2 * totPts)") +print("where") +print(" pixNoise is the noise/pixel due to read noise and sky") +print(" totPts = sum(numPts(r))") +print() +print("The centroids are randomly distributed over") +print("a range of -FWHM/2, FWHM/2 with respect to the") +print("center of the CCD = the center of the slit.") +print() +print("The slit is along y so the error along y should be smaller than x.") +print() +print("fwhm ampl maskWid xErr yErr xUncert yUncert asymm totPix totCts rad msgs") nBad = 0 ctrXStats = Stats() @@ -90,7 +94,7 @@ numpy.random.seed(1) for ii in range(NumTries): - actCtr = numpy.random.uniform(-fwhm/2.0, fwhm/2.0, size=(2,)) + nomCtr + actCtr = numpy.random.uniform(-fwhm / 2.0, fwhm / 2.0, size=(2,)) + nomCtr cleanData = PyGuide.FakeData.fakeStar(imShape, actCtr, sigma, ampl) data = PyGuide.FakeData.addNoise( @@ -110,29 +114,29 @@ doSmooth = DoSmooth, ) if not ctrData.isOK: - print "%s %s %s NaN NaN NaN NaN NaN NaN NaN %s %r" % ( + print("%s %s %s NaN NaN NaN NaN NaN NaN NaN %s %r" % ( fwhm, ampl, maskWidth, ctrData.rad, ctrData.msgStr, - ) + )) nBad += 1 continue - + xyMeasErr = [ctrData.xyCtr[ii] - actCtr[ii] for ii in (0,1)] - print "%s %s %s %.3f %.3f %.3f %.3f %.3f %s %s %s %r" % ( + print("%s %s %s %.3f %.3f %.3f %.3f %.3f %s %s %s %r" % ( fwhm, ampl, maskWidth, xyMeasErr[0], xyMeasErr[1], ctrData.xyErr[0], ctrData.xyErr[1], ctrData.asymm, ctrData.pix, ctrData.counts, ctrData.rad, ctrData.msgStr, - ) + )) ctrXStats.append(xyMeasErr[0]) ctrYStats.append(xyMeasErr[1]) -print -print "Error statistics (for %d points)" % ctrXStats.nPoints() -print " min max mean stdDev" -print "xErr %8.1f %8.1f %8.1f %8.1f" % (ctrXStats.min(), ctrXStats.max(), ctrXStats.mean(), ctrXStats.stdDev()) -print "yErr %8.1f %8.1f %8.1f %8.1f" % (ctrYStats.min(), ctrYStats.max(), ctrYStats.mean(), ctrYStats.stdDev()) +print() +print("Error statistics (for %d points)" % ctrXStats.nPoints()) +print(" min max mean stdDev") +print("xErr %8.1f %8.1f %8.1f %8.1f" % (ctrXStats.min(), ctrXStats.max(), ctrXStats.mean(), ctrXStats.stdDev())) +print("yErr %8.1f %8.1f %8.1f %8.1f" % (ctrYStats.min(), ctrYStats.max(), ctrYStats.mean(), ctrYStats.stdDev())) if nBad > 0: - print - print "number of failures =", nBad + print() + print("number of failures =", nBad) diff --git a/tests/testStarShape.py b/tests/testStarShape.py index 05438d4..72548f0 100755 --- a/tests/testStarShape.py +++ b/tests/testStarShape.py @@ -17,6 +17,8 @@ 2005-04-19 ROwen Modified for PyGuide 2.0 2005-10-14 ROwen Supply null satMask for PyGuide 2.1. """ +from __future__ import print_function +from __future__ import unicode_literals import os.path import sys import PyGuide @@ -50,7 +52,7 @@ #mask = data < 0 #mask[64:101, 78:92] = 1 -print "searching for stars" +print("searching for stars") ctrDataList, imStats = PyGuide.findStars( data = data, mask = mask, @@ -62,7 +64,7 @@ for ctrData in ctrDataList: xyCtr = ctrData.xyCtr rad = ctrData.rad - print "star xyCtr=%.2f, %.2f, radius=%s" % (xyCtr[0], xyCtr[1], rad) + print("star xyCtr=%.2f, %.2f, radius=%s" % (xyCtr[0], xyCtr[1], rad)) shapeData = PyGuide.starShape( data, @@ -71,8 +73,8 @@ rad = rad, ) if not shapeData.isOK: - print "starShape failed: %s" % (shapeData.msgStr,) + print("starShape failed: %s" % (shapeData.msgStr,)) else: - print "star ampl=%.1f, fwhm=%.1f, bkgnd=%.1f, chiSq=%.2f" %\ - (shapeData.ampl,shapeData.fwhm, shapeData.bkgnd, shapeData.chiSq) - print + print("star ampl=%.1f, fwhm=%.1f, bkgnd=%.1f, chiSq=%.2f" %\ + (shapeData.ampl,shapeData.fwhm, shapeData.bkgnd, shapeData.chiSq)) + print() diff --git a/tests/testStarShapeLong.py b/tests/testStarShapeLong.py index 5ae1029..a1c061f 100755 --- a/tests/testStarShapeLong.py +++ b/tests/testStarShapeLong.py @@ -21,6 +21,10 @@ 2005-10-14 ROwen Supply null satMask for PyGuide 2.1. 2009-11-20 ROwen Modified to use numpy. """ +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + import sys import traceback import numpy @@ -50,31 +54,31 @@ nomCtr = (ImWidth // 2, ImWidth // 2) mask = numpy.zeros(imShape, numpy.bool) -print "Compare star shape fit values to correct values" -print "over a range of fake data" -print -print "Settings:" -print "Sky =", Sky, "ADU" -print "Read Noise =", CCDInfo.readNoise, "e-" -print "CCD Gain =", CCDInfo.ccdGain, "e-/ADU" -print "Bias =", CCDInfo.bias, "ADU" -print "DoCentroid =", DoCentroid +print("Compare star shape fit values to correct values") +print("over a range of fake data") +print() +print("Settings:") +print("Sky =", Sky, "ADU") +print("Read Noise =", CCDInfo.readNoise, "e-") +print("CCD Gain =", CCDInfo.ccdGain, "e-/ADU") +print("Bias =", CCDInfo.bias, "ADU") +print("DoCentroid =", DoCentroid) if DoCentroid: - print "Thresh =", Thresh -print "Amplitudes =", AmplValues, "ADU" -print "FWHMs =", FWHMValues, "pixels" -print "Mask Widths =", MaskWidthsPerFWHM, "fractions of a FWHM" -print "Num Tries =", NumTries, "number of cases per star shape" -print "CCD Size =", ImWidth, "x", ImWidth, "pixels" -print -print "Each try is a star whose center is randomly distributed over" -print "a range of -FWHM/2, FWHM/2 with respect to the" -print "center of the CCD = the center of the slit." -print -print "Reported errors and statistics on these errors are in percent:" -print "reported error (%) = 100 * (meas value - act value) / act value" -print -print "The slit is along y." + print("Thresh =", Thresh) +print("Amplitudes =", AmplValues, "ADU") +print("FWHMs =", FWHMValues, "pixels") +print("Mask Widths =", MaskWidthsPerFWHM, "fractions of a FWHM") +print("Num Tries =", NumTries, "number of cases per star shape") +print("CCD Size =", ImWidth, "x", ImWidth, "pixels") +print() +print("Each try is a star whose center is randomly distributed over") +print("a range of -FWHM/2, FWHM/2 with respect to the") +print("center of the CCD = the center of the slit.") +print() +print("Reported errors and statistics on these errors are in percent:") +print("reported error (%) = 100 * (meas value - act value) / act value") +print() +print("The slit is along y.") def pctErr(meas, act): return (meas - act) * 100.0 / float(act) @@ -85,8 +89,8 @@ def pctErr(meas, act): nBadCtr = 0 nBad = 0 -print -print "fwhm ampl bg xCtr yCtr maskWid xCtMeas yCtMeas fitFWHM fitAmpl fitBg chiSq fwhmErr amplErr bgErr msgs" +print() +print("fwhm ampl bg xCtr yCtr maskWid xCtMeas yCtMeas fitFWHM fitAmpl fitBg chiSq fwhmErr amplErr bgErr msgs") bkgnd = Sky + CCDInfo.bias for ampl in AmplValues: for fwhm in FWHMValues: @@ -100,7 +104,7 @@ def pctErr(meas, act): numpy.random.seed(1) for ii in range(NumTries): - xyCtr = numpy.random.uniform(-fwhm/2.0, fwhm/2.0, size=(2,)) + nomCtr + xyCtr = numpy.random.uniform(-fwhm / 2.0, fwhm /2.0, size=(2,)) + nomCtr cleanData = PyGuide.FakeData.fakeStar(imShape, xyCtr, sigma, ampl) data = PyGuide.FakeData.addNoise( @@ -108,7 +112,7 @@ def pctErr(meas, act): sky = Sky, ccdInfo = CCDInfo, ) - + if DoCentroid: ctrData = PyGuide.centroid( data = data, @@ -120,11 +124,11 @@ def pctErr(meas, act): thresh = Thresh, ) if not ctrData.isOK: - print "%.1f %.1f %.1f %.2f %.2f %.2f NaN NaN NaN NaN NaN NaN NaN NaN NaN %r" % ( + print("%.1f %.1f %.1f %.2f %.2f %.2f NaN NaN NaN NaN NaN NaN NaN NaN NaN %r" % ( fwhm, ampl, bkgnd, xyCtr[0], xyCtr[1], maskWidth, ctrData.msgStr, - ) + )) nBadCtr += 1 continue else: @@ -140,37 +144,37 @@ def pctErr(meas, act): rad = fwhm * 3, ) if not shapeData.isOK: - print "%.1f %.1f %.1f %.2f %.2f %.2f %.2f %.2f NaN NaN NaN NaN NaN NaN NaN %r" % ( + print("%.1f %.1f %.1f %.2f %.2f %.2f %.2f %.2f NaN NaN NaN NaN NaN NaN NaN %r" % ( fwhm, ampl, bkgnd, xyCtr[0], xyCtr[1], maskWidth, ctrData.xyCtr[0], ctrData.xyCtr[1], shapeData.msgStr, - ) + )) nBad += 1 continue - + fwhmErr = pctErr(shapeData.fwhm, fwhm) amplErr = pctErr(shapeData.ampl, ampl) bkgndErr = pctErr(shapeData.bkgnd, bkgnd) - print "%.1f %.1f %.1f %.2f %.2f %.2f %.2f %.2f %.1f %.1f %.1f %.2f %.1f %.1f %.1f %r" % ( + print("%.1f %.1f %.1f %.2f %.2f %.2f %.2f %.2f %.1f %.1f %.1f %.2f %.1f %.1f %.1f %r" % ( fwhm, ampl, bkgnd, xyCtr[0], xyCtr[1], maskWidth, ctrData.xyCtr[0], ctrData.xyCtr[1], shapeData.fwhm, shapeData.ampl, shapeData.bkgnd, shapeData.chiSq, fwhmErr, amplErr, bkgndErr, shapeData.msgStr, - ) + )) fwhmStats.append(fwhmErr) amplStats.append(amplErr) bkgndStats.append(bkgndErr) -print -print "Error statistics (for %d points)" % fwhmStats.nPoints() -print " min max mean stdDev" -print "fwhm %8.1f %8.1f %8.1f %8.1f" % (fwhmStats.min(), fwhmStats.max(), fwhmStats.mean(), fwhmStats.stdDev()) -print "ampl %8.1f %8.1f %8.1f %8.1f" % (amplStats.min(), amplStats.max(), amplStats.mean(), amplStats.stdDev()) -print "bkgnd %8.1f %8.1f %8.1f %8.1f" % (bkgndStats.min(), bkgndStats.max(), bkgndStats.mean(), bkgndStats.stdDev()) +print() +print("Error statistics (for %d points)" % fwhmStats.nPoints()) +print(" min max mean stdDev") +print("fwhm %8.1f %8.1f %8.1f %8.1f" % (fwhmStats.min(), fwhmStats.max(), fwhmStats.mean(), fwhmStats.stdDev())) +print("ampl %8.1f %8.1f %8.1f %8.1f" % (amplStats.min(), amplStats.max(), amplStats.mean(), amplStats.stdDev())) +print("bkgnd %8.1f %8.1f %8.1f %8.1f" % (bkgndStats.min(), bkgndStats.max(), bkgndStats.mean(), bkgndStats.stdDev())) if (nBad > 0) or (nBadCtr > 0): - print - print "number of shape fit failures =", nBad + print() + print("number of shape fit failures =", nBad) if DoCentroid: - print "number of centroid failures =", nBadCtr + print("number of centroid failures =", nBadCtr) diff --git a/tests/timeCentroid.py b/tests/timeCentroid.py index 6b38957..9237396 100755 --- a/tests/timeCentroid.py +++ b/tests/timeCentroid.py @@ -11,6 +11,11 @@ 2005-10-14 ROwen Supply null satMask for PyGuide 2.1. 2009-11-20 ROwen Modified to use numpy. """ +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +from past.utils import old_div import time import numpy import PyGuide @@ -28,8 +33,8 @@ Ampl = 5000 def timeCentroid(data, mask, xyGuess, niter, rad=20): - print "timeCentroid: xyGuess=%3.0f, %3.0f; niter=%2d; rad=%3d;" % \ - (xyGuess[0], xyGuess[1], niter, rad), + print("timeCentroid: xyGuess=%3.0f, %3.0f; niter=%2d; rad=%3d;" % \ + (xyGuess[0], xyGuess[1], niter, rad), end=' ') begTime = time.time() for ii in range(niter): PyGuide.centroid( @@ -42,15 +47,15 @@ def timeCentroid(data, mask, xyGuess, niter, rad=20): ccdInfo = CCDInfo, ) dTime = time.time() - begTime - print "time/iter=%.3f" % (dTime/niter,) + print("time/iter=%.3f" % (old_div(dTime,niter),)) def timeRadAsymmWeighted(data, mask, niter, rad=20): shape = data.getshape() - xc = shape[0]/2 - yc = shape[1]/2 - print "timeRadAsymmWeighted: niter=%2d; rad=%3d;" % (niter, rad), - + xc = old_div(shape[0],2) + yc = old_div(shape[1],2) + print("timeRadAsymmWeighted: niter=%2d; rad=%3d;" % (niter, rad), end=' ') + begTime = time.time() for ii in range(niter): PyGuide.radProf.radAsymmWeighted( @@ -58,16 +63,16 @@ def timeRadAsymmWeighted(data, mask, niter, rad=20): CCDInfo.bias, CCDInfo.readNoise, CCDInfo.ccdGain, ) dTime = time.time() - begTime - print "time/iter=%.3f" % (dTime/niter,) + print("time/iter=%.3f" % (old_div(dTime,niter),)) def timeRadProf(data, mask, niter, rad): """Time radProf and radSqProf""" shape = data.getshape() - xc = shape[0]/2 - yc = shape[1]/2 - print "timeRadProf: niter=%2d; rad=%3d;" % (niter, rad,), - + xc = old_div(shape[0],2) + yc = old_div(shape[1],2) + print("timeRadProf: niter=%2d; rad=%3d;" % (niter, rad,), end=' ') + radSqLen = rad**2 + 1 radSqMean = numpy.zeros([radSqLen], numpy.float64) radSqVar = numpy.zeros([radSqLen], numpy.float64) @@ -77,27 +82,27 @@ def timeRadProf(data, mask, niter, rad): radMean = numpy.zeros([radLen], numpy.float64) radVar = numpy.zeros([radLen], numpy.float64) radNPts = numpy.zeros([radLen], numpy.int32) - + begTime = time.time() for ii in range(niter): PyGuide.radProf.radSqProf(data, mask, (xc, yc), rad, radSqMean, radSqVar, radSqNPts) dTime = time.time() - begTime - print "radSqProf time/iter=%.4f;" % (dTime/niter,), - + print("radSqProf time/iter=%.4f;" % (old_div(dTime,niter),), end=' ') + begTime = time.time() for ii in range(niter): PyGuide.radProf.radProf(data, mask, (xc, yc), rad, radMean, radVar, radNPts) dTime = time.time() - begTime - print "radProf time/iter=%.4f" % (dTime/niter,), - - print + print("radProf time/iter=%.4f" % (old_div(dTime,niter),), end=' ') + + print() def runTests(): # generate fake data imShape = (ImWidth, ImWidth) xyCtr = numpy.divide(imShape, 2.0) - sigma = FWHM / PyGuide.FWHMPerSigma + sigma = old_div(FWHM, PyGuide.FWHMPerSigma) cleanData = PyGuide.FakeData.fakeStar(imShape, xyCtr, sigma, Ampl) data = PyGuide.FakeData.addNoise( data = cleanData, @@ -105,36 +110,36 @@ def runTests(): ccdInfo = CCDInfo, ) data = data.astype(numpy.int16) - + # let centroiding walk a bit to find the center xyGuess = numpy.add(xyCtr, (2, -2)) - print "Time various parts of centroiding as a function of radius" - print - print "Settings:" - print "CCD Size =", ImWidth, "x", ImWidth, "pix" - print "Star center = %d, %d pix" % (xyCtr[0], xyCtr[1]) - print "Initial guess = %d, %d pix" % (xyGuess[0], xyGuess[1]) - print - print "Amplitude =", Ampl, "ADU" - print "FWHM =", FWHM, "pix" - print "Sky =", Sky, "ADU" - print "Bias =", CCDInfo.bias, "ADU" - print "Read Noise =", CCDInfo.readNoise, "e-" - print "CCD Gain =", CCDInfo.ccdGain, "e-/ADU" + print("Time various parts of centroiding as a function of radius") + print() + print("Settings:") + print("CCD Size =", ImWidth, "x", ImWidth, "pix") + print("Star center = %d, %d pix" % (xyCtr[0], xyCtr[1])) + print("Initial guess = %d, %d pix" % (xyGuess[0], xyGuess[1])) + print() + print("Amplitude =", Ampl, "ADU") + print("FWHM =", FWHM, "pix") + print("Sky =", Sky, "ADU") + print("Bias =", CCDInfo.bias, "ADU") + print("Read Noise =", CCDInfo.readNoise, "e-") + print("CCD Gain =", CCDInfo.ccdGain, "e-/ADU") allZerosMask = data.astype(numpy.bool) allZerosMask[:] = 0 - + maskData = ( (None, "No mask"), (allZerosMask, "Mask of all zeros"), ) - + for mask, expl in maskData: - print - print expl - + print() + print(expl) + radNiterList = ( ( 10, 20), ( 20, 20), @@ -144,20 +149,20 @@ def runTests(): (320, 20), (640, 10), ) - - print + + print() for rad, niter in radNiterList: try: timeRadProf(data, mask, niter, rad) except Exception as e: - print "timeRadProf(niter=%s, rad=%s) failed: %s" % (niter, rad, e) - - print + print("timeRadProf(niter=%s, rad=%s) failed: %s" % (niter, rad, e)) + + print() for rad, niter in radNiterList: try: timeRadAsymmWeighted(data, mask, niter, rad) except Exception as e: - print "timeRadAsymmWeighted(niter=%s, rad=%s) failed: %s" % (niter, rad, e) + print("timeRadAsymmWeighted(niter=%s, rad=%s) failed: %s" % (niter, rad, e)) radNiterList = ( ( 10, 10), @@ -168,8 +173,8 @@ def runTests(): (320, 2), (640, 1), ) - - print + + print() for rad, niter in radNiterList: try: timeCentroid(data, mask, xyGuess, niter, rad)