casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
imagetest_regression.py
Go to the documentation of this file.
00001 ##############################################################################
00002 #                                                                            #
00003 # Test Name:                                                                 #
00004 #    imagetest_regression.py                                                 #
00005 # Rationale for Inclusion:                                                   #
00006 #    This is a Python translation of the Glish assay test imageservertest.g  #
00007 #    It tests many image tool methods                                        #
00008 # Features Tested:                                                           #
00009 #    fromshape, fromarray, fromimage, fromfits, imageconcat, imagecalc       #
00010 #    done, close, open, isopen, type, lock, unlock, haslock,                 #
00011 #    coordsys, setcoordsys, shape, name, rename, delte, persistent           #
00012 #    getchunk,  putchunk, pixelvalue, getregion, putregion, set              #
00013 #    replacemaskedpixels, FITS conversion, boundingbox, {set}restoringbeam   #
00014 #    coordmeasures, topixel, toworld,                                        #
00015 #    summary, maskhandler, subimage, insert, hanning, convolve, sepconvole,  #
00016 #    LEL, statistics, histograms, moments, modify, fft, regrid,      #
00017 #    convolve2d, deconvolvecomponentlist, findsources, maxfit, adddegaxes,   #
00018 #    addnoise, {set}miscinfo, {set}history, {set}brightnessunit              #
00019 #    {set}restoringbeam, convertflux
00020 #    fromascii, toascii, fitpolynomial, twopointcorrelation, continuumsub,   #
00021 #    rebin, fitprofile                                                       #
00022 # Success/failure criteria:                                                  #
00023 #    Internally tests each method for pass/fail.  Throws an uncaught         #
00024 #    exception ending test when an unexpected failure occurs.                #
00025 #    All tests pass if script runs to completion.                            #
00026 #                                                                            #
00027 ##############################################################################
00028 #                                                                            #
00029 # Converted by RRusk 2007-11-08 from imagetest.py                            #
00030 # Updated      RRusk 2007-11-16 fixed some typos, cleaned up temp output     #
00031 #                                                                            #
00032 ##############################################################################
00033 
00034 import os
00035 import shutil
00036 import time
00037 import math
00038 from numpy import array
00039 
00040 #
00041 # imagetest.py: test casapy image tool
00042 #
00043 
00044 #
00045 # Utils
00046 #
00047 def note(message, priority="NORMAL", origin="imagetest", ntime=None, postcli='F'):
00048     #if not ntime:  #if (ntime==None):
00049     #    ntime=time.asctime()
00050     #print ntime, priority, origin, message
00051     print message
00052     casalog.postLocally(message, priority, origin)
00053 
00054 def info(message):
00055     #note(message,origin='imagetest')
00056     print message
00057     casalog.postLocally(message, priority="NORMAL", origin='imagetest')
00058 
00059 def fail(message=""):
00060     casalog.postLocally(message, priority="SEVERE", origin='imagetest')
00061     raise RuntimeError, message
00062 
00063     #Glish's all() returns T if every element of x is either T (if x's
00064     #type is boolean) or non-zero (otherwise). It returns F if any
00065     #element of x is either F or zero. For example,
00066     #
00067     #all(y > 3)
00068     #
00069     #returns T if-and-only-if every element of y is greater than 3.
00070     #If x is not numeric an error is generated and an undefined value
00071     #is returned.
00072 def all(x,y):
00073     if len(x) != len(y):
00074         return false
00075     for i in range(len(x)):
00076         if not (x[i]==y[i]):
00077             print "x["+str(i)+"]=", x[i]
00078             print "y["+str(i)+"]=", y[i]
00079             return false
00080     return true
00081 
00082 def allbooleq(x,y):
00083     if len(x) != len(y):
00084         return false
00085     if len(x.shape)==1:
00086         for i in range(x.shape[0]):
00087             if not (x[i]==y[i]):
00088                 return false
00089     if len(x.shape)==2:
00090         for i in range(x.shape[0]):
00091             for j in range(x.shape[1]):
00092                 if not (x[i][j]==x[i][j]):
00093                     return false
00094     if len(x.shape)==3:
00095         for i in range(x.shape[0]):
00096             for j in range(x.shape[1]):
00097                 for k in range(x.shape[2]):
00098                     if not (x[i][j][k]==y[i][j][k]):
00099                         return false
00100     if len(x.shape)==4:
00101         for i in range(x.shape[0]):
00102             for j in range(x.shape[1]):
00103                 for k in range(x.shape[2]):
00104                     for l in range(x.shape[3]):
00105                         if not (x[i][j][k][l]==y[i][j][k][l]):
00106                             return false
00107     if len(x.shape)>4:
00108         stop('unhandled array shape in all')
00109     return true
00110 
00111 def alltrue(x):
00112     if len(x.shape)==1:
00113         for i in range(x.shape[0]):
00114             if not (x[i]):
00115                 return false
00116     if len(x.shape)==2:
00117         for i in range(x.shape[0]):
00118             for j in range(x.shape[1]):
00119                 if not (x[i][j]):
00120                     return false
00121     if len(x.shape)==3:
00122         for i in range(x.shape[0]):
00123             for j in range(x.shape[1]):
00124                 for k in range(x.shape[2]):
00125                     if not (x[i][j][k]):
00126                         return false
00127     if len(x.shape)==4:
00128         for i in range(x.shape[0]):
00129             for j in range(x.shape[1]):
00130                 for k in range(x.shape[2]):
00131                     for l in range(x.shape[3]):
00132                         if not (x[i][j][k][l]):
00133                             return false
00134     if len(x.shape)>4:
00135         stop('unhandled array shape in alltrue')
00136     return true
00137 
00138 def alleq(x,y,tolerance=0):
00139     if x.size != y.size:
00140         print "x.size=", x.size
00141         print "y.size=", y.size
00142         return false
00143     if len(x.shape)==1:
00144         for i in range(x.shape[0]):
00145             if not (abs(x[i]-y[i]) < tolerance):
00146                 print "x[",i,"]=", x[i]
00147                 print "y[",i,"]=", y[i]
00148                 return false
00149     if len(x.shape)==2:
00150         for i in range(x.shape[0]):
00151             for j in range(x.shape[1]):
00152                 if not (abs(x[i][j]-y[i][j]) < tolerance):
00153                     print "x[",i,"][",j,"]=", x[i][j]
00154                     print "y[",i,"][",j,"]=", y[i][j]
00155                     return false
00156     if len(x.shape)==3:
00157         for i in range(x.shape[0]):
00158             for j in range(x.shape[1]):
00159                 for k in range(x.shape[2]):
00160                     if not (abs(x[i][j][k]-y[i][j][k]) < tolerance):
00161                         print "x[",i,"][",j,"][",k,"]=", x[i][j][k]
00162                         print "y[",i,"][",j,"][",k,"]=", y[i][j][k]
00163                         return false
00164     if len(x.shape)==4:
00165         for i in range(x.shape[0]):
00166             for j in range(x.shape[1]):
00167                 for k in range(x.shape[2]):
00168                     for l in range(x.shape[3]):
00169                         if not (abs(x[i][j][k][l]-y[i][j][k][l]) < tolerance):
00170                             print "x[",i,"][",j,"][",k,"][",l,"]=", x[i][j][k][l]
00171                             print "y[",i,"][",j,"][",k,"][",l,"]=", y[i][j][k][l]
00172                             return false
00173     if len(x.shape)>4:
00174         stop('unhandled array shape in alleq')
00175     return true
00176 
00177 def alleqnum(x,num,tolerance=0):
00178     if len(x.shape)==1:
00179         for i in range(x.shape[0]):
00180             if not (abs(x[i]-num) < tolerance):
00181                 print "x[",i,"]=", x[i]
00182                 return false
00183     if len(x.shape)==2:
00184         for i in range(x.shape[0]):
00185             for j in range(x.shape[1]):
00186                 if not (abs(x[i][j]-num) < tolerance):
00187                     print "x[",i,"][",j,"]=", x[i][j]
00188                     return false
00189     if len(x.shape)==3:
00190         for i in range(x.shape[0]):
00191             for j in range(x.shape[1]):
00192                 for k in range(x.shape[2]):
00193                     if not (abs(x[i][j][k]-num) < tolerance):
00194                         print "x[",i,"][",j,"][",k,"]=", x[i][j][k]
00195                         return false
00196     if len(x.shape)==4:
00197         for i in range(x.shape[0]):
00198             for j in range(x.shape[1]):
00199                 for k in range(x.shape[2]):
00200                     for l in range(x.shape[3]):
00201                         if not (abs(x[i][j][k][l]-num) < tolerance):
00202                             print "x[",i,"][",j,"][",k,"][",l,"]=", x[i][j][k]
00203                             return false
00204     if len(x.shape)>4:
00205         stop('unhandled array shape in alleq')
00206     return true
00207 
00208 def datamax(x):
00209     if len(x.shape)==1:
00210         dmax = x[0]
00211         for i in range(x.shape[0]):
00212             if dmax < x[i]: dmax = x[i]
00213         return dmax
00214     if len(x.shape)==2:
00215         dmax = x[0][0]
00216         for i in range(x.shape[0]):
00217             for j in range(x.shape[1]):
00218                 if dmax < x[i][j]: dmax = x[i][j]
00219         return dmax
00220     if len(x.shape)==3:
00221         dmax = x[0][0][0]
00222         for i in range(x.shape[0]):
00223             for j in range(x.shape[1]):
00224                 for k in range(x.shape[2]):
00225                     if dmax < x[i][j][k]: dmax = x[i][j][k]
00226         return dmax
00227     if len(x.shape)==4:
00228         dmax = x[0][0][0][0]
00229         for i in range(x.shape[0]):
00230             for j in range(x.shape[1]):
00231                 for k in range(x.shape[2]):
00232                     for l in range(x.shape[3]):
00233                         if dmax < x[i][j][k][l]: dmax = x[i][j][k][l]
00234         return dmax
00235     if len(x.shape)>4:
00236         stop('unhandled array shape in max')
00237 
00238 def imagedemo():
00239     #
00240     # Cleanup
00241     #
00242     def cleanup(dir):
00243         if (os.path.isdir(dir)):
00244             info("Cleaning up directory "+dir)
00245             def errFunc(raiser, problemPath, excInfo):
00246                 note(raiser.__name__+'failed on'+problemPath,"SEVERE")
00247                 raise RuntimeError, "Cleanup of " + dir + " fails!"
00248             shutil.rmtree(dir,0,errFunc)
00249         return true
00250 
00251     demodir = "./demoimage_temp"
00252     if not cleanup(demodir): fail()
00253 
00254     #
00255     # Make directory
00256     #
00257     try:
00258         os.mkdir(demodir,0770)
00259     except IOError, e:
00260         note(e, "SEVERE")
00261         raise RuntimeError, "Failed to make directory " + demodir
00262     #
00263     # Manufacture some data   
00264     #
00265     nx = 10; ny = 20; nz = 5
00266     data = ia.makearray(0, [nx,ny,nz])
00267     file = demodir+"/demoimage.image"
00268     ia.fromarray(file,data)
00269     note('Created image='+ ia.name(), origin="imagedemo")
00270     for k in range(0,nz):
00271         slice = ia.getchunk(blc=[0,0,k], trc=[nx-1,ny-1,k], list=F)
00272         for i in range(0,nx):
00273             slice[i]=list(slice[i])
00274             for j in range(0,ny):
00275                 slice[i][j] = k+1
00276             slice[i]=tuple(slice[i])
00277         ok = ia.putchunk(pixels=slice, blc=[0,0,k], list=F)
00278         if not ok: fail('putchunk failed')
00279         note('Set plane ' + str(k) + ' to ' + str(k), origin='imagedemo()')
00280     stats = ia.statistics(axes=[0,1],async=F)
00281     #
00282     file = demodir + '/DEMOIMAGE.FITS'
00283     ok = ia.tofits(file)
00284     if not ok: fail('tofits failed')
00285     ia.close()
00286     note('Created fits file=' + file, origin='imagedemo')
00287     return cleanup(demodir)
00288 
00289 def imagetest(which=None, size=[32,32,8]):
00290     #
00291     dowait = true
00292 
00293     def stop(message):
00294         note(message, priority='SEVERE',origin='imagetest()')
00295         raise RuntimeError, message
00296 
00297     def cleanup(dir):
00298         if (os.path.isdir(dir)):
00299             info("Cleaning up directory "+dir)
00300             def errFunc(raiser, problemPath, excInfo):
00301                 note(raiser.__name__+'failed on'+problemPath,"SEVERE")
00302                 raise RuntimeError, "Cleanup of " + dir + " fails!"
00303             shutil.rmtree(dir,0,errFunc)
00304         return true
00305 
00306     def compareComponentList(cl0, cl1, tol=0.005, dotype=T):
00307         n0 = cl0.length()
00308         n1 = cl1.length()
00309         errmsg = 'compareComponentList: '
00310         if (n0 != n1):
00311             errmsg += 'Number of components differ'
00312             print cl0.torecord()
00313             print cl1.torecord()
00314             info(errmsg)
00315             return False
00316         #
00317         for i in range(0,n0):
00318             f0 = cl0.getfluxvalue(i)
00319             f1 = cl1.getfluxvalue(i)
00320             t = tol * f0[0]
00321             if not alleq(array(f1),array(f0),tolerance=t):
00322                 errmsg +='Component fluxes differ'
00323                 info(errmsg)
00324                 return False
00325             #
00326             shp0 = cl0.getshape(i)
00327             shp1 = cl1.getshape(i)
00328             type0 = cl0.shapetype(i)
00329             type1 = cl1.shapetype(i)
00330             if (dotype and type0!=type1):
00331                 errmsg+='Component types differ'
00332                 info(errmsg)
00333                 return False
00334             #
00335             dir0 = cl0.getrefdir(i)
00336             dir1 = cl1.getrefdir(i)
00337             #
00338             v0 = me.getvalue(dir0)
00339             v1 = me.getvalue(dir1)
00340             #
00341             d = abs(qa.convert(v1['m0'],v0['m0']['unit'])['value'] - v0['m0']['value'])
00342             t = tol * abs(v0['m0']['value'])
00343             if (d > t):
00344                 errmsg+='Longitudes differ'
00345                 info(errmsg)
00346                 return False
00347             #
00348             d = abs(qa.convert(v1['m1'],v0['m1']['unit'])['value'] - v0['m1']['value'])
00349             t = tol * abs(v0['m1']['value'])
00350             if (d > t):
00351                 errmsg+='Latitudes differ'
00352                 info(errmsg)
00353                 return False
00354             #
00355             if dotype and (type0=='Gaussian' or type1=='Disk'):
00356                 q0 = shp0['majoraxis']
00357                 q1 = shp1['majoraxis']
00358                 d = abs(qa.convert(q1,q0['unit'])['value']  - q0['value'])
00359                 t = tol * q0['value']
00360                 if (d > t):
00361                     errmsg+='Major axes differ'
00362                     info(errmsg)
00363                     return False
00364                 #
00365                 q0 = shp0['minoraxis']
00366                 q1 = shp1['minoraxis']
00367                 d = abs(qa.convert(q1,q0['unit'])['value']  - q0['value'])
00368                 t = tol * q0['value'];
00369                 if (d > t):
00370                     errmsg+='Minor axes differ'
00371                     info(errmsg)
00372                     return False
00373                 #
00374                 q0 = shp0['positionangle']
00375                 q1 = shp1['positionangle']
00376                 d = abs(qa.convert(q1,q0['unit'])['value']  - q0['value'])
00377                 t = tol * q0['value']
00378                 if (d > t):
00379                     errmsg+='Position angles differ'
00380                     info(errmsg)
00381                     return False
00382             #
00383         return True
00384 
00385     def deconvolveTest(myim, majIn, minIn, paIn, iTest):
00386         smaj = str(majIn) + 'arcsec'
00387         smin = str(minIn) + 'arcsec'
00388         spa  = str(paIn) + 'deg'
00389         #
00390         ok = myim.setrestoringbeam(major=smaj, minor=smin, pa=spa, log=F)
00391         if not ok: fail('failed setrestoringbeam in deconvolveTest')
00392         beam = myim.restoringbeam()
00393         if not beam: fail('failed restoringbeam in deconvolveTest')
00394         #
00395         # Very simple test. Align major axis of source with beam.
00396         #
00397         newcl = cltool()
00398         newcl.simulate(1)
00399         #
00400         major = qa.quantity(1.5*majIn, 'arcsec')
00401         minor = qa.quantity(1.5*minIn, 'arcsec')
00402         pa = qa.quantity(spa)
00403         newcl.setshape(which=0, type='Gaussian', majoraxis=major,
00404                     minoraxis=minor, positionangle=pa,
00405                     majoraxiserror='0arcsec', minoraxiserror='0arcsec',
00406                     positionangleerror='0deg', log=F)
00407         #
00408         mycs = myim.coordsys()
00409         refval = mycs.referencevalue(type='dir', format='q')
00410         newcl.setrefdir(which=0, ra=refval['quantity']['*1'],
00411                      dec=refval['quantity']['*2'],
00412                      log=F)
00413         #
00414         cl2 = myim.deconvolvecomponentlist(newcl.torecord())
00415         if not cl2:
00416             stop ('deconvolvecomponentlist 1 failed')
00417         cl2tool = cltool()
00418         cl2tool.fromrecord(cl2)
00419         shape = cl2tool.getshape(0)
00420         #
00421         majin = major['value']
00422         minin = minor['value']
00423         pain = qa.convert(pa,'deg')['value']
00424         majout = shape['majoraxis']['value']
00425         minout = shape['minoraxis']['value']
00426         paout = qa.convert(shape['positionangle'],'deg')['value']
00427         bmaj = beam['major']['value']
00428         bmin = beam['minor']['value']
00429         #
00430         e1 = math.sqrt(majin*majin - bmaj*bmaj)
00431         d1 = abs(e1 - majout)
00432         e2 = math.sqrt(minin*minin - bmin*bmin)
00433         d2 = abs(e2 - minout)
00434         #
00435         t1 = zeroToPi (paout)
00436         t2 = zeroToPi (pain)
00437         d3 = abs(t1-t2)
00438         if (d1>1e-5 or d2>1e-5 or d3>1e-5):
00439             msg = 'deconvolvecomponentlist ' + str(iTest) + ' gave wrong results'
00440             fail(msg)
00441         #
00442         if not newcl.done(): fail('failed done')
00443         if not cl2tool.done(): fail('failed done')
00444         return True
00445 
00446     def gaussian(flux, major, minor, pa, dir=None):
00447         newcl = cltool()
00448         newcl.simulate(1,log=F);
00449         #newcl.setspectrum(0)
00450         newcl.setshape(which=0, type='Gaussian',
00451                     majoraxis=major, minoraxis=minor, positionangle=pa,
00452                     majoraxiserror = '0arcsec', minoraxiserror = '0arcsec',
00453                     positionangleerror = '0deg', log=F);
00454         flux2 = [flux, 0, 0, 0];
00455         newcl.setflux(which=0, value=flux2, unit='Jy',
00456                    polarization='Stokes', log=F);
00457         if dir==None:
00458             dir = me.direction('J2000', '0rad', '0rad')
00459         values = me.getvalue(dir);
00460         newcl.setrefdir(which=0, ra=values['m0'], dec=values['m1'], log=F);
00461         return newcl;
00462 
00463     def gaussianarray(nx, ny, height, major, minor, pa):
00464         pa = 0
00465         x = ia.makearray(0.0,[nx,ny])
00466         xc = ((nx - 1)/2)
00467         yc = ((ny - 1)/2)
00468         centre = [xc, yc]
00469         fwhm = [major, minor]
00470         #
00471         for j in range(ny):
00472             for i in range(nx):
00473                 x[i,j] = gaussianfunctional(i, j, 1.0, centre, fwhm, pa)
00474         return x
00475 
00476     def gaussianfunctional(x, y, height, center, fwhm, pa):
00477         x -= center[0]
00478         y -= center[1]
00479         #
00480         pa -= math.pi/2
00481         cpa = math.cos(pa)
00482         spa = math.sin(pa)
00483         if (cpa != 1):
00484             tmp = x
00485             x =  cpa*tmp + spa*y
00486             y = -spa*tmp + cpa*y
00487         #
00488         width=[0,0]
00489         width[0] = fwhm[0] / math.sqrt(math.log(16))
00490         width[1] = fwhm[1] / math.sqrt(math.log(16))
00491         if (width[0] != 1): x = x/width[0]
00492         if (width[1] != 1): y = y/width[1]
00493         #
00494         x *= x
00495         y *= y
00496         #
00497         return height * math.exp(-(x+y))
00498 
00499     def doneAllImageTypes(rec):
00500         names = rec.keys()
00501         for mytype in names:
00502             ok = rec[mytype]['tool'].done()
00503             if not ok: fail()
00504         return True
00505 
00506     def makeAllImageTypes(imshape=[10,10], root="im", data=None,
00507                           includereadonly=true):
00508         rec = {}
00509         # PagedImage
00510         imname=root+"1"
00511         rec["pi"] = {}
00512         if (data==None):
00513             #rec["pi"]["tool"] = ia.newimagefromshape(imname, shape=imshape)
00514             ok = ia.fromshape(imname, shape=imshape)
00515         else:
00516             #rec["pi"]["tool"] = ia.newimagefromarray(imname, pixels=data)
00517             ok = ia.fromarray(imname, pixels=data)
00518         #if not rec["pi"]["tool"]: fail('failed to make PagedImage')
00519         if not ok: fail('failed to make PagedImage')
00520         ia.close()
00521         #rec["pi"]["tool"] = ia.newimage(imname)
00522         rec["pi"]["tool"] = ia.newimagefromfile(imname)
00523         rec["pi"]["type"] = "PagedImage"
00524 
00525         #FITSImage
00526         if includereadonly:
00527             fitsname = imname +'.fits'
00528             ok = rec["pi"]["tool"].tofits(fitsname)
00529             if not ok: fail('failed in tofits')
00530             rec["fi"] = {}
00531             rec["fi"]["tool"] = ia.newimagefromfile(fitsname)
00532             if not rec["fi"]["tool"]: fail('failed to open '+fitsname)
00533             rec["fi"]["type"] = "FITSImage"
00534 
00535         # Virtual: SubImage (make it from another PagedImage so there
00536         # are no locking problems)
00537         if includereadonly:
00538             imname = root+'2'
00539             if not data:
00540                 ok = ia.fromshape(imname, shape=imshape)
00541             else:
00542                 ok = ia.fromarray(imname, pixels=data)
00543             if not ok: fail('failed to make virtual subimage')
00544             ok = ia.close()
00545             if not ok: fail('failed to close image while making virtual subimage')
00546             ok = ia.fromimage(infile=imname)
00547             if not ok: fail('failed in fromimage from '+imname)
00548             #since fromimage no longer returns an image tool use subimage
00549             rec["si"] = {}
00550             rec["si"]["tool"] = ia.subimage()
00551             if not rec["si"]["tool"]: fail('failed to get subimage')
00552             rec["si"]["type"] = "SubImage"  # equivalent to old subimage?
00553 
00554         # Virtual: TempImage
00555         rec["ti"] = {}
00556         if data==None:
00557             rec["ti"]["tool"] = ia.newimagefromshape(shape=imshape)
00558         else:
00559             rec["ti"]["tool"] = ia.newimagefromarray(pixels=data)
00560         if not rec["ti"]["tool"]: fail('failed in Virtual: TempImage')
00561         #rec["ti"]["tool"] = ia.subimage()
00562         #if not rec["ti"]["tool"]: fail('failed to get temporary image')
00563         rec["ti"]["type"] = "TempImage"
00564 
00565         # Virtual: ImageExpr (make it from another PagedImage so there
00566         # are no locking problems)
00567         if includereadonly:
00568             imname = root+'3'
00569             if not data: #(data==None):
00570                 ok = ia.fromshape(imname, shape=imshape)
00571             else:
00572                 ok = ia.fromarray(imname, pixels=data)
00573             if not ok: fail('failed in Virtual: ImageExpr')
00574             if not ia.close(): fail('failed in Virtual: ImageExpr closing file')
00575             expr = '"'+imname+'"'
00576             rec["ie"] = {}
00577             rec["ie"]["tool"] = ia.imagecalc(pixels=expr)
00578             if not rec["ie"]["tool"]: fail('failed in imagecalc')
00579             rec["ie"]["type"] = "ImageExpr"
00580 
00581         # Virtual: ImageConcat (make it from another PagedImage so there
00582         # are no locking problems)
00583         if includereadonly:
00584             imname1 = root +'4'
00585             if not data:
00586                 ok = ia.fromshape(imname1, shape=imshape)
00587             else:
00588                 ok = ia.fromarray(imname1, pixels=data)
00589             if not ok: fail('failed in Virtual: ImageConcat making PagedImage')
00590             if not ia.close(): fail('failed in Virtual: ImageConcat closing PagedImage')
00591             #
00592             imname2 = root + '5'
00593             if not data: #(data==None):
00594                 ok = ia.fromshape(imname2, shape=imshape)
00595             else:
00596                 ok = ia.fromarray(imname2, pixels=data)
00597             if not ok: fail('failed to make ' + imname2)
00598             if not  ia.close(): fail('failed to close ' + imname2)
00599             #
00600             files = [imname1, imname2]
00601             rec["ic"] = {}
00602             rec["ic"]["tool"] = ia.imageconcat(infiles=files, axis=0, relax=T, tempclose=F)
00603             if not rec["ic"]["tool"]: fail('failed in imageconcat')
00604             rec["ic"]["type"] = "ImageConcat"
00605 
00606         return rec
00607 
00608     # 3D only
00609     def make_data(imshape):
00610         data = ia.makearray(0, imshape)
00611         for i in range(imshape[0]):
00612             data[i] = list(data[i])
00613             for j in range(imshape[1]):
00614                 data[i][j] = list(data[i][j])
00615                 for k in range(imshape[2]):
00616                     data[i][j][k] = (k+1) + (j+1)*imshape[0] + (i+1)
00617                 data[i][j] = tuple(data[i][j])
00618             data[i] = tuple(data[i])
00619         return data
00620 
00621 
00622     # 3D only
00623     def pick(imshape, data, inc):
00624         idxx = range(0,imshape[0],inc[0])  #range doesn't include maxval
00625         idxy = range(0,imshape[1],inc[1])
00626         idxz = range(0,imshape[2],inc[2])
00627         data2 = ia.makearray(0,[len(idxx),len(idxy),len(idxz)])
00628         kk = 0
00629         for k in idxz:
00630             jj = 0
00631             for j in idxy:
00632                 ii = 0
00633                 for i in idxx:
00634                     data2[ii,jj,kk] = data[i, j, k]
00635                     ii += 1
00636                 jj += 1
00637             kk += 1
00638         return data2
00639 
00640     def fitsreflect(imagefile, fitsfile, do16=false):
00641         #
00642         # imagefile can be file name or image object
00643         #
00644         myim = imagefile;
00645         opened = F
00646         try:
00647             if (myim.type()=='image'):
00648                 pass
00649         except Exception, e:
00650             myim = ia.newimagefromfile(imagefile);
00651             if not myim:
00652                 stop('fitsreflect: image constructor failed');
00653             opened = T
00654         mi = myim.miscinfo()
00655         mi['hello'] = 'hello'
00656         mi['world'] = 'world';
00657         ok = myim.setmiscinfo(mi)
00658         if not ok:
00659             raise RuntimeError, 'setmiscinfo failed in fitsreflect'
00660         myim.sethistory(history=["A","B","C","D"])
00661         history = myim.history(F,F)
00662         #
00663         p1 = myim.getregion()
00664         m1 = myim.getregion(getmask=T)
00665         if len(p1)==0 or len(m1)==0:
00666             raise RuntimeError, 'getregion 1 failed in fitsreflect'
00667         imshape = myim.shape()
00668         m0=m1
00669         m1[0,0,0] = F
00670         m1[imshape[0]-1,imshape[1]-1,imshape[2]-1] = F
00671         ok = myim.putregion(pixelmask=m1)
00672         if not ok:
00673             raise RuntimeError, 'putregion 1 failed in fitsreflect'
00674         #
00675         bitpix = -32
00676         if do16: bitpix = 16
00677         ok = myim.tofits(outfile=fitsfile, bitpix=bitpix)
00678         if not ok:
00679             raise RuntimeError, 'tofits failed in fitsreflect'
00680         #
00681         testdir = os.path.dirname(fitsfile)
00682         imname2 = testdir +'/fitsreflect.image'
00683         myim2 = ia.newimagefromfits(outfile=imname2, infile=fitsfile)
00684         if not ok:
00685             raise RuntimeError, 'ia.newimagefromfits failed in fitsreflect'
00686         p1 = myim.getregion()
00687         m1 = myim.getregion(getmask=T)
00688         if len(p1)==0 or len(m1)==0:
00689             return throw('getregion 2 failed', origin='fitsreflect')
00690         p2 = myim2.getregion()
00691         m2 = myim2.getregion(getmask=T)
00692         if len(p2)==0 or len(m2)==0:
00693             stop('fitsreflect: getregion 3 failed')
00694         if not allbooleq(m2,m1):
00695             raise RuntimeError, 'Some mask values have changed in FITS reflection'
00696         #
00697         d = p2-p1
00698         sh = d.shape
00699         for i in range(sh[0]):
00700             for j in range(sh[1]):
00701                 for k in range(sh[2]):
00702                     if m1[i][j][k]==true:
00703                         if not (abs(d[i][j][k]) < 0.0001):
00704                             raise RuntimeError, 'Some values have changed in FITS reflection'
00705         ok = myim.putregion(pixelmask=m0);
00706         if not ok:
00707             raise RuntimeError, 'putregion 2 failed in fitsreflect'
00708         #
00709         mi = myim2.miscinfo();
00710         if not (mi['hello'] == 'hello') or not (mi['world'] == 'world'):
00711             raise RuntimeError, 'miscinfo changed after fits in fitsreflect'
00712         #
00713         history2 = myim2.history(F,F);
00714         #Behaviour of history logged in FITS changed (2007/10/02)
00715         #Grab just the messages (indices 2, 4, 6, ...)
00716         #
00717         # funny things are happening here with move to casacore
00718         #
00719         history3=[]
00720         for i in range(len(history2)/2 - 1):
00721             history3.append(history2[2*(i+1)])
00722         if not all(history,history2):
00723             print "history written=", history
00724             print "history retrieved=", history2
00725             raise RuntimeError, 'history changed after fits in fitsreflect'
00726         #
00727         ok = myim2.done();
00728         if not ok:
00729             raise RuntimeError, 'done 1 failed in fitsreflect'
00730         if opened:
00731             ok = myim.done();
00732             if not ok:
00733                 raise RuntimeError, 'done 2 failed in fitsreflect'
00734         #
00735         os.remove(fitsfile)
00736         ok = cleanup(imname2)
00737         if not ok:
00738             raise RuntimeError, 'image file deletion failed in fitsreflect'
00739         return true
00740 
00741     def coordcheck(im1, axes, testdir):
00742         #im1 = ia.newimage(im1name)
00743         ok = im1.summary(list=F)
00744         if not ok:
00745             fail('summary 1 failed in coordcheck')
00746         rec1 = ok
00747         imname = testdir + "/" + "coordcheck.image"
00748         cs2 = im1.coordsys(axes)
00749         if not cs2:
00750             fail('coordsys 1 failed in coordcheck')
00751         shape2=[]
00752         tmp = im1.shape()
00753         print tmp
00754         for i in axes:
00755             shape2.append(tmp[i])
00756             print tmp[i]
00757         print 'shape2 is ', type(shape2), shape2
00758         ok = ia.fromshape(imname, shape2, cs2.torecord())
00759         if not ok:
00760             fail('ia.fromshape 1 failed in coordcheck');
00761         ia.close()  # close coordcheck.image
00762         im2 = ia.newimage(imname)
00763         ok = im2.summary(list=F)
00764         if not ok:
00765             fail('summary 2 failed in coordcheck')
00766         rec2 = ok
00767         #
00768         if rec1.has_key('axisnames') and rec2.has_key('axisnames'):
00769             rec1axes=[]
00770             for i in axes:
00771                 rec1axes.append(rec1['axisnames'][i])
00772             if not all(rec1axes,rec2['axisnames']):
00773                 note('axisnames mismatch')
00774                 return false
00775         else:
00776             note('axisnames key missing')
00777             return false
00778         #
00779         if rec1.has_key('refpix') and rec2.has_key('refpix'):
00780             rec1axes=[]
00781             for i in axes:
00782                 rec1axes.append(rec1['refpix'][i])
00783             if not all(rec1axes,rec2['refpix']):
00784                 note('refpix mismatch')
00785                 return false
00786         else:
00787             note('refpix key missing')
00788             return false
00789         #
00790         if rec1.has_key('refval') and rec2.has_key('refval'):
00791             rec1axes=[]
00792             for i in axes:
00793                 rec1axes.append(rec1['refval'][i])
00794             if not all(rec1axes,rec2['refval']):
00795                 note('refval mismatch')
00796                 return false
00797         else:
00798             note('refval key missing')
00799             return false
00800         #
00801         if rec1.has_key('incr') and rec2.has_key('incr'):
00802             rec1axes=[]
00803             for i in axes:
00804                 rec1axes.append(rec1['incr'][i])
00805             if not all(rec1axes,rec2['incr']):
00806                 note('incr mismatch')
00807                 return false
00808         else:
00809             note('incr key missing')
00810             return false
00811         #
00812         if rec1.has_key('axisunits') and rec2.has_key('axisunits'):
00813             rec1axes=axes
00814             for i in range(len(axes)):
00815                 rec1axes[i]=rec1['axisunits'][i]
00816             if not all(rec1axes,rec2['axisunits']):
00817                 note('axisunits mismatch')
00818                 return false
00819         else:
00820             note('axisunits key missing')
00821             return false
00822         if not im2.remove(done=T):
00823             fail('failed image delete in coordcheck')
00824         if not cs2.done():
00825             fail('failed cs2 done in coordcheck')
00826         return true
00827 
00828 
00829     def zeroToPi(x):
00830         n = int(x / 180.0)
00831         rem = x - n*180.0
00832         #
00833         if (rem < 0): rem += 180.0
00834         return rem
00835 
00836 
00837     def test1():
00838         #
00839         # Test everything a bit
00840         #
00841         info('')
00842         info('')
00843         info('')
00844         info('Test 1 - general')
00845         #
00846         # Make the directory
00847         testdir = 'imagetest_temp'
00848         if not cleanup(testdir):
00849             note("Cleanup failed", "SEVERE")
00850             return false
00851         try:
00852             os.mkdir(testdir)
00853         except IOError, e:
00854             note(e, "SEVERE")
00855             raise RuntimeError, "mkdir " + testdir + " fails!"
00856 
00857         #
00858         # Make some data
00859         #
00860         imshape = [32,32,8]
00861         info("Manufacturing data cube shaped " + str(imshape))
00862         data = make_data(imshape)
00863 
00864         info('z = 1:'+ str(imshape[2])+' + y * '+str(imshape[0])+' + x')
00865         manname = testdir+'/'+'manufactured.im'
00866         info('Turning array into image named ' + manname)
00867         man = ia.newimagefromarray(manname, data)
00868         if not man:
00869             stop('ia.fromarray constructor 1 fails')
00870         #
00871         info('Trying close')
00872         ok = man.close()
00873         if not ok:
00874             stop('Close failed')
00875         info('')
00876         #
00877         info('Trying open')
00878         ok = man.open(manname)
00879         if not ok:
00880             stop('Open failed')
00881         info('')
00882         #
00883         info('Trying rename')
00884         manname2 = testdir+'/'+'manufactured.im_rename'
00885         ok = man.rename(manname2)
00886         if not ok:
00887             stop('Rename of', manname, ' to ', manname2, 'fails')
00888         info('')
00889         #
00890         info('Trying remove')
00891         ok = man.remove(done=T)
00892         if not ok:
00893             stop('Remove of ', mannam2, 'fails')
00894         info('')
00895         #
00896         info('Remake the image')
00897         man = ia.newimagefromarray(manname, data)
00898         if not man:
00899             stop('ia.fromarray constructor fails')
00900         ok = man.done()
00901         if not ok:
00902             stop('Done 1 fails')
00903         #
00904         info('Trying image(...)')
00905         man = ia.newimagefromfile(manname)
00906         if not man:
00907             stop('image constructor 1 failed')
00908         info('')
00909 
00910         # verify the shape
00911         info('Verifying shape')
00912         if not all(man.shape(),imshape):
00913             stop('Shape of image is wrong:'+str(man.shape()))
00914         info('')
00915 
00916         # verify the name
00917         info('Verifying name');
00918         fullname = os.path.abspath(manname)
00919         if (man.name(strippath=F) != fullname):
00920             stop('The name is wrong: ', man.name())
00921         info('')
00922 
00923         # verify bounding box of default region
00924         info('Verifying default bounding box');
00925         bb = man.boundingbox(rg.box())
00926         actualStart = man.shape()
00927         actualEnd = man.shape()
00928         for i in range(len(actualStart)):
00929             actualStart[i] = 0
00930             actualEnd[i] = actualEnd[i]-1
00931         if not all(bb['blc'],actualStart) or not all(bb['trc'],actualEnd):
00932             msg = 'The default bounding box '+str(bb['blc'])+str(bb['trc'])+' is wrong'
00933             stop(msg)
00934         info('')
00935 
00936         # Summarise the image
00937         info('Summarize image');
00938         header = man.summary()
00939         info('')
00940 
00941         # Do statistics
00942         info('Find statistics')
00943         stuff = man.statistics()
00944         if not stuff: fail()
00945         info('')
00946 
00947         # Do histograms
00948         info('Find histograms')
00949         ok = man.histograms()
00950         print ok
00951         if not ok: fail()
00952         stuff = ok['counts']
00953         info('')
00954 
00955         # Find coordinates
00956         info('Verify coordinates')
00957         refPix = header['refpix']
00958         world = man.toworld(list(refPix), 'n')
00959         pixel = man.topixel(world)['numeric']
00960         if not alleq(refPix,pixel,tolerance=.0001):
00961             stop('Coordinate reflection failed')
00962         info('')
00963 
00964         # Fish out coordinates as measures
00965         info('Get coordinates as measures')
00966         rec = man.coordmeasures(list(pixel))
00967         info('')
00968 
00969         # Fish out CoordinateSYStem
00970         info('Get CoordinateSystem')
00971         csys = man.coordsys()
00972         if not csys:
00973             stop('Coordinate recovery failed')
00974         ok = csys.done()
00975         if not ok: fail()
00976 
00977         # Get/put region (mask is T at present)
00978         info('Verify get/putregion')
00979         trc = [imshape[0]-1,imshape[1]-1,0]
00980         r = rg.box([0,0,0], trc)
00981         pixels = man.getregion(region=r, list=F, dropdeg=F)
00982         mask = man.getregion(getmask=true, region=r, list=F, dropdeg=F)
00983         if len(pixels)==0 or len(mask)==0:
00984             stop('getregion 1 failed')
00985         pixels2 = ia.makearray(0,list(pixels.shape))  # don't set pixel2=pixels
00986         mask2 = ia.makearray(1,list(mask.shape))      # don't set mask2=mask
00987         for i in range(pixels2.shape[0]):
00988             for j in range(pixels2.shape[1]):
00989                 for k in range(pixels2.shape[2]):
00990                     pixels2[i][j][k]=pixels[i][j][k]
00991                     mask2[i][j][k]=mask[i][j][k]
00992         pixels2[0,0,0] = -10
00993         pixels2[imshape[0]-1,imshape[1]-1,0] = -10
00994         ok = man.putregion(pixels=pixels2, pixelmask=mask2, region=r)
00995         if not ok:
00996             stop('putregion 1 failed')
00997         pixels3 = man.getregion(region=r, dropdeg=F)
00998         mask3 = man.getregion(getmask=true, region=r, dropdeg=F)
00999         if not ok:
01000             stop('getregion 2 failed')
01001         if not alleq(pixels3,pixels2,tolerance=.00001) or not allbooleq(mask3,mask2):
01002             stop ('get/putregion reflection failed')
01003         ok = man.putregion(pixels=pixels, pixelmask=mask, region=r)
01004         if not ok:
01005             stop('putregion 2 failed')
01006         info('')
01007 
01008         # Subimage
01009         info('Subimage')
01010         trc = [imshape[0]-1,imshape[1]-1,imshape[2]-1]
01011         trc[2] = 0
01012         r = rg.box([0,0,0], trc)
01013         pixels = man.getregion(region=r, dropdeg=F)
01014         mask = man.getregion(getmask=true, region=r, dropdeg=F)
01015         if len(pixels)==0 or len(mask)==0:
01016             stop('getregion 3 failed')
01017         if not man: fail()
01018         man3 = man.subimage(region=r)
01019         if not man3:
01020             stop('subimage 1 failed')
01021         pixels2 = man3.getregion(region=rg.box(), dropdeg=F)
01022         mask2 = man3.getregion(getmask=true, region=rg.box(), dropdeg=F)
01023         if len(pixels2)==0 or len(mask2)==0:
01024             stop('getregion 4 failed')
01025         if not alleq(pixels,pixels2,tolerance=.00001) or not allbooleq(mask,mask2):
01026             stop('SubImage got wrong results')
01027         ok = man3.done()
01028         if not ok:
01029             stop('Done 2 fails')
01030 
01031         # Do moments
01032         info('Find moments')
01033         ok = man.moments(axis=2)
01034         if not ok: fail()
01035         ok.done()
01036         info('')
01037 
01038         # Do Hanning
01039         info('Hanning smooth')
01040         man3 = man.hanning(axis=2, drop=F)
01041         if not man3:
01042             stop('Hanning fails')
01043         ok = man3.done()
01044         if not ok:
01045             stop('Done 3 fails')
01046         info('')
01047 
01048         # Do insert
01049         info('Insert')
01050         padshape = [imshape[0]+2,imshape[1]+2,imshape[2]+2]
01051         man3 = ia.newimagefromshape(shape=padshape)
01052         stats1 = man3.statistics()
01053         ok = man3.insert(infile=man.name(F), locate=[2,2,2]) 
01054         if not ok:
01055             stop('insert 1 fails')
01056         stats2 = man3.statistics()
01057         if stats1['sigma'][0] >= stats2['sigma'][0]: fail()
01058         ok = man3.done()
01059         if not ok:
01060             stop('Done 4 fails')
01061         info('')
01062 
01063         # Read the data in various directions
01064         info('Starting read/compare tests....')
01065         info('XY plane by XY plane')
01066         t = time.time()
01067         for i in range(imshape[2]):
01068             data2 = man.getchunk(blc=[0,0,i],
01069                                  trc=[imshape[0]-1,imshape[1]-1,i],
01070                                  list=F)
01071             len_data2 = 1
01072             for idx in data2.shape: len_data2 *= idx
01073             if (len_data2 != imshape[0]*imshape[1]):
01074                 stop('Not enough data read')
01075             for j in range(imshape[0]):
01076                 for k in range(imshape[1]):
01077                     data2[j][k][0] = abs(data2[j][k][0]-data[j][k][i])
01078 
01079         rate = imshape[0]*imshape[1]*imshape[2]/(time.time() - t)/1.0e+6
01080         #rate::print.precision = 3
01081         info('            OK ('+ str(rate)+ 'M pix/s)')
01082 
01083         info('XZ plane by XZ plane')
01084         t = time.time()
01085         for i in range(imshape[1]):
01086             data2 = man.getchunk(blc=[0,i,0],
01087                                  trc=[imshape[0]-1,i,imshape[2]-1],
01088                                  list=F)
01089             len_data2 = 1
01090             for idx in data2.shape: len_data2 *= idx
01091             if (len_data2 != imshape[0]*imshape[2]):
01092                 stop('Not enough data read')
01093             for j in range(imshape[0]):
01094                 for k in range(imshape[2]):
01095                     data2[j][0][k] = abs(data2[j][0][k]-data[j][i][k])
01096             if not alleqnum(data2,0.0,tolerance=0.0001):
01097                 dmax = datamax(data2)
01098                 stop('Some values have changed, max deviation='+ str(max))
01099         rate = imshape[0]*imshape[1]*imshape[2]/(time.time() - t)/1.0e+6
01100         #rate::print.precision = 3
01101         info('            OK ('+ str(rate)+ 'M pix/s)')
01102 
01103         info('X row by X row')
01104         t = time.time()
01105         for j in range(imshape[2]):
01106             for i in range(imshape[1]):
01107                 data2 = man.getchunk(blc=[0,i,j],
01108                                      trc=[imshape[0]-1,i,j],
01109                                      list=F)
01110                 len_data2 = 1
01111                 for idx in data2.shape: len_data2 *= idx
01112                 if (len_data2 != imshape[0]):
01113                     stop('Not enough data read')
01114                 for k in range(imshape[0]):
01115                     data2[k][0][0] = abs(data2[k][0][0] - data[k][i][j])
01116                 if not alleqnum(data2,0.0,tolerance=0.0001):
01117                     dmax = datamax(data2)
01118                     stop('Some values have changed, max deviation='+str(dmax))
01119         rate = imshape[0]*imshape[1]*imshape[2]/(time.time() - t)/1.0e+6
01120         #rate::print.precision = 3
01121         info('            OK (' + str(rate) + 'M pix/s)')
01122 
01123         info('Z row by Z row')
01124         t = time.time()
01125         for j in range(imshape[1]):
01126             for i in range(imshape[0]):
01127                 data2 = man.getchunk(blc=[i,j,0],
01128                                      trc=[i,j,imshape[2]],
01129                                      list=F)
01130                 len_data2 = 1
01131                 for idx in data2.shape: len_data2 *= idx
01132                 if (len_data2 != imshape[2]):
01133                     stop('Not enough data read')
01134 
01135                 for k in range(imshape[2]):
01136                     data2[0][0][k] = abs(data2[0][0][k] - data[i][j][k])
01137                 if not alleqnum(data2,0.0,tolerance=0.0001):
01138                     dmax = datamax(data2)
01139                     stop('Some values have changed, max deviation='+str(dmax))
01140         rate = imshape[0]*imshape[1]*imshape[2]/(time.time() - t)/1.0e+6
01141         #rate::print.precision = 3
01142         info('            OK (' + str(rate) + 'M pix/s)')
01143 
01144         info('Check get/set miscinfo')
01145         mi = {'hello':('world'), 'foo':('bar'), 'answer':(42)}
01146         ok = man.setmiscinfo(mi)
01147         if not ok: stop('Error in setmiscinfo')
01148         mi = man.miscinfo()
01149         if (len(mi) != 3 or mi['hello'] != 'world' or mi['foo'] != 'bar' or
01150             mi['answer'] != 42):
01151             stop('Error in miscinfo ' + str(mi))
01152 
01153         info('Reflect file through fits and look for changes in data values and miscinfo')
01154         mannamefits = manname + '.fits'
01155         ok = fitsreflect (man, mannamefits)
01156         if not ok: fail()
01157 
01158         # close
01159         ok = man.done();
01160         if not ok:
01161             stop('Done 5 fails')
01162         #
01163         return cleanup(testdir)
01164 
01165         
01166     def test2():
01167         #
01168         # Test constructors
01169         #
01170         info('')
01171         info('')
01172         info('')
01173         info('Test 2 - ia.fromshape constructor')
01174         #
01175         # Make the directory
01176         testdir = 'imagetest_temp'
01177         if not cleanup(testdir):
01178             note("Cleanup failed", "SEVERE")
01179             return false
01180         try:
01181             os.mkdir(testdir)
01182         except IOError, e:
01183             note(e, "SEVERE")
01184             raise RuntimeError, "mkdir " + testdir + " fails!"
01185 
01186         #
01187         imname = testdir+'/'+'ia.fromshape.image'
01188         try:
01189             myim = true
01190             note('Expect SEVERE error and Exception here')
01191             myim = ia.newimagefromshape(shape='fish')
01192         except Exception, e:
01193             note('Caught expected Exception:'+str(e))
01194             myim = false
01195         if myim:
01196             stop('ia.fromshape constructor 1 unexpectedly did not fail')
01197 
01198         try:
01199             myim = true
01200             note('Expect SEVERE error and Exception here')
01201             myim = ia.newimagefromshape(outfile=[10,20], shape=[10,20])
01202         except Exception, e:
01203             note('Caught expected Exception')
01204             myim = false
01205         if myim:
01206             stop('ia.fromshape constructor 2 unexpectedly did not fail')
01207 
01208         myim = ia.newimagefromshape(outfile=imname, shape=[10,20])
01209         if not myim:
01210             stop('ia.fromshape constructor 3 failed')
01211         pixels = myim.getregion()
01212         mask = myim.getregion(getmask=true)
01213         if not alleqnum(pixels,0.0,tolerance=0.00001):
01214             stop('ia.fromshape constructor 3 pixels are not all zero')
01215         if not alltrue(mask):
01216             stop('ia.fromshape constructor 3 mask is not all T')
01217         csys = myim.coordsys()
01218         if not csys:
01219             stop('coordsys 1 failed')
01220         ok = myim.remove(done=T)
01221         if not ok:
01222             stop('Delete 1 of', imname, ' failed')
01223 
01224         #
01225         try:
01226            note('Expect SEVERE error here')
01227            myim = ia.newimagefromshape(shape=[10,20], csys='xyz')
01228            if myim and myim.name()!="none":
01229                stop('ia.fromshape constructor 4 unexpectedly did not fail')
01230            else:
01231                note('Expected SEVERE error occurred')
01232         except Exception, e:
01233             note('Caught expected Exception')
01234             myim = false
01235         myim = ia.newimagefromshape(shape=[10,20], csys=csys.torecord())
01236         if not myim:
01237             stop('ia.fromshape constructor 5 failed')
01238         csysRec = csys.torecord()
01239         csys2 = myim.coordsys()
01240         if not csys2:
01241             stop('coordsys 2 failed')
01242         csys2Rec = csys2.torecord()
01243         if not all(csysRec.keys(),csys2Rec.keys()):
01244             stop('coordinates from ia.fromshape 5 are wrong')
01245         ok = myim.done()
01246         if not ok: fail()
01247         if not csys.done(): fail()
01248         if not csys2.done(): fail()
01249         #
01250         # Try a few different shapes to test out the standard coordinate
01251         # system making of CoordinateUtil
01252         #
01253         myim = ia.newimagefromshape(shape=[10])
01254         if not myim:
01255             stop('ia.fromshape constructor 6 failed')
01256         ok = myim.done()
01257         if not ok: fail()
01258         myim = ia.newimagefromshape(shape=[10,20])
01259         if not myim:
01260             stop('ia.fromshape constructor 7 failed')
01261         ok = myim.done()
01262         if not ok: fail()
01263         myim = ia.newimagefromshape(shape=[10,20,4])
01264         if not myim:
01265             stop('ia.fromshape constructor 8 failed')
01266         ok = myim.done()
01267         if not ok: fail()
01268         myim = ia.newimagefromshape(shape=[10,20,4,16])
01269         if not myim:
01270             stop('ia.fromshape constructor 9 failed')
01271         ok = myim.done()
01272         if not ok: fail()
01273         myim = ia.newimagefromshape(shape=[10,20,16,4])
01274         if not myim:
01275             stop('ia.fromshape constructor 10 failed')
01276         ok = myim.done()
01277         if not ok: fail()
01278         myim = ia.newimagefromshape(shape=[10,20,16])
01279         if not myim:
01280             stop('ia.fromshape constructor 11 failed')
01281         ok = myim.done()
01282         if not ok: fail()
01283         myim = ia.newimagefromshape(shape=[10,20,16,4,5,6])
01284         if not myim:
01285             stop('ia.fromshape constructor 12 failed')
01286         ok = myim.done()
01287         if not ok: fail()
01288 
01289         ###
01290         return cleanup(testdir)
01291         
01292     def test3():
01293         info('')
01294         info('')
01295         info('')
01296         info('Test 3 - ia.fromarray constructor')
01297 
01298         # Make the directory
01299         testdir = 'imagetest_temp'
01300         if not cleanup(testdir):
01301             note("Cleanup failed", "SEVERE")
01302             return false
01303         try:
01304             os.mkdir(testdir)
01305         except IOError, e:
01306             note(e, "SEVERE")
01307             raise RuntimeError, "mkdir " + testdir + " fails!"
01308 
01309         #
01310         # Make some data
01311         #
01312         imshape = [10,20,30]
01313         data = make_data(imshape)
01314         #
01315         imname = testdir+'/'+'ia.fromarray.image'
01316         try:
01317             myim = true
01318             note('Expect SEVERE error and Exception here')
01319             myim = ia.newimagefromarray(outfile=[10,20], pixels=data)
01320         except Exception, e:
01321             note('Caught expected Exception')
01322             myim = false
01323         if myim:
01324             stop('ia.fromarray constructor 1 unexpectedly did not fail')
01325         myim = ia.newimagefromarray(outfile=imname, pixels=data)
01326         if not myim:
01327             stop('ia.fromarray constructor 2 failed')
01328         pixels = myim.getregion()
01329         mask = myim.getregion(getmask=true)
01330         #data2 = pixels - data
01331         if not alleq(pixels,data,tolerance=0.0001):
01332             stop('ia.fromarray 2 pixels have the wrong value')
01333         if not alltrue(mask):
01334             stop('ia.fromarray 2 mask is not all T')
01335         csys = myim.coordsys()
01336         if not csys:
01337             stop('coordinates 1 failed')
01338         ok = myim.remove(done=T)
01339         if not ok:
01340             stop('Delete 1 of '+imname+' failed')
01341         #
01342         note('Expect SEVERE error here')
01343         try :
01344            myim = ia.newimagefromarray(outfile=imname, pixels=data, csys='xyz')
01345            if myim.isopen():
01346                stop('ia.fromarray constructor 3 unexpectedly did not fail')
01347         except Exception, e :
01348             note('Caught expected Exception')
01349 
01350         myim = ia.newimagefromarray(pixels=data, csys=csys.torecord())
01351         if not myim:
01352             stop('ia.fromarray constructor 4 failed')
01353         csysRec = csys.torecord()
01354         csys2 = myim.coordsys()
01355         if not csys2:
01356             stop('coordinates 2 failed')
01357         csys2Rec = csys2.torecord()
01358         if not all(csysRec.keys(),csys2Rec.keys()):
01359             stop('coordinates from ia.fromarray 4 are wrong')
01360         ok = myim.done()
01361         if not ok: fail()
01362         if not csys.done(): fail()
01363         if not csys2.done(): fail()
01364         ###
01365         return cleanup(testdir)
01366 
01367         
01368     def test4():
01369         info('')
01370         info('')
01371         info('')
01372         info('Test 4 - image constructor')
01373         # Make the directory
01374         testdir = 'imagetest_temp'
01375         if not cleanup(testdir):
01376             note("Cleanup failed", "SEVERE")
01377             return false
01378         try:
01379             os.mkdir(testdir)
01380         except IOError, e:
01381             note(e, "SEVERE")
01382             raise RuntimeError, "mkdir " + testdir + " fails!"
01383 
01384         # Test native aips++ image
01385         imname = testdir+'/'+'image.image'
01386         note('Expect SEVERE error here')
01387         myim = ia.newimage(infile='_doggies')
01388         if myim.isopen():
01389             stop('image constructor 1 unexpectedly did not fail')
01390         myim = ia.newimagefromshape(outfile=imname, shape=[10,20])
01391         if not myim:
01392             stop('ia.fromshape constructor 1 failed')
01393         myim.done()
01394         myim = ia.newimage(infile=imname)
01395         if not myim:
01396             stop('image constructor 2 failed')
01397         pixels = myim.getregion()
01398         mask = myim.getregion(getmask=true)
01399         if not alleqnum(pixels,0.0,tolerance=0.00001):
01400             stop('pixels (1) are not all zero')
01401         if not alltrue(mask):
01402             stop('mask (1) is not all T')
01403         #
01404         fitsname = testdir+'/'+'image.fits'
01405         ok = myim.tofits(fitsname)
01406         if not ok: fail()
01407         #
01408         ok = myim.remove(done=T)
01409         if not ok:
01410             stop('Failed to remove ', imname)
01411 
01412         # Test FITS image
01413         myim = ia.newimage(fitsname)
01414         if not myim:
01415             stop('image constructor 3 failed')
01416         #
01417         pixels = myim.getregion()
01418         mask = myim.getregion(getmask=true)
01419         if len(pixels)==0 or len(mask)==0: fail()
01420         if not alleqnum(pixels,0.0,tolerance=0.00001):
01421             stop('pixels (2) are not all zero')
01422         if not alltrue(mask):
01423             stop('mask (2) is not all T')
01424         if not myim.done(): fail()
01425 
01426         ###
01427         return cleanup(testdir)
01428 
01429         
01430     def test5():
01431         info('')
01432         info('')
01433         info('')
01434         info('Test 5 - ia.fromimage constructor')
01435 
01436         # Make the directory
01437         testdir = 'imagetest_temp'
01438         if not cleanup(testdir):
01439             note("Cleanup failed", "SEVERE")
01440             return false
01441         try:
01442             os.mkdir(testdir)
01443         except IOError, e:
01444             note(e, "SEVERE")
01445             raise RuntimeError, "mkdir " + testdir + " fails!"
01446         #
01447         # Test ia.fromimage constructor
01448         #
01449         info('')
01450         imname = testdir+'/'+'ia.fromshape.image'
01451         imname2 = testdir+'/'+'ia.fromimage.image'
01452         #
01453         #myim = ia.fromimage(outfile=imname2, infile='_doggies')
01454         try:
01455             myim = true
01456             note('Expect SEVERE error and Exception here')
01457             myim = ia.newimagefromimage(outfile=imname2, infile='_doggies')
01458         except Exception, e:
01459             note('Caught expected Exception')
01460             myim = false
01461         if myim:
01462             stop('ia.fromimage constructor 1 unexpectedly did not fail')
01463         #myim = ia.fromimage(outfile=imname2, infile='_doggies',
01464         #                    region='doggies')
01465         try:
01466             myim = true
01467             note('Expect SEVERE error and Exception here')
01468             myim = ia.newimagefromimage(outfile=imname2, infile='_doggies',region='doggies')
01469         except Exception, e:
01470             note('Caught expected Exception')
01471             myim = false
01472         if myim:
01473             stop('ia.fromimage constructor 2 unexpectedly did not fail')
01474         myim = ia.newimagefromshape(outfile=imname, shape=[20,40])
01475         if not myim:
01476             stop('ia.fromshape constructor 1 failed')
01477         #region1 = rg.quarter()
01478         region1 = rg.box(blc=[.25,.25],trc=[.75,.75],frac=true)
01479         pixels = myim.getregion(region=region1)
01480         mask = myim.getregion(getmask=true, region=region1)
01481         if len(pixels)==0 or len(mask)==0:
01482             stop('getregion 1 failed')
01483         ok = myim.done()
01484         if not ok:
01485             stop('done 1 failed')
01486         #
01487         #myim = ia.fromimage(outfile=imname2, infile=imname)
01488         myim = ia.newimagefromimage(outfile=imname2, infile=imname)
01489         if not myim:
01490             stop('ia.fromimage constructor 3 failed')
01491         if not myim.remove(done=T): fail()
01492         #myim = ia.fromimage(infile=imname, region=region1)
01493         myim = ia.newimagefromimage(infile=imname, region=region1)
01494         if not myim:
01495             stop('ia.fromimage constructor 4 failed')
01496         bb = myim.boundingbox()
01497         shape = myim.shape()
01498         shape2 = bb['trc'] - bb['blc'] + 1
01499         if not all(shape,shape2):
01500             stop ('Output image has wrong shape');
01501         pixels2 = myim.getregion()
01502         mask2 = myim.getregion(getmask=true)
01503         if not alleq(pixels,pixels2,tolerance=0.00001):
01504             stop('The data values are wrong in the ia.fromimage')
01505         if not allbooleq(mask,mask2):
01506             stop('The mask values are wrong in the ia.fromimage')
01507         if not myim.done(): fail()
01508         ###
01509         return cleanup(testdir)
01510         
01511     def test6():
01512         info('')
01513         info('')
01514         info('')
01515         info('Test 6 - ia.fromfits constructor')
01516         # Make the directory
01517         testdir = 'imagetest_temp'
01518         if not cleanup(testdir):
01519             note("Cleanup failed", "SEVERE")
01520             return false
01521         try:
01522             os.mkdir(testdir)
01523         except IOError, e:
01524             note(e, "SEVERE")
01525             raise RuntimeError, "mkdir " + testdir + " fails!"
01526         #
01527         info('Testing ia.fromfits constructor')
01528         imname = testdir+'/'+'ia.fromshape.image'
01529         imname2 = testdir+'/'+'image.fits'
01530         imname3 = testdir+'/'+'ia.fromfimage'
01531         #
01532         # ia.fromfits
01533         #
01534         try:
01535             myim = true
01536             note('Expect SEVERE error and Exception here')
01537             myim = ia.newimagefromfits(outfile=imname3, infile='_doggies')
01538         except Exception, e:
01539             note('Caught expected Exception')
01540             myim = false
01541         if myim:
01542             stop('ia.fromfits constructor 1 unexpectedly did not fail')
01543         myim = ia.newimagefromshape(outfile=imname, shape=[10,20])
01544         if not myim:
01545             stop('ia.fromshape constructor 1 failed')
01546         ok = myim.tofits(outfile=imname2)
01547         if not ok:
01548             stop('tofits failed')
01549         ok = myim.done()
01550         if not ok: fail()
01551 
01552         try:
01553             myim = true
01554             note('Expect SEVERE error and Exception here')
01555             myim = ia.newimagefromfits(outfile=imname3, infile=imname2,
01556                                        whichhdu=22)
01557         except Exception, e:
01558             note('Caught expected Exception')
01559             myim = false
01560         if myim:
01561             stop('ia.fromfits constructor 2 unexpectedly did not fail')
01562         myim = ia.newimagefromfits(outfile=imname3, infile=imname2, whichhdu=0)
01563         if not myim:
01564             stop('ia.fromfits constructor 3 failed')
01565         pixels = myim.getregion()
01566         mask = myim.getregion(getmask=true)
01567         if len(pixels)==0 or len(mask)==0: fail()
01568         if not alleqnum(pixels,0.0,tolerance=0.00001):
01569             stop('ia.fromfits constructor 3 pixels are not all zero')
01570         if not alltrue(mask):
01571             stop('ia.fromfits constructor 3 mask is not all T')
01572         if not myim.remove(done=T): fail('*****FAILED TO REMOVE IMAGE*****')
01573         #
01574         myim = ia.newimagefromfits(infile=imname2, whichhdu=0)
01575         if not myim:
01576             stop('ia.fromfits constructor 4 failed')
01577         pixels = myim.getregion()
01578         mask = myim.getregion(getmask=true)
01579         if len(pixels)==0 or len(mask)==0: fail()
01580         if not alleqnum(pixels,0.0,tolerance=0.00001):
01581             stop('ia.fromfits constructor 3 pixels are not all zero')
01582         if not alltrue(mask):
01583             stop('ia.fromfits constructor 3 mask is not all T')
01584         if not myim.done(): fail()
01585 
01586         ###
01587         return cleanup(testdir)
01588         
01589     def test7():
01590         #
01591         # Test  constructors
01592         #
01593         info('')
01594         info('')
01595         info('')
01596         info('Test 7 - imageconcat constructor')
01597 
01598         # Make the directory
01599         testdir = 'imagetest_temp'
01600         if not cleanup(testdir):
01601             note("Cleanup failed", "SEVERE")
01602             return false
01603         try:
01604             os.mkdir(testdir)
01605         except IOError, e:
01606             note(e, "SEVERE")
01607             raise RuntimeError, "mkdir " + testdir + " fails!"
01608 
01609         #
01610         imname = testdir+'/'+'ia.fromshapeconcat.image'
01611         imname2 = testdir+'/'+'imageconcat.image'
01612         #
01613         try:
01614             myim = true
01615             note('Expect SEVERE error and Exception here')
01616             myim = ia.imageconcat(outfile=imname2, infiles='_doggies')
01617         except Exception, e:
01618             note('Caught expected Exception')
01619             myim = false
01620         if myim:
01621             stop('imageconcat constructor 1 unexpectedly did not fail')
01622         myim = ia.newimagefromshape(outfile=imname, shape=[10,20])
01623         if not myim:
01624             stop('ia.fromshape constructor 1 failed')
01625         shape = myim.shape()
01626         myim.done()
01627         #
01628         infiles = [imname,imname,imname]
01629         shapex = [3*shape[0], shape[1]]
01630         shapey = [shape[0], 3*shape[1]]
01631         try:
01632             myim = true
01633             note('Expect SEVERE error and Exception here')
01634             myim = ia.imageconcat(outfile=imname2, infiles=infiles,
01635                                   axis=29, relax=T)
01636         except Exception, e:
01637             note('Caught expected Exception')
01638             myim = false
01639         if myim:
01640             stop('imageconcat constructor 2 unexpectedly did not fail')
01641         try:
01642             myim = true
01643             note('Expect SEVERE error and Exception here')
01644             myim = ia.imageconcat(outfile=imname2, infiles=infiles, axis=1,
01645                                relax=F)
01646         except Exception, e:
01647             note('Caught expected Exception:'+str(e))
01648             myim = false
01649         if myim:
01650             stop('imageconcat constructor 3 unexpectedly did not fail')
01651         myim = ia.imageconcat(outfile=imname2,infiles=infiles,axis=1,relax=T)
01652         if not myim:
01653             stop('imageconcat constructor 4 failed')
01654         shape = myim.shape()
01655         if not all(shape,shapey):
01656             stop('imageconcat image has wrong shape')
01657         ia.close() # needed to we can done myim
01658         ok = myim.remove(done=T)
01659         if not ok: fail()
01660         myim = ia.imageconcat(infiles=infiles, axis=0, relax=T)
01661         if not myim:
01662             stop('imageconcat constructor 5 failed')
01663         shape = myim.shape()
01664         if not all(shape,shapex):
01665             stop('imageconcat image has wrong shape')
01666         if not myim.done(): fail()
01667 
01668          ###
01669         return cleanup(testdir)
01670 
01671         
01672     def test8():
01673         info('');
01674         info('');
01675         info('');
01676         info('Test 8 - imagecalc constructor');
01677 
01678         # Make the directory
01679         testdir = 'imagetest_temp'
01680         if not cleanup(testdir):
01681             note("Cleanup failed", "SEVERE")
01682             return false
01683         try:
01684             os.mkdir(testdir)
01685         except IOError, e:
01686             note(e, "SEVERE")
01687             raise RuntimeError, "mkdir " + testdir + " fails!"
01688 
01689         #
01690         imname = testdir+'/'+'ia.fromarray1.image'
01691         imname2 = testdir+'/'+'ia.fromshape2.image'
01692         imname3 = testdir+'/'+'imagecalc.image'
01693         imshape = [10,20,5]
01694         data = make_data(imshape)
01695         #
01696         try:
01697             myim = true
01698             note('Expect SEVERE error and Exception here')
01699             myim = ia.imagecalc(outfile=imname3, pixels='i_like_doggies')
01700         except Exception, e:
01701             note('Caught expected Exception')
01702             myim = false
01703         if myim:
01704             stop('imagecalc constructor 1 unexpectedly did not fail')
01705         myim = ia.newimagefromarray(outfile=imname, pixels=data)
01706         if not myim:
01707             stop('ia.fromarray constructor 1 failed')
01708         stats = myim.statistics(force=T, list=F)
01709         if not stats: fail()
01710         myim.done()
01711         #
01712         myim = ia.newimagefromshape(outfile=imname2,
01713                                     shape=[2*imshape[0], 2*imshape[1],
01714                                            2*imshape[2]])
01715         if not myim:
01716             stop('imagefromshape constructor 1 failed')
01717         myim.done
01718         #
01719         ex = imname+'+'+imname2
01720         try:
01721             myim = true
01722             note('Expect SEVERE error and Exception here')
01723             myim = ia.imagecalc(outfile=imname3, pixels=ex)
01724         except Exception, e:
01725             note('Caught expected Exception')
01726             myim = false
01727         if myim:
01728             stop('imagecalc constructor 2 unexpectedly did not fail')
01729         #
01730         # Need the double quotes because of / in expression
01731         #
01732         ex = '"'+imname+'"'+'+'+'"'+imname+'"'
01733         myim = ia.imagecalc(outfile=imname3, pixels=ex)
01734         if not myim:
01735             stop('imagecalc constructor 3 failed')
01736         stats2 = myim.statistics(force=T, list=F)
01737         if not stats2: fail()
01738         if (stats2['max'] != 2*(stats['max'])):
01739             stop('imagecalc 3 image has wrong data values')
01740         if (stats2['min'] != 2*(stats['min'])):
01741             stop('imagecalc 3 image has wrong data values')
01742         ia.close()  # needed to remove table lock preventing myim.done
01743         if not myim.remove(done=T): fail()
01744 
01745         ###
01746         return cleanup(testdir)
01747 
01748 
01749         
01750     def test9():
01751         info('')
01752         info('')
01753         info('')
01754         info('Test 9 - readonly imagecalc constructors')
01755 
01756         # Make the directory
01757         testdir = 'imagetest_temp'
01758         if not cleanup(testdir):
01759             note("Cleanup failed", "SEVERE")
01760             return false
01761         try:
01762             os.mkdir(testdir)
01763         except IOError, e:
01764             note(e, "SEVERE")
01765             raise RuntimeError, "mkdir " + testdir + " fails!"
01766         #
01767         imname = testdir+'/'+'ia.fromarray1.image'
01768         imname2 = testdir+'/'+'ia.fromshape2.image'
01769         imshape = [10,20,5]
01770         data = make_data(imshape)
01771         #
01772         try:
01773             myim = true
01774             note('Expect SEVERE error and Exception here')
01775             myim = ia.imagecalc(pixels='i_like_doggies')
01776         except Exception, e:
01777             note('Caught expected Exception')
01778             myim = false
01779         if myim:
01780             stop('expr constructor 1 unexpectedly did not fail')
01781         myim = ia.newimagefromarray(outfile=imname, pixels=data)
01782         if not myim:
01783             stop('ia.fromarray constructor 1 failed')
01784         stats = myim.statistics(force=T, list=F)
01785         if not stats:
01786             stop('statistics 1 failed')
01787         ok = myim.done()
01788         if not ok:
01789             stop('done 1 failed')
01790         myim = ia.newimagefromshape(outfile=imname2,
01791                                     shape=[2*imshape[0],2*imshape[1],
01792                                            2*imshape[2]])
01793         if not myim:
01794             stop('ia.fromshape constructor 1 failed')
01795         ok = myim.done()
01796         if not ok:
01797             stop('done 2 failed')
01798         #
01799         ex = '"'+imname+'"'+'+'+'"'+imname2+'"'
01800         try:
01801             myim = true
01802             note('Expect SEVERE error and Exception here')
01803             myim = ia.imagecalc(pixels=ex)
01804         except Exception, e:
01805             note('Caught expected Exception')
01806             myim = false
01807         if myim:
01808             stop('expr constructor 2 unexpectedly did not fail')
01809         #
01810         ex = '"'+imname+'"'+'+'+'"'+imname+'"'
01811         myim = ia.imagecalc(pixels=ex)
01812         if not myim:
01813             stop('expr constructor 3 failed')
01814         stats2 = myim.statistics(force=T, list=F)
01815         if not stats2:
01816             stop('statistics 2 failed')
01817         if (stats2['max'] != 2*(stats['max'])):
01818             stop('expr image has wrong data values')
01819         if (stats2['min'] != 2*(stats['min'])):
01820             stop('imagecalc image has wrong data values')
01821         ok = myim.done()
01822         if not ok:
01823             stop('done 3 failed')
01824         ###
01825         return cleanup(testdir)
01826 
01827         
01828     def test10():
01829         # Test methods
01830         #   is_image, imagetools, imagedones
01831         #   open, close, done, type, id
01832         info('')
01833         info('')
01834         info('')
01835         #info('Test 10 - is_image, imagetools, imagedones, done, close, open')
01836         #info('Test 10 - isopen, type, id, lock, unlock, haslock')
01837         info('Test 10 - done, close, open')
01838         info('Test 10 - isopen, type, lock, unlock, haslock')
01839 
01840         # Make the directory
01841         testdir = 'imagetest_temp'
01842         if not cleanup(testdir):
01843             note("Cleanup failed", "SEVERE")
01844             return false
01845         try:
01846             os.mkdir(testdir)
01847         except IOError, e:
01848             note(e, "SEVERE")
01849             raise RuntimeError, "mkdir " + testdir + " fails!"
01850 
01851         # Make two images
01852         imname1 = testdir+'/'+'ia.fromshape.image'
01853         shape1 = [10,20]
01854         myim1_test10_ = ia.newimagefromshape(outfile=imname1, shape=shape1)
01855         if not myim1_test10_:
01856             stop('ia.fromshape constructor 1 failed')
01857         imname2 = testdir+'/'+'ia.fromshape.image2'
01858         shape2 = [10,20]
01859         myim2_test10_ = ia.newimagefromshape(outfile=imname2, shape=shape2)
01860         if not myim2_test10_:
01861             stop('ia.fromshape constructor 2 failed')
01862 
01863         #
01864         #info('')
01865         #info('Testing is_image')
01866         #if not is_image(myim1_test10_) or not is_image(myim2_test10_):
01867         #    stop('Global function is_image failed')
01868 
01869         #
01870         #info('')
01871         #info('Testing imagetools')
01872         #itools = ia.imagetools()
01873         #
01874         # There might be other global image tools out there
01875         #
01876         #nimages = len(itools)
01877         #if nimages>1:
01878         #    ok = T
01879         #    found1 = F
01880         #    found2 = F
01881         #    for i in range(nimages):
01882         #        if (itools[i]=='myim1_test10_'):
01883         #            if (found1): ok = F
01884         #            else: found1 = T
01885         #        else:
01886         #            if (itools[i]=='myim2_test10_'):
01887         #                if (found2): ok = F
01888         #                else: found2 = T
01889         #    if (!ok or !found1 or !found2):
01890         #        stop('Global function imagetools failed')
01891         #else:
01892         #    stop('Global function imagetools failed')
01893         #
01894         #
01895         #info('')
01896         #info('Testing done/imagedones')
01897         #ok = imagedones("myim1_test10_ myim2_test10_")
01898         #if not ok:
01899         #    stop('imagedones failed')
01900         #if (myim1_test10_!=F or myim2_test10_!=F):
01901         #    stop('imagedones did not completely destroy image tools')
01902         myim1_test10_.done()
01903         myim2_test10_.done()
01904 
01905         # Test shape/close/open
01906         info('')
01907         info('Testing close')
01908         myim = ia.newimage(imname1)
01909         shape = myim.shape()
01910         if not all(shape,shape1):
01911             stop('image has wrong shape')
01912         ok = myim.close()
01913         if not ok:
01914             stop('Close fails')
01915         if myim.isopen():
01916             stop('isopen 1 fails')
01917         note('Expect SEVERE error here')
01918         ok = myim.shape()
01919         if ok:
01920             stop('Closed image is unexpectedly viable')
01921         else:
01922             note('Expected SEVERE error occurred')
01923 
01924         #
01925         info('')
01926         info('Testing open')
01927         ok = myim.open(imname2)
01928         if not ok:
01929             stop('Open fails')
01930         if not myim.isopen():
01931             stop('isopen 2 fails')
01932         shape = myim.shape()
01933         if not all(shape,shape2):
01934             stop('image has wrong shape')
01935 
01936         #
01937         info('')
01938         info('Testing type')
01939         if (myim.type()!='image'):
01940             stop('image has wrong type')
01941 
01942         #
01943         #info('')
01944         #info('Testing id')
01945         #id = myim.id()
01946         #if not id:
01947         #    stop('id failed')
01948         #ok = is_record(id) and id.has_key('sequence')
01949         #ok = ok and id.has_key('pid')
01950         #ok = ok and id.has_key('time')
01951         #ok = ok and id.has_key('host')
01952         #ok = ok and id.has_key('agentid')
01953         #if not ok:
01954         #    stop('id record has wrong fields')
01955 
01956         #
01957         ok = myim.done()
01958         if not ok:
01959             stop('Done 2 failed')
01960 
01961         #
01962         myim = ia.newimage(imname1)
01963         ok = myim.open(imname2)
01964         if not ok:
01965             stop('Open on already open image failed')
01966 
01967         #
01968         # We cant test locking properly without two processes
01969         # trying to access the same image.  So all we can do is
01970         # see that the functions run and test that haslock
01971         # gives the right answers
01972         #
01973         info('')
01974         info('Testing locking')
01975         ok = myim.lock(T, nattempts=0)
01976         if not ok:
01977             stop('Lock failed (1)')
01978         ok = myim.haslock()
01979         if not ok[0]:
01980             stop('haslock failed (1)')
01981         if (ok[0]!=T or ok[1]!=T):
01982             stop('haslock returns wrong values (1)')
01983         #
01984         ok = myim.unlock()
01985         if not ok:
01986             stop('Unlock failed (1)')
01987         ok = myim.haslock()
01988         if not len(ok):
01989             stop('haslock failed (2)')
01990         if (ok[0]!=F or ok[1]!=F):
01991             stop('haslock returns wrong values (2)')
01992         #
01993         ok = myim.lock(F, nattempts=0)
01994         if not ok:
01995             stop('Lock failed (2)')
01996         ok = myim.haslock()
01997         if not ok[0]:
01998             stop('haslock failed (3)')
01999         if (ok[0]!=T or ok[1]!=F):
02000             stop('haslock returns wrong values (3)')
02001         #
02002         ok = myim.done()
02003         if not ok:
02004             stop('Done 3 failed')
02005         ###
02006         return cleanup(testdir)
02007 
02008 
02009     def test11():
02010         # Test methods
02011         #   coordsys, setcoordsys, shape, name, rename, delete, persistent
02012         info('-------')
02013         info('Test 11 - coordsys, setcoordsys,')
02014         info('          shape, name, rename,  ')
02015         info('          delete, persistent    ')
02016         info('-------')
02017         
02018         # Make the directory
02019         testdir = 'imagetest_temp'
02020         if not cleanup(testdir):
02021             note("Cleanup failed", "SEVERE")
02022             return false
02023         try:
02024             os.mkdir(testdir)
02025         except IOError, e:
02026             note(e, "SEVERE")
02027             raise RuntimeError, "mkdir " + testdir + " fails!"
02028 
02029         # Make two images
02030         imname1 = testdir+'/'+'ia.fromshape.image1'
02031         shape1 = [10,20]
02032         if not ia.fromshape(outfile=imname1, shape=shape1):
02033             stop('ia.fromshape constructor 1 failed')
02034         #
02035         imname2 = testdir+'/'+'ia.fromshape.image2'
02036         shape2 = [5,10]
02037         myim = ia.newimagefromshape(outfile=imname2, shape=shape2)
02038         if not myim:
02039             stop('ia.newimagefromshape constructor 2 failed')
02040         if not myim.done():
02041             stop('Done 2 fails')
02042 
02043         # coordsys
02044         info('Testing coordsys')
02045         myim = ia.newimage(imname1)
02046         try:
02047             mycs = myim.coordsys()
02048         except:
02049             stop('coordsys 1 failed')
02050         #if not is_coordsys(mycs):
02051         #    stop('coordinates are not valid (1)')
02052         ok = coordcheck(myim, [0,1], testdir)
02053         if not ok:
02054             stop('coordinates subset selection 0,1 failed')
02055         ok = coordcheck(myim, [0], testdir)
02056         if not ok:
02057             stop('coordinates subset selection 0 failed')
02058         ok = coordcheck(myim, [1], testdir)
02059         if not ok:
02060             stop('coordinates subset selection 1 failed')
02061         if not mycs.done():
02062             stop('mycs.done fails')
02063 
02064         # setcoordsys
02065         info('')
02066         info('Testing setcoordsys')
02067         try:
02068             mycs = myim.coordsys()
02069         except:
02070             stop('coordsys 2 failed')
02071         #
02072         try:
02073             incr = mycs.increment(format='n')
02074             incr = list(incr['numeric'])
02075             for i in range(len(incr)):
02076                 incr[i] *= 2.0
02077         except:
02078             fail('failed in mycs.increment')
02079         try:
02080             refval = mycs.referencevalue(format='n')
02081             refval = list(refval['numeric'])
02082             for i in range(len(refval)):
02083                 refval[i] += 0.01
02084         except:
02085             fail('failed in mycs.referencevalue')
02086         try:
02087             refpix = list(mycs.referencepixel()['numeric'])
02088             for i in range(len(refpix)):
02089                 refpix[i] += 10.0
02090         except:
02091             fail('failed in mycs.referencepixel')
02092         ok = mycs.setincrement (value=incr)
02093         if not ok:
02094             fail('mycs.setincrement failed')
02095         ok = mycs.setreferencevalue(value=refval)
02096         if not ok:
02097             fail('mycs.setreferencevalue failed')
02098         ok = mycs.setreferencepixel(value=refpix);
02099         if not ok:
02100             fail('mycs.setreferencepixel failed')
02101         #
02102         ok = myim.setcoordsys (mycs.torecord())
02103         if not ok:
02104             stop('setcoordsys 1 failed')
02105         if not mycs.done():
02106             fail('mycs.done failed')
02107         cs2 = myim.coordsys()
02108         incr2 = list(cs2.increment(format='n')['numeric'])
02109         if not all(incr,incr2):
02110             stop('coordsys/setcoordsys  reflection fails increment test')
02111         refval2 = list(cs2.referencevalue(format='n')['numeric'])
02112         if not all(refval, refval2):
02113             stop('coordsys/setcoordsys  reflection fails ref val test')
02114         if not all(refpix,list(cs2.referencepixel()['numeric'])):
02115             stop('coordsys/setcoordsys  reflection fails ref pix test')
02116         if not cs2.done():
02117             fail('failed cs2.done')
02118         #
02119         try:
02120             mycs2 = cs.newcoordsys(direction=F, spectral=F, stokes="", linear=0)
02121         except:
02122             fail('failed creating mycs2')
02123         try:
02124             note("Expect a SEVERE error and exception here.")
02125             ok = myim.setcoordsys(mycs2.torecord())
02126         except Exception, e:
02127             note("Exception: "+ str(e),"SEVERE")
02128             note("Exception occurred as expected.")
02129             ok = false
02130         if ok:
02131             stop('setcoordsys 3 unexpectedly did not fail')
02132         if not mycs2.done():
02133             fail('failed mycs2.done')
02134         badcs = 'doggies'
02135         try:
02136             note("Expect a SEVERE error and exception here.")
02137             ok = myim.setcoordsys(badcs)
02138         except Exception, e:
02139             note("Exception occurred as expected.")
02140         if ok:
02141             stop('setcoordsys 4 unexpectedly did not fail')
02142 
02143         # shape
02144         info('')
02145         info('Testing shape')
02146         if not all(myim.shape(),shape1):
02147             stop('Shape fails')
02148 
02149         # Name
02150         info('')
02151         info('Testing name')
02152         absoluteName = os.path.abspath(imname1)
02153         if not absoluteName:
02154             fail('failed to get absoluteName')
02155         if (myim.name(strippath=F) != absoluteName):
02156             stop('The absolute name is wrong')
02157         baseName = 'ia.fromshape.image1'
02158         if (myim.name(strippath=T) != baseName):
02159             stop('The base name is wrong')
02160 
02161         # Rename
02162         info('')
02163         info('Testing rename')
02164         imname4 = testdir + '/' + 'ia.fromshape.image4'
02165         ok = myim.rename(imname4, overwrite=F)
02166         if not ok:
02167             stop('Rename 1 fails')
02168         absoluteName = os.path.abspath(imname4)
02169         if not absoluteName:
02170             fail('failed to get absoluteName for rename')
02171         if (myim.name(strippath=F) != absoluteName):
02172             stop('The name has not been renamed correctly')
02173         #
02174         ok = myim.rename(imname2, overwrite=F)
02175         if ok:
02176             stop('Rename unexpectedly did not fail')
02177         ok = myim.rename(imname2, overwrite=T)
02178         if not ok:
02179             stop('Rename 2 fails')
02180 
02181         # Remove/Delete
02182         info('')
02183         info('Testing remove')
02184         ok = myim.remove(done=T)
02185         if not ok:
02186             stop('Done 3 fails')
02187         if (myim!=F):
02188             note('Done did not completely destroy image tool')
02189         #
02190         #myim = ia.fromshape(imname1, shape1)
02191         ok = ia.fromshape(imname1, shape1)
02192         if not ok:
02193             stop('failed to create image from shape in remove')
02194         ia.close()  # remove lock on imname1
02195         myim = ia.newimage(imname1)
02196         if not myim:
02197             stop('ia.fromshape constructor 3 fails')
02198         ok = myim.remove(done=F)
02199         if not ok:
02200             stop('Remove fails')
02201         #if (is_boolean(myim) && myim==F) {
02202         if not myim:
02203             stop('Remove erroneously destroyed the image tool')
02204         ok = myim.done()
02205         if not ok:
02206             stop('Done 4 fails')
02207 
02208         # persistent
02209         info('')
02210         info('Testing ispersistent')
02211         imname4 = testdir + '/' + 'ia.fromshape.image4'
02212         shape4 = [10,10]
02213         #myim4 = ia.fromshape(outfile=imname4, shape=shape4)
02214         ok = ia.fromshape(outfile=imname4, shape=shape4)
02215         if not ok:
02216             stop('failed to create image from shape4 in persistent')
02217         ia.close()  # unlock imname4
02218         myim4 = ia.newimage(imname4)
02219         if not myim4:
02220             stop('ia.fromshape constructor 4 failed')
02221         #
02222         if not myim4.ispersistent():
02223             stop('Persistent test 1 fails')
02224         ok = myim4.done()
02225         if not ok:
02226             stop('Done 5 fails')
02227         ex = '"' + imname4 + '"' + '+' + '"' + imname4 + '"'
02228         myim4 = ia.imagecalc(pixels=ex)
02229         if not myim4:
02230             stop('imagecalc constructor fails')
02231         if myim4.ispersistent():
02232             stop('Persistent test 2 fails')
02233         ok = myim4.done()
02234         if not ok:
02235             stop('Done 6 fails')
02236 
02237         #
02238         return cleanup(testdir)
02239 
02240     def test12():
02241         # Test methods
02242         #   getchunk, putchunk
02243         #   pixelvalue
02244         info('')
02245         info('')
02246         info('')
02247         info('Test 12 - getchunk, putchunk, pixelvalue')
02248         # Make the directory
02249         testdir = 'imagetest_temp'
02250         if not cleanup(testdir):
02251             note("Cleanup failed", "SEVERE")
02252             return false
02253         try:
02254             os.mkdir(testdir)
02255         except IOError, e:
02256             note(e, "SEVERE")
02257             raise RuntimeError, "mkdir " + testdir + " fails!"
02258         #
02259         # Make images of all the wondrous flavours that we have
02260         #
02261         root = testdir + '/' + 'testimage'
02262         imshape = [12,24,20]
02263         data = make_data(imshape)
02264         images = makeAllImageTypes(imshape, root, data, F)
02265         if not images:
02266             fail('failed to make all image types')
02267         #
02268         # Loop over all image types
02269         #
02270         types = images.keys()
02271         for mytype in types:
02272             info('')
02273             info('Testing Image type ' + images[mytype]["type"])
02274             myim = images[mytype]["tool"]
02275             #
02276             # Get some chunks !
02277             #
02278             info('')
02279             info('Testing getchunk')
02280             pixels = myim.getchunk(list=T)
02281             if len(pixels)==0:
02282                 stop('getchunk 1 failed')
02283             if list(pixels.shape) != imshape:
02284                 stop('getchunk 1 recovers wrong array shape')
02285             #if (!all((pixels-data < 0.0001)))
02286             if not alleq(pixels, data, tolerance=0.0001):
02287                 stop('getchunk 1 recovers wrong pixel values')
02288             #
02289             inc = [1,2,5]
02290             pixels = myim.getchunk(inc=inc)
02291             if len(pixels)==0:
02292                 stop('getchunk 2 failed')
02293             timshape=[]
02294             timshape.append(imshape[0]/1)
02295             timshape.append(imshape[1]/2)
02296             timshape.append(imshape[2]/5)
02297             if list(pixels.shape) != timshape:
02298                 stop('getchunk 2 recovers wrong array shape')
02299             data2 = pick(imshape, data, inc)
02300             if not alleq(pixels,data2,tolerance= 0.0001):
02301                 return stop('getchunk 2 recovers wrong pixel values')
02302             #
02303             blc = [2,3,4]
02304             trc = [5,6,7]
02305             shape2 = [trc[0]-blc[0]+1, trc[1]-blc[1]+1, trc[2]-blc[2]+1]
02306             pixels = myim.getchunk(blc=blc, trc=trc, inc=[1,1,1])
02307             if len(pixels)==0:
02308                 stop('getchunk 3 failed')
02309             if list(pixels.shape) != shape2:
02310                 stop('getchunk 3 recovers wrong array shape')
02311             data2 = data[blc[0]:(trc[0]+1), blc[1]:(trc[1]+1), blc[2]:(trc[2]+1)]
02312             if not alleq(pixels,data2,tolerance=0.0001):
02313                 stop('getchunk 3 recovers wrong pixel values')
02314             #
02315             blc = [-10,-10,-10];
02316             pixels = myim.getchunk(blc=blc)
02317             if len(pixels)==0:
02318                 stop('getchunk 4 failed')
02319             if list(pixels.shape) != imshape:
02320                 stop('getchunk 4 recovers wrong array shape')
02321             #
02322             trc = [10000,10000,10000]
02323             pixels = myim.getchunk(trc=trc)
02324             if len(pixels)==0:
02325                 stop('getchunk 5 failed')
02326             if list(pixels.shape) != imshape:
02327                 stop('getchunk 5 recovers wrong array shape')
02328             #
02329             blc = [5,6,7]
02330             trc = [1,2,3]
02331             pixels = myim.getchunk(blc=blc,trc=trc)
02332             if len(pixels)==0:
02333                 stop('getchunk 6 failed')
02334             if list(pixels.shape) != imshape:
02335                 stop('getchunk 6 recovers wrong array shape')
02336             #
02337             inc = [100,100,100]
02338             pixels = myim.getchunk(inc=100)
02339             if len(pixels)==0:
02340                 stop('getchunk 7 failed')
02341             if list(pixels.shape) != imshape:
02342                 stop('getchunk 7 recovers wrong array shape')
02343             #
02344             pixels = myim.getchunk (axes=[0,1], dropdeg=T)
02345             if len(pixels) != imshape[2]:
02346                 stop('getchunk 8 recovers wrong array shape')
02347             #
02348             pixels = myim.getchunk (axes=[1,2], dropdeg=T)
02349             if len(pixels) != imshape[0]:
02350                 stop('getchunk 9 recovers wrong array shape')
02351             #
02352             pixels = myim.getchunk (axes=[0], dropdeg=T)
02353             if not all(list(pixels.shape),imshape[1:3]):
02354                 stop('getchunk 10 recovers wrong array shape')
02355             #
02356             # Now some putchunking
02357             #
02358             info('')
02359             info('Testing putchunk')
02360             pixels = myim.getchunk()
02361             if len(pixels)==0:
02362                 stop('getchunk 8 failed')
02363             data2=ia.makearray(100,[data.shape[0],data.shape[1],data.shape[2]])
02364             for i in range(data.shape[0]):
02365                 for j in range(data.shape[1]):
02366                     for k in range(data.shape[2]):
02367                         if data[i][j][k]<-10000:
02368                             data2[i][j][k] = data[i][j][k]
02369             ok = myim.putchunk(pixels=data2, list=T)
02370             if not ok:
02371                 stop('putchunk 1 failed')
02372             pixels = myim.getchunk()
02373             if len(pixels)==0:
02374                 stop('getchunk 9 failed')
02375             if not alleq(pixels,data2, tolerance=0.0001):
02376                 stop('getchunk 10 recovers wrong pixel values=')
02377             #
02378             inc = [2,1,5]
02379             data2 = ia.makearray(0,[imshape[0]/inc[0], imshape[1]/inc[1], imshape[2]/inc[2]])
02380             ok = myim.putchunk(pixels=data2, inc=inc)
02381             if not ok:
02382                 stop('putchunk 2 failed')
02383             pixels = myim.getchunk(inc=inc)
02384             if len(pixels)==0:
02385                 stop('getchunk 9 failed')
02386             if not alleq(pixels,data2, tolerance=0.0001):
02387                 stop('getchunk 10 recovers wrong pixel values=')
02388             pixels2 = myim.getchunk()
02389             if len(pixels2)==0:
02390                 stop('getchunk 11 failed')
02391             data2 = pick(imshape, pixels2, inc)
02392             if not alleq(data2,pixels, tolerance=0.0001):
02393                 stop('getchunk 11 recovers wrong pixel values=')
02394             pixels = F; pixels2 = F; data2 = F
02395             #
02396             pixels = myim.getchunk()
02397             if len(pixels)==0:
02398                 stop('getchunk 12 failed')
02399             try:
02400                 note('Expect SEVERE error and Exception here')
02401                 ok = myim.putchunk(pixels=pixels, blc=[3,4,5])
02402             except Exception, e:
02403                 note('Expected exception occurred.')
02404                 ok = False
02405             if ok:
02406                 stop('putchunk 3 unexpectedly did not fail')
02407             try:
02408                 note('Expect SEVERE error and Exception here')
02409                 ok = myim.putchunk(pixels=pixels, inc=[3,4,5])
02410             except Exception, e:
02411                 note('Expected exception occurred.')
02412                 ok = False
02413             if ok:
02414                 stop('putchunk 4 unexpectedly did not fail')
02415             #
02416             pixels_shape=pixels.shape
02417             for i in range(pixels_shape[0]):
02418                 for j in range(pixels_shape[1]):
02419                     for k in range(pixels_shape[2]):
02420                         if pixels[i][j][k] >= -10000:
02421                             pixels[i]=100
02422             ok = myim.putchunk(pixels=pixels)
02423             if not ok:
02424                 stop('putchunk 5 failed')
02425             pixels = ia.makearray(0,[imshape[0], imshape[1]])
02426             ok = myim.putchunk(pixels=pixels)
02427             if not ok:
02428                 stop('putchunk 6 failed')
02429             pixels2 = myim.getchunk()
02430             pixels2shape=pixels2.shape
02431             for i in range(pixels2shape[0]):
02432                 for j in range(pixels2shape[1]):
02433                     if not pixels2[i,j,0]==0:
02434                         stop('getchunk 13 recovered wrong pixel values')
02435                     if not pixels2[i,j,1]==100:
02436                         stop('getchunk 14 recovered wrong pixel values')
02437             #
02438             # Test replication in putchunk
02439             #
02440             ok = myim.set(pixels=0.0)
02441             if not ok:
02442                 stop('set 1 fails')
02443             #
02444             p = ia.makearray(10.0, [imshape[0],imshape[1]]); # Adds degenerate axis
02445             ok = myim.putchunk(p, replicate=T)
02446             if not ok:
02447                 stop('putchunk 8 fails')
02448             p2 = myim.getchunk()
02449             if len(p2)==0:
02450                 stop('getchunk 16 fails')
02451             p2shape=p2.shape
02452             for i in range(p2shape[0]):
02453                 for j in range(p2shape[1]):
02454                     for k in range(p2shape[2]):
02455                         if not (p2[i,j,k]==10.0):
02456                             stop('putchunk 8 put wrong values')
02457             #
02458             p = ia.makearray(10.0, [imshape[0],imshape[1], 1])
02459             ok = myim.putchunk(p, replicate=T)
02460             if not ok:
02461                 stop('putchunk 9 fails')
02462             p2 = myim.getchunk()
02463             if len(p2)==0:
02464                 stop('getchunk 17 fails')
02465             p2shape=p2.shape
02466             for i in range(p2shape[0]):
02467                 for j in range(p2shape[1]):
02468                     for k in range(p2shape[2]):
02469                         if not (p2[i,j,k]==10):
02470                             stop('putchunk 9 put wrong values')
02471             #
02472             # Now pixelvalue
02473             #
02474             info('')
02475             info('Testing pixelvalue')
02476             #pixels2[:,:,:] = 0.0
02477             pixels2shape=pixels2.shape
02478             for i in range(pixels2shape[0]):
02479                 for j in range(pixels2shape[1]):
02480                     for k in range(pixels2shape[2]):
02481                         pixels2[i,j,k] = 0.0
02482             pixels2[0,0,0] = 1.0
02483             ok = myim.putchunk(pixels=pixels2)
02484             if not ok:
02485                 stop('putchunk 7 failed')
02486             ok = myim.setbrightnessunit('Jy/beam')
02487             if not ok:
02488                 stop('setbrightnessunit 1 failed')
02489             #
02490             r = myim.pixelvalue([0,0,0])
02491             ok = (r['value']['value']==1.0) and (r['value']['unit']=='Jy/beam')
02492             ok = ok and (r['mask']==T)
02493             ok = ok and (r['pixel'][0]==0)
02494             ok = ok and (r['pixel'][1]==0)
02495             ok = ok and (r['pixel'][2]==0)
02496             if not ok:
02497                 stop('pixelvalue 1 recovered wrong values')
02498             #
02499             r = myim.pixelvalue([-1,-1,-1])
02500             if r != {}:
02501                 stop('pixelvalue 2 recovered wrong values')
02502             r = myim.pixelvalue(myim.shape())
02503             if r != {}:
02504                 stop('pixelvalue 3 recovered wrong values')
02505             #
02506             r = myim.pixelvalue([2,2,2,100])
02507             ok = (r['value']['value']==0.0) and (r['value']['unit']=='Jy/beam')
02508             ok = ok and (r['mask']==T)
02509             ok = ok and (r['pixel'][0]==2)
02510             ok = ok and (r['pixel'][1]==2)
02511             ok = ok and (r['pixel'][2]==2)
02512             if not ok:
02513                 stop('pixelvalue 4 recovered wrong values')
02514             #
02515             ok = myim.done();
02516             if not ok:
02517                 stop('Done 1 fails')
02518         return cleanup(testdir)
02519     
02520     def test13():
02521         # Test methods
02522         #   getregion, putregion, set, replacemaskedpixels
02523         info('')
02524         info('')
02525         info('')
02526         info('Test 13 - getregion, putregion, set, replacemaskedpixels')
02527 
02528         # Make the directory
02529         testdir = 'imagetest_temp'
02530         if not cleanup(testdir):
02531             note("Cleanup failed", "SEVERE")
02532             return false
02533         try:
02534             os.mkdir(testdir)
02535         except IOError, e:
02536             note(e, "SEVERE")
02537             raise RuntimeError, "mkdir " + testdir + " fails!"
02538 
02539         # Make images of all the wondrous flavours that we have
02540         root = testdir + '/' + 'testimage'
02541         imshape = [10,20,30]
02542         images = makeAllImageTypes(imshape, root, includereadonly=T)
02543         if not images:
02544             fail('failed to make all image types')
02545 
02546         # Loop over all image types
02547         types = images.keys()
02548         for mytype in types:
02549             info('')
02550             info('Testing Image type ' + images[mytype]["type"])
02551             myim = images[mytype]["tool"]
02552             # Reassign as one of the image types is ImageConcat
02553             imshape = myim.shape();
02554             #
02555             # Get some regions !
02556             #
02557             info('')
02558             info('Testing getregion')
02559             #local pixels, mask
02560             r1 = rg.box()
02561             pixels = myim.getregion(region=r1, list=T)
02562             mask = myim.getregion(region=r1, list=T, getmask=True)
02563             if len(pixels)==0 or len(mask)==0:
02564                 stop('getregion 1 failed')
02565             bb = myim.boundingbox(r1)
02566             pixels_shape=list(pixels.shape)
02567             mask_shape=list(mask.shape)
02568             if not all(pixels_shape, mask_shape):
02569                 stop('getregion 1 pixels and mask have different shapes')
02570             if not all(pixels_shape, bb['regionShape']):
02571                 stop('getregion 1 recovers wrong array shape')
02572             for i in range(pixels_shape[0]):
02573                 for j in range(pixels_shape[1]):
02574                     for k in range(pixels_shape[2]):
02575                         if not (pixels[i][j][k] < 0.0001):
02576                             stop('getregion 1 recovers wrong pixel values=')
02577                         if not (mask[i][j][k] == T):
02578                             stop('getregion 1 recovers wrong mask values=')
02579             #
02580             csys = myim.coordsys()
02581             ok = rg.setcoordinates(csys.torecord())
02582             if not ok:
02583                 stop('Failed to set coordinate system in regionmanager 1')
02584             if not csys.done():
02585                 fail('Failed in csys.done()')
02586             #blc = qa.quantity([2,4,6], 'pix')
02587             blc = ['2pix','4pix','6pix']
02588             if not blc:
02589                 fail('Failed to create blc')
02590             #trc = qa.quantity([8,10,12], 'pix')
02591             trc = ['8pix','10pix','12pix']
02592             if not trc:
02593                 fail('Failed to create trc')
02594             r1 = rg.wbox(blc=blc, trc=trc)
02595             if not r1:
02596                 stop('Failed to make region r1')
02597             r2 = rg.wpolygon(x=['5pix','6pix','7pix','8pix'],
02598                              y=['5pix','5pix','10pix','7.5pix'],
02599                              pixelaxes=[0,1])
02600             if not r2:
02601                 stop('Failed to make region r2')
02602             d={"reg1":r1, "reg2":r2}
02603             r3 = rg.makeunion(d)
02604             if not r3:
02605                 stop('Failed to make region r3')
02606             pixels = myim.getregion(r3)
02607             mask = myim.getregion(r3, getmask=true)
02608             if len(pixels)==0 or len(mask)==0:
02609                 stop('getregion 2 failed')
02610             bb = myim.boundingbox(r3)
02611             pixels_shape = pixels.shape
02612             for i in range(len(pixels_shape)):
02613                 if pixels_shape[i] != bb['regionShape'][i]:
02614                     stop('getregion 2 recovers wrong array shape')
02615             for i in range(pixels_shape[0]):
02616                 for j in range(pixels_shape[1]):
02617                     for k in range(pixels_shape[2]):
02618                         if not (pixels[i][j][k] < 0.0001):
02619                             stop('getregion 2 recovers wrong pixel values=')
02620             #
02621             pixels = myim.getregion (axes=[0,1], dropdeg=T)
02622             mask = myim.getregion (axes=[0,1], dropdeg=T, getmask=true)
02623             if len(pixels)==0:
02624                 fail('getregion 3 failed to retrieval pixels')
02625             if ((pixels.shape)[0]!=imshape[2]) or ((mask.shape)[0]!=imshape[2]):
02626                 stop('getregion 3 recovers wrong array shape')
02627             #
02628             pixels = myim.getregion (axes=[1,2], dropdeg=T)
02629             mask = myim.getregion (axes=[1,2], dropdeg=T, getmask=true)
02630             if (len(pixels)==0) or (len(mask)==0):
02631                 fail('getgregion could not retrieve pixels/mask')
02632             if (pixels.shape[0] != imshape[0]) or (mask.shape[0] != imshape[0]):
02633                 stop('getregion 4 recovers wrong array shape')
02634             #
02635             pixels = myim.getregion (axes=[0], dropdeg=T)
02636             mask = myim.getregion (axes=[0], dropdeg=T, getmask=true)
02637             if (len(pixels)==0) or (len(mask)==0):
02638                 if (not all(list(shape(pixels)),imshape[1:3])) or (not all(list(shape(mask)),imshape[1:3])):
02639                     stop('getregion 5 recovers wrong array shape')
02640             #
02641             pixels = myim.getregion()
02642             if len(pixels)==0:
02643                 fail('failed to retrieve pixels with getregion')
02644             #
02645             mask = myim.getregion (getmask=true)
02646             if len(mask)==0:
02647                 fail('failed to retrieve pixelmask with getregion')
02648             #
02649             if not myim.done():
02650                 fail('failed in myim.done()')
02651             #
02652         ok = cleanup(testdir)
02653         if not ok:
02654             fail('failed to cleanup')
02655 
02656         #
02657         # Putregions
02658         #
02659         try:
02660             os.mkdir(testdir)
02661         except IOError, e:
02662             note(e, "SEVERE")
02663             raise RuntimeError, "mkdir " + testdir + " fails!"
02664         imshape = [10,20,30]
02665         images = makeAllImageTypes(imshape, root, includereadonly=F)
02666         if not images:
02667             fail('failed to make all image types')
02668 
02669         # Loop over all image types
02670         types = images.keys()
02671         for thetype in types:
02672             info('')
02673             info('Testing Image type ' + images[thetype]["type"])
02674             myim = images[thetype]["tool"]
02675             imshape = myim.shape(); # Reassign as one of the image types is ImageConcat
02676             #
02677             info('');
02678             info('Testing putregion')
02679             pixels = myim.getregion(r3)
02680             mask = myim.getregion(r3, getmask=true)
02681             if (len(pixels)==0 or len(mask)==0):
02682                 fail('geregion failed to get r3')
02683             ok = myim.putregion(pixelmask=mask, region=r3)
02684             if not ok:
02685                 stop('putregion 1 failed')
02686             pixels2 = myim.getregion(r3)
02687             mask2 = myim.getregion(r3, getmask=true)
02688             if (len(pixels)==0 or len(mask)==0):
02689                 stop('getregion 6 failed')
02690             if not allbooleq(mask2,mask):
02691                 stop('getregion 6 recovered wrong mask')
02692             #
02693             r1 = rg.box(trc=[1000])
02694             pixels = myim.getregion(r1)
02695             mask = myim.getregion(r1)
02696             if (len(pixels)==0 or len(mask)==0):
02697                 stop('getregion 7 failed')
02698             #
02699             r1 = rg.box(trc=[1000])
02700             ok = myim.putregion(pixels, mask, r1)
02701             if not ok:
02702                 stop('putregion 2 failed')
02703             #
02704             try:
02705                 note('Expect SEVERE error and Exception here')
02706                 ok = myim.putregion()
02707             except Exception, e:
02708                 note('Expected exception occurred.')
02709                 ok = False
02710             if ok:
02711                 stop('putregion 3 unexpectedly did not fail')
02712             pixels = ia.makearray(0,[2,3,4,5])
02713             try:
02714                 note('Expect SEVERE error and Exception here')
02715                 ok = myim.putregion(pixels=pixels)
02716             except Exception, e:
02717                 note('Expected exception occurred')
02718                 ok = False
02719             if ok:
02720                 stop('putregion 4 unexpectedly did not fail')
02721             mask = ia.makearray(F,[2,3,4,5])
02722             try:
02723                 note('Expect SEVERE error and Exception here')
02724                 ok = myim.putregion(pixelmask=mask)
02725             except Exception, e:
02726                 note('Expected exception occurred')
02727                 ok = False
02728             if ok:
02729                 stop('putregion 5 unexpectedly did not fail')
02730             pixels = ia.makearray(0,[100,100,100])
02731             try:
02732                 note('Expect SEVERE error and Exception here')
02733                 ok = myim.putregion(pixels=pixels)
02734             except Exception, e:
02735                 note('Expected exception occurred')
02736                 ok = False
02737             if ok:
02738                 stop('putregion 6 unexpectedly did not fail')
02739             #
02740             pixels = myim.getregion()
02741             mask = myim.getregion(getmask=true)
02742             if (len(pixels)==0 or len(mask)==0):
02743                 stop('getregion 8 failed')
02744             sh = myim.shape()
02745             pixels[0:sh[0], 0:sh[1], 0:sh[2]] = 1.0
02746             mask[0:sh[0], 0:sh[1], 0:sh[2]] = T
02747             mask[0,0,0] = F
02748             ok = myim.putregion(pixels=pixels, pixelmask=mask, usemask=F)
02749             if not ok:
02750                 stop('putregion 7 failed')
02751             mask = myim.getregion(getmask=true)
02752             pixels = myim.getregion()
02753             if (len(pixels)==0 or len(mask)==0):
02754                 stop('getregion 9 failed')
02755             for i in range(sh[0]):
02756                 for j in range(sh[1]):
02757                     for k in range(sh[2]):
02758                         if not (pixels[i][j][k] - 1.0 < 0.0001):
02759                             stop('getregion 9 recovers wrong pixel values')
02760             if (mask[0,0,0]==T):
02761                 stop('getregion 9 recovers wrong mask values (1)')
02762             tmp = mask[1:sh[0], 1:sh[1], 1:sh[2]]
02763             for i in range(sh[0]-1):
02764                 for j in range(sh[1]-1):
02765                     for k in range(sh[2]-1):
02766                         if not (tmp[i][j][k] == T):
02767                             stop('getregion 9 recovers wrong mask values (2)')
02768             #
02769             pixels[0:sh[0], 0:sh[1], 0:sh[2]] = 10.0
02770             ok = myim.putregion(pixels=pixels, usemask=T)
02771             if not ok:
02772                 stop('putregion 8 failed')
02773             pixels = myim.getregion()
02774             mask = myim.getregion(getmask=true)
02775             if len(pixels)==0 or len(mask)==0:
02776                 stop('getregion 10 failed')
02777             if ((pixels[0,0,0]-1.0)>0.0001):
02778                 stop('getregion 10 recovers wrong pixel values (1)')
02779             tmp = pixels[1:sh[0], 1:sh[1], 1:sh[2]] - 1.0
02780             for i in range(sh[0]-1):
02781                 for j in range(sh[1]-1):
02782                     for k in range(sh[2]-1):
02783                         if not (tmp[i][j][k] > 0.0001):
02784                             stop('getregion 10 recovers wrong pixel values (2)')
02785             #
02786             pixels[0:sh[0], 0:sh[1], 0:sh[2]] = 10.0
02787             mask[0:sh[0], 0:sh[1], 0:sh[2]] = T
02788             ok = myim.putregion(pixels=pixels, pixelmask=mask, usemask=F)
02789             if not ok:
02790                 stop('putregion 9 failed')
02791             pixels = ia.makearray(0.0, [sh[0], sh[1]])
02792             # Pad with degenerate axes
02793             print sh
02794             print "shape", sh[0], sh[1]
02795             print type(sh[0])
02796             print type(sh[1])
02797             print "pixels", pixels
02798             ok = myim.putregion(pixels=pixels, usemask=F)
02799             if not ok:
02800                 stop('putregion 10 failed')
02801             pixels = myim.getregion()
02802             mask = myim.getregion(getmask=true)
02803             if len(pixels)==0 or len(mask)==0:
02804                 stop('getregion 11 failed')
02805             tmp = pixels[0:sh[0], 0:sh[1], 0]
02806             for i in range(sh[0]):
02807                 for j in range(sh[1]):
02808                     if not (tmp[i][j] < 0.0001):
02809                         stop('getregion 11 recovers wrong pixel values (1)')
02810             tmp = pixels[0:sh[0], 0:sh[1], 0:sh[2]] - 10.0
02811             for i in range(sh[0]):
02812                 for j in range(sh[1]):
02813                     for k in range(sh[2]):
02814                         if not (tmp[i][j][k] < 0.0001):
02815                             stop('getregion 11 recovers wrong pixel values (2)')
02816             #
02817             pixels = ia.makearray(0.0, [sh[0], sh[1], sh[2]])
02818             mask = ia.makearray(T, [sh[0], sh[1], sh[2]])
02819             mask[0,0,0] = F
02820             ok = myim.putregion(pixels=pixels, pixelmask=mask, usemask=F)
02821             if not ok:
02822                 stop('putregion 11 failed')
02823             pixels = ia.makearray(0.0, [sh[0], sh[1]])
02824             # Pad with degenerate axes
02825             ok = myim.putregion(pixels=pixels, usemask=T);
02826             if not ok:
02827                 stop('putregion 12 failed')
02828             pixels = myim.getregion()
02829             mask = myim.getregion(getmask=true)
02830             if not ok:
02831                 stop('getregion 12 failed')
02832             if ((pixels[0,0,0]-10.0)>0.0001):
02833                 stop('getregion 12 recovers wrong pixel values (1)')
02834             tmp = pixels[1:sh[0], 1:sh[1], 0]
02835             for i in range(sh[0]-1):
02836                 for j in range(sh[1]-1):
02837                     if not (tmp[i][j] < 0.0001):
02838                         stop('getregion 12 recovers wrong pixel values (1)')
02839             tmp = pixels[0:sh[0], 0:sh[1], 1:sh[2]] - 10.0
02840             for i in range(sh[0]):
02841                 for j in range(sh[1]):
02842                     for k in range(sh[2]-1):
02843                         if not (tmp[i][j][k] < 0.0001):
02844                             stop('getregion 12 recovers wrong pixel values (2)')
02845             #
02846             # Test replication
02847             #
02848             ok = myim.set(pixels=0.0, pixelmask=F)
02849             if not ok:
02850                 stop('set 1 fails')
02851             #
02852             # Adds degenerate axis
02853             p = ia.makearray(10.0, [imshape[0], imshape[1]]);
02854             # Adds degenerate axis
02855             m = ia.makearray(T, [imshape[0], imshape[1]]);
02856             ok = myim.putregion(pixels=p, pixelmask=m, usemask=F, replicate=T)
02857             if not ok:
02858                 stop('putregion 13 fails')
02859             p2 = myim.getregion()
02860             m2 = myim.getregion(getmask=true)
02861             if len(p2)==0 or len(m2)==0:
02862                 stop('getregion 13 fails')
02863             sh = p2.shape
02864             for i in range(sh[0]):
02865                 for j in range(sh[1]):
02866                     for k in range(sh[2]):
02867                         if not p2[i][j][k]==10.0:
02868                             stop('putregion 13 put wrong values')
02869             #
02870             ok = myim.set(pixels=0.0, pixelmask=F)
02871             if not ok:
02872                 stop('set 1 fails')
02873             #
02874             p = ia.makearray(10.0, [imshape[0], imshape[1], 1])
02875             m = ia.makearray(T, [imshape[0], imshape[1], 1]);
02876             ok = myim.putregion(pixels=p, pixelmask=m, usemask=F, replicate=T)
02877             if not ok:
02878                 stop('putregion 14 fails')
02879             p2 = myim.getregion()
02880             m2 = myim.getregion(getmask=true)
02881             if len(p2)==0 or len(m2)==0:
02882                 stop('getregion 14 fails')
02883             sh = p2.shape
02884             for i in range(sh[0]):
02885                 for j in range(sh[1]):
02886                     for k in range(sh[2]):
02887                         if not p2[i][j][k]==10.0:
02888                             stop('putregion 14 put wrong values')
02889             #
02890             # set
02891             #
02892             info('');
02893             info('Testing set')
02894             #
02895             try:
02896                 note('Expect SEVERE error and Exception here')
02897                 ok = myim.set(pixels='doggies')
02898             except Exception, e:
02899                 note('Expected exception occurred')
02900                 ok = False
02901             if ok:
02902                 stop('set 1 unexpectedly did not fail')
02903             try:
02904                 note('Expect SEVERE error and Exception here')
02905                 ok = myim.set(pixelmask='doggies')
02906             except Exception, e:
02907                 note('Expected exception occurred: '+str(e))
02908                 ok = False
02909             if ok:
02910                 stop('set 2 unexpectedly did not fail')
02911             note('Expect Warning message here')
02912             ok = myim.set()
02913             if ok:
02914                 stop('set 3 unexpectedly did not fail')
02915             try :
02916                note('Expect Warning message here')
02917                ok = myim.set(region='doggies')
02918             except Exception, e:
02919                ok = False
02920             if ok:
02921                 stop('set 4 unexpectedly did not fail')
02922             try:
02923                 note('Expect SEVERE error and Exception here')
02924                 ok = myim.set(pixels='imname')
02925             except Exception, e:
02926                 note('Expected exception occurred')
02927                 ok = False
02928             if ok:
02929                 stop('set 5 unexpectedly did not fail')
02930             #
02931             ok = myim.set(pixels=1.0)
02932             if not ok:
02933                 stop('set 6 failed')
02934             pixels = myim.getregion()
02935             mask = myim.getregion(getmask=true)
02936             if len(pixels)==0 or len(mask)==0:
02937                 stop('getregion 6 failed')
02938             sh = pixels.shape
02939             for i in range(sh[0]):
02940                 for j in range(sh[1]):
02941                     for k in range(sh[2]):
02942                         if not ((pixels[i][j][k] -1) < 0.0001):
02943                             stop('getregion 6 recovers wrong pixel values')
02944             #
02945             ok = myim.set(pixels='1.0')
02946             if not ok:
02947                 stop('set 7 failed')
02948             pixels = myim.getregion()
02949             mask = myim.getregion(getmask=true)
02950             if len(pixels)==0 or len(mask)==0:
02951                 stop('getregion 7 failed')
02952             sh = pixels.shape
02953             for i in range(sh[0]):
02954                 for j in range(sh[1]):
02955                     for k in range(sh[2]):
02956                         if not ((pixels[i][j][k] -1) < 0.0001):
02957                             stop('getregion 7 recovers wrong pixel values')
02958             #
02959             pixels[0,0,0] = -100
02960             ok = myim.putregion(pixels=pixels)
02961             if not ok:
02962                 stop('putregion 7 failed')
02963             imname = testdir + '/subimage.test'
02964             myim2 = myim.subimage(imname)
02965             if not myim2:
02966                 fail('failed to get subimage myim2')
02967             expr = 'min("' + imname + '")'
02968             ok = myim.set(pixels=expr)
02969             if not ok:
02970                 stop('set 8 failed')
02971             pixels = myim.getregion()
02972             mask = myim.getregion(getmask = true)
02973             if len(pixels)==0 or len(mask)==0:
02974                 stop('getregion 8 failed')
02975             sh = pixels.shape
02976             for i in range(sh[0]):
02977                 for j in range(sh[1]):
02978                     for k in range(sh[2]):
02979                         if not ((pixels[i][j][k] + 100) < 0.0001):
02980                             stop('getregion 8 recovers wrong pixel values')
02981             if not myim2.remove(T):
02982                 fail('failed to remove myim2')
02983             #
02984             ok = myim.set(pixelmask=F)
02985             if not ok:
02986                 stop('set 9 failed')
02987             pixels = myim.getregion()
02988             mask = myim.getregion(getmask=true)
02989             if len(pixels)==0 or len(mask)==0:
02990                 stop('getregion 9 failed')
02991             if mask.any():  #mask==F
02992                 stop('getregion 9 recovers wrong mask values')
02993             #
02994             ok = myim.set(pixels=1.0)
02995             if not ok:
02996                 stop('set 10 failed')
02997             blc = [0,0,4]
02998             trc = [2,3,9]
02999             r1 = rg.box(blc, trc)
03000             ok = myim.set(pixels=0.0, pixelmask=T, region=r1)
03001             if not ok:
03002                 stop('set 11 failed')
03003             pixels = myim.getregion()
03004             mask = myim.getregion(getmask=true)
03005             if len(pixels)==0 or len(pixels)==0:
03006                 stop('getregion 10 failed')
03007             blc2 = [3,4,10] # blc2 = trc+ 1
03008             tmp = pixels[blc[0]:trc[0],blc[1]:trc[1],blc[2]:trc[2]]
03009             for i in range(tmp.shape[0]):
03010                 for j in range(tmp.shape[1]):
03011                     for k in range(tmp.shape[2]):
03012                         if not (tmp[i][j][k] < 0.0001):
03013                             stop('getregion 10 recovers wrong pixel values')
03014             tmp = pixels[blc2[0]:imshape[0],blc2[1]:imshape[1],blc2[2]:imshape[2]]
03015             for i in range(tmp.shape[0]):
03016                 for j in range(tmp.shape[1]):
03017                     for k in range(tmp.shape[2]):
03018                         if not ((tmp[i][j][k] - 1) < 0.0001):
03019                             stop('getregion 10 recovers wrong pixel values')
03020             ok1 = (mask[blc[0]:trc[0],blc[1]:trc[1],blc[2]:trc[2]]).all()
03021             ok2 = (mask[blc2[0]:imshape[0],blc2[1]:imshape[1],blc2[2]:imshape[2]]).any()  # (not all false if ok2 is true)
03022             if not ok1 or ok2:
03023                 stop('getregion 10 recovers wrong mask values')
03024             #
03025             # Can not see a way to do this in casapy
03026             #global __global_setimage = ref myim
03027             #ok = myim.set(pixels='min('+myim+')')
03028             #if not ok:
03029             #    stop('set 11 failed')
03030             #
03031             # replacemaskedpixels
03032             #
03033             info('')
03034             info('Testing replacemaskedpixels')
03035             ok = myim.set(pixels=0.0, pixelmask=T)
03036             if not ok:
03037                 stop('set 12 failed')
03038             pixels = myim.getregion()
03039             mask = myim.getregion(getmask=true)
03040             if len(pixels)==0 or len(mask)==0:
03041                 stop('getregion 11 failed')
03042             ys = imshape[1] - 3
03043             ye = imshape[1]
03044             mask[0:2,ys:(ye+1),] = F
03045             ok = myim.putregion(pixelmask=mask)
03046             if not ok:
03047                 stop('putregion 8 failed')
03048             #
03049             try:
03050                 note('Expect SEVERE error and Exception here')
03051                 ok = myim.replacemaskedpixels(pixels=T)
03052             except Exception, e:
03053                 note('Expected exception occurred: '+str(e))
03054                 ok = False
03055             if ok:
03056                 stop('replacemaskedpixels 1 unexpectedly did not fail')
03057             try:
03058                 note('Expect SEVERE error and Exception here')
03059                 ok = myim.replacemaskedpixels(mask ='makemaskgood doggies')
03060             except Exception, e:
03061                 note('Expected exception occurred: '+str(e))
03062                 ok = False
03063             if ok:
03064                 stop('replacemaskedpixels 2 unexpectedly did not fail')
03065             #
03066             value = -1.0
03067             ok = myim.replacemaskedpixels(pixels=value)
03068             if not ok:
03069                 stop('replacemaskedpixels 3 failed')
03070             pixels = myim.getregion()
03071             mask2 = myim.getregion(getmask=true)
03072             if not ok:
03073                 stop('getregion 12 failed')
03074             tmp = pixels[0:2,ys:ye,] - value
03075             for i in range(tmp.shape[0]):
03076                 for j in range(tmp.shape[1]):
03077                     for k in range(tmp.shape[2]):
03078                         if not (tmp[i][j][k] < 0.0001):
03079                             stop('getregion 12 recovered wrong pixel values')
03080             tmp = pixels[2:imshape[0], 0:ys,]
03081             for i in range(tmp.shape[0]):
03082                 for j in range(tmp.shape[1]):
03083                     for k in range(tmp.shape[2]):
03084                         if not (tmp[i][j][k] < 0.0001):
03085                             stop('getregion 12 recovered wrong pixel values')
03086             if not allbooleq(mask,mask2):
03087                 stop('getregion 12 recovered wrong mask')
03088             #
03089             #global __global_replaceimage = ref myim
03090             value = 10.0
03091             #ex1 = 'max($__global_replaceimage)+10'
03092             #ok = myim.replacemaskedpixels(pixels=ex1)
03093             #if not ok:
03094             #    stop('replacemaskedpixels 4 failed')
03095             pixels = myim.getregion()
03096             mask2 = myim.getregion(getmask=true)
03097             if len(pixels)==0 or len(mask2)==0:
03098                 stop('getregion 13 failed')
03099             tmp = pixels[0:2,ys-1:ye,] - value
03100             for i in range(tmp.shape[0]):
03101                 for j in range(tmp.shape[1]):
03102                     for k in range(tmp.shape[2]):
03103                         if not (tmp[i][j][k] < 0.0001):
03104                             stop('getregion 13 recovered wrong pixel values')
03105             tmp = pixels[2:imshape[0], 0:(ys-2),]
03106             for i in range(tmp.shape[0]):
03107                 for j in range(tmp.shape[1]):
03108                     for k in range(tmp.shape[2]):
03109                         if not (tmp[i][j][k] < 0.0001):
03110                             stop('getregion 13 recovered wrong pixel values')
03111             if not allbooleq(mask,mask2):
03112                 stop('getregion 13 recovered wrong mask')
03113             #
03114             ok = myim.set(pixels=1.0, pixelmask=T)
03115             if not ok:
03116                 stop('set 12 failed')
03117             pixels = myim.getregion()
03118             mask = myim.getregion(getmask=true)
03119             if len(pixels)==0 or len(mask)==0:
03120                 stop('getregion 15 failed')
03121             mask[0,0,0] = F;
03122             mask[imshape[0]-1,imshape[1]-1,imshape[2]-1] = F
03123             ok = myim.putregion(pixelmask=mask)
03124             if not ok:
03125                 stop('putregion 9 failed')
03126             #
03127             imname2 = testdir + '/' + 'ia.fromshape.image3'
03128             myim2 = ia.newimagefromshape(outfile=imname2, shape=imshape)
03129             if not myim2:
03130                 stop('ia.newimagefromshape constructor 2 failed')
03131             ok = myim2.set(pixels=2.0)
03132             if not ok:
03133                 stop('set 13 failed')
03134             ex1 = '"' + imname2 +'"'
03135             ok = myim.replacemaskedpixels(pixels=ex1)
03136             if not ok:
03137                 stop('replacemaskedpixels 6 failed')
03138             pixels = myim.getregion()
03139             mask2 = myim.getregion(getmask=true)
03140             if len(pixels)==0 or len(mask2)==0:
03141                 stop('getregion 16 failed')
03142             if pixels[0,0,0]!=2 or pixels[imshape[0]-1,imshape[1]-1,imshape[2]-1]!=2:
03143                 stop('getregion 16a recovered wrong pixel values')
03144             tmp = pixels[1:(imshape[0]-2), 1:(imshape[1]-2),1:(imshape[2]-2)]
03145             for i in range(tmp.shape[0]):
03146                 for j in range(tmp.shape[1]):
03147                     for k in range(tmp.shape[2]):
03148                         if not (tmp[i][j][k] == 1.0):
03149                             stop('getregion 16b recovered wrong pixel values')
03150             #
03151             ok = myim.done();
03152             if not ok:
03153                 stop('Done 2 fails')
03154             ok = myim2.remove(T);
03155             if not ok:
03156                 stop('Done 3 fails')
03157 
03158         ###
03159         return cleanup(testdir)
03160 
03161     def test14():
03162         #
03163         # Test methods
03164         #   tofits
03165         #
03166         info('')
03167         info('')
03168         info('')
03169         info('Test 14 - FITS conversion')
03170         # Make the directory
03171         testdir = 'imagetest_temp'
03172         if not cleanup(testdir):
03173             note("Cleanup failed", "SEVERE")
03174             return false
03175         try:
03176             os.mkdir(testdir)
03177         except IOError, e:
03178             note(e, "SEVERE")
03179             raise RuntimeError, "mkdir " + testdir + " fails!"
03180 
03181         # Make image
03182         imshape = [12,24,20]
03183         myim = ia.newimagefromshape(shape=imshape)
03184         if not myim:
03185             stop('ia.fromshape constructor 1 failed')
03186         #
03187         fitsname1 = testdir + '/' + 'fimage1'
03188         ok = fitsreflect (myim, fitsname1)
03189         if not ok:
03190             fail('failed in fitsreflect')
03191         ok = fitsreflect (myim, fitsname1, do16=T)
03192         if not ok:
03193             fail('failed in second fitsreflect')
03194         #
03195         ok = myim.tofits(outfile=fitsname1, region=rg.box())
03196         if not ok:
03197             stop('tofits 1 failed')
03198         #
03199         fitsname2 = testdir + '/' + 'fimage2'
03200         r1 = rg.box(trc=[10000])
03201         ok = myim.tofits(outfile=fitsname2, region=r1)
03202         if not ok:
03203             stop('tofits 2 failed')
03204         #
03205         # Not useful because there is no spectral axis and I can't make one !
03206         #
03207         fitsname3 = testdir + '/' + 'fimage3'
03208         ok = myim.tofits(outfile=fitsname3, optical=F, velocity=F)
03209         if not ok:
03210             stop('tofits 3 failed')
03211         ok = myim.done();
03212         if not ok:
03213             stop('Done 1 fails')
03214         ###
03215         return cleanup(testdir)
03216 
03217     def test15():
03218         # Test methods
03219         #   boundingbox, {set}restoringbeam, coordmeasures, topixel, toworld
03220         info('-------')
03221         info('Test 15 - boundingbox,       ')
03222         info('          {set}restoringbeam ')
03223         info('          coordmeasures,     ')
03224         info('          topixel, toworld   ')
03225         info('-------')
03226 
03227         # Make the directory
03228         testdir = 'imagetest_temp'
03229         if not cleanup(testdir):
03230             note("Cleanup failed", "SEVERE")
03231             return false
03232         try:
03233             os.mkdir(testdir)
03234         except IOError, e:
03235             note(e, "SEVERE")
03236             raise RuntimeError, "mkdir " + testdir + " fails!"
03237 
03238         # Make images of all the wondrous flavours that we have
03239         root = testdir + '/' + 'testimage'
03240         imshape = [12,24,20]
03241         images = makeAllImageTypes(imshape, root, includereadonly=T)
03242         if not images:
03243             fail('failed to make all image types')
03244 
03245         # Loop over all image types
03246         types = images.keys()
03247         for mytype in types:
03248             info('')
03249             info('Testing Image type ' + images[mytype]["type"])
03250             myim = images[mytype]["tool"]
03251             imshape = myim.shape()
03252             #
03253             info('')
03254             info('Testing boundingbox')
03255             info('')
03256             bb = myim.boundingbox()
03257             if not bb:
03258                 stop('boundingbox 1 failed')
03259             ok = bb.has_key('blc') and bb.has_key('trc')
03260             ok = ok and bb.has_key('inc')
03261             ok = ok and bb.has_key('bbShape')
03262             ok = ok and bb.has_key('regionShape')
03263             ok = ok and bb.has_key('imageShape')
03264             if not ok:
03265                 stop('boundingbox record 1 has invalid fields')
03266             stat = not all(bb['blc'],[0,0,0])
03267             theTRC = []
03268             for value in imshape:
03269                 theTRC.append(value-1)
03270             stat = stat or (not all(bb['trc'], theTRC))
03271             stat = stat or (not all(bb['inc'], [1,1,1]))
03272             stat = stat or (not all(bb['bbShape'], imshape))
03273             stat = stat or (not all(bb['regionShape'], imshape))
03274             stat = stat or (not all(bb['imageShape'], imshape))
03275             if stat:
03276                 stop('boundingbox record 1 values are invalid')
03277             #
03278             blc = [2,3,4]
03279             trc = [5,8,15]
03280             inc = [1,2,3]
03281             #
03282             trc2 = [5,7,13];    # Account for stride
03283             rShape = [4,3,4]
03284             r1 = rg.box(blc=blc, trc=trc, inc=inc)
03285             bb = myim.boundingbox(region=r1)
03286             if not bb:
03287                 stop('boundingbox 2 failed')
03288             stat = not all(bb['blc'],blc)
03289             stat = stat or (not all(bb['trc'], trc2))
03290             stat = stat or (not all(bb['inc'], inc))
03291             bbshp = []
03292             for i in range(len(trc2)):
03293                 bbshp.append(trc2[i]-blc[i]+1)
03294             stat = stat or (not all(bb['bbShape'], bbshp))
03295             stat = stat or (not all(bb['regionShape'], rShape))
03296             stat = stat or (not all(bb['imageShape'], imshape))
03297             if stat:
03298                 stop('boundingbox record 2 values are invalid')
03299             #
03300             trc = [100,100,100]
03301             r1 = rg.box(trc=trc)
03302             bb = myim.boundingbox(region=r1)
03303             if not bb:
03304                 stop('boundingbox 4 failed')
03305             stat = not all(bb['blc'], [0,0,0])
03306             theTRC = []
03307             for value in imshape:
03308                 theTRC.append(value-1)
03309             stat = stat or (not all(bb['trc'], theTRC))
03310             stat = stat or (not all(bb['inc'], [1,1,1]))
03311             stat = stat or (not all(bb['bbShape'], imshape))
03312             stat = stat or (not all(bb['regionShape'], imshape))
03313             stat = stat or (not all(bb['imageShape'], imshape))
03314             if stat:
03315                 stop('boundingbox record 4 values are invalid')
03316             #
03317             trc = [10,20,30,40,50,60]
03318             r1 = rg.box(trc=trc)
03319             try:
03320                 note("Expect SEVERE Error and Exception here")
03321                 bb = myim.boundingbox(region=r1)
03322             except Exception, e:
03323                 #print "Expected Exception: ", e
03324                 note("Excepted occurred as expected.")
03325                 bb = {}
03326             if bb:
03327                 stop('boundingbox 5 unexpectedly did not fail')
03328 
03329         ok = cleanup(testdir)
03330         if not ok:
03331             fail('cleanup failed')
03332         #
03333         # Make image with all coordinate types
03334         #
03335         try:
03336             os.mkdir(testdir)
03337         except IOError, e:
03338             note(e, "SEVERE")
03339             raise RuntimeError, "mkdir " + testdir + " fails!"
03340         imname =  testdir + '/' + 'ia.fromshape.image2'
03341         imshape = [10,10,4,10,10]
03342         ok = ia.fromshape(outfile=imname, shape=imshape)
03343         if not ok:
03344             stop('ia.fromshape 2 failed')
03345         ia.close()
03346         myim = ia.newimage(imname)
03347         #
03348         # Coordmeasures. A wrapper for coordsys where testing more thorough
03349         #
03350         info('')
03351         info('Testing coordmeasures')
03352         info('')
03353         mycs = myim.coordsys()
03354         if not mycs:
03355             fail('failed to get mycs from image')
03356         rp = mycs.referencepixel()
03357         if not rp:
03358             fail('failed to get referencepixel')
03359         if not mycs.done():
03360             fail('failed to close mycs')
03361         w = myim.coordmeasures(list(rp['numeric']))
03362         if not w:
03363             stop('coordmeasures failed')
03364         w = w['measure']
03365         ok = w.has_key('direction') and w.has_key('spectral')
03366         ok = ok and w.has_key('stokes')
03367         ok = ok and w.has_key('linear')
03368         if not ok:
03369             stop('coordmeasures record has wrong fields')
03370         #
03371         # topixel/toworld are just wrappers; coordsys tests more thoroughly
03372         #
03373         info('')
03374         info('Testing topixel/toworld')
03375         info('')
03376         #w = myim.toworld(list(rp['numeric']), 'nqms')
03377         w = myim.toworld(rp, 'nqms')
03378         if not w:
03379             fail('failed toworld')
03380         p = myim.topixel(w)
03381         if not p:
03382             fail('failed topixel')
03383         #
03384         ok = myim.done()
03385         if not ok:
03386             stop('Done 2 fails')
03387             
03388         ###
03389         return cleanup(testdir)
03390 
03391     def test16():
03392         #
03393         # Test methods
03394         #   summary, maskhandler
03395         #
03396         info('')
03397         info('')
03398         info('')
03399         info('Test 16 - summary, maskhandler')
03400         # Make the directory
03401         testdir = 'imagetest_temp'
03402         if not cleanup(testdir):
03403             note("Cleanup failed", "SEVERE")
03404             return false
03405         try:
03406             os.mkdir(testdir)
03407         except IOError, e:
03408             note(e, "SEVERE")
03409             raise RuntimeError, "mkdir " + testdir + " fails!"
03410 
03411         # Make images of all the wondrous flavours that we have
03412         root = testdir + '/' + 'testimage'
03413         imshape = [12,24,20]
03414         images = makeAllImageTypes(imshape, root, includereadonly=T)
03415         if not images:
03416             fail('failed to make all image types')
03417 
03418         # Loop over all image types
03419         info('')
03420         info('Testing summary')
03421         types = images.keys()
03422         for mytype in types:
03423             info('')
03424             info('Testing Image type ' + images[mytype]["type"])
03425             myim = images[mytype]["tool"]
03426             imshape = myim.shape()
03427             #
03428             # Summary
03429             #
03430             header = myim.summary(list=F)
03431             if not header:
03432                 fail('unable to retrieve summary')
03433             ok = header.has_key('ndim') and header.has_key('shape')
03434             ok = ok and header.has_key('tileshape')
03435             ok = ok and header.has_key('axisnames')
03436             ok = ok and header.has_key('refpix')
03437             ok = ok and header.has_key('refval')
03438             ok = ok and header.has_key('incr')
03439             ok = ok and header.has_key('axisunits')
03440             ok = ok and header.has_key('unit')
03441             ok = ok and header.has_key('imagetype')
03442             ok = ok and header.has_key('hasmask')
03443             ok = ok and header.has_key('defaultmask')
03444             ok = ok and header.has_key('masks')
03445             if not ok:
03446                 stop('summary record is invalid')
03447             if not myim.done():
03448                 fail('failed in myim.done')
03449         ok = cleanup(testdir)
03450         if not ok:
03451             fail('could not cleanup testdir')
03452         #
03453         # Masks
03454         #
03455         try:
03456             os.mkdir(testdir)
03457         except IOError, e:
03458             note(e, "SEVERE")
03459             raise RuntimeError, "mkdir " + testdir + " fails!"
03460         imshape = [12,24,20]
03461         images = makeAllImageTypes(imshape, root, includereadonly=F)
03462         if not images:
03463             fail('failed to make all image types')
03464         #
03465         # Loop over all image types
03466         #
03467         info('')
03468         info('Testing maskhandler')
03469         types = images.keys()
03470         for mytype in types:
03471             info('')
03472             info('Testing Image type ' + images[mytype]["type"])
03473             myim = images[mytype]["tool"]
03474             imshape = myim.shape()
03475             #
03476             myim2 = ia.newimagefromshape(shape=imshape)
03477             if not myim2:
03478                 stop('ia.fromshape constructor 2 failed')
03479             #
03480             pixels = myim.getregion()
03481             mask = myim.getregion(getmask=true)
03482             if len(pixels)==0 or len(mask)==0:
03483                 stop('getregion 1 failed')
03484             #
03485             ok = myim.putregion(pixels, mask)
03486             if not ok:
03487                 stop('putregion 1a failed')
03488             ok = myim2.putregion(pixels, mask)
03489             if not ok:
03490                 stop('putregion 1b failed')
03491             #
03492             names = myim.maskhandler('get')
03493             if not names:
03494                 stop('maskhandler 1a failed')
03495             if (names[0]!="mask0"):      #(len(names)!=1) doesn't work
03496                 stop('maskhandler 1a unexpectedly recovered more than 1 mask')
03497             names = myim2.maskhandler('get')
03498             if not names:
03499                 stop('maskhandler 1b failed')
03500             if (names[0]!="mask0"):      #(len(names)!=1) doesn't work
03501                 stop('maskhandler 1b unexpectedly recovered more than 1 mask')
03502             #
03503             ok = myim.maskhandler('set', name=names)
03504             if not ok[0]=="T":
03505                 stop('maskhandler 2a failed')
03506             ok = myim2.maskhandler('set', name=names)
03507             if not ok[0]=="T":
03508                 stop('maskhandler 2b failed')
03509             #
03510             defname = myim.maskhandler('default')
03511             if not defname:
03512                 stop('maskhandler 3a failed')
03513             if (names!=defname):
03514                 stop('maskhandler 3a did not recover the default mask name')
03515             defname = myim2.maskhandler('default')
03516             if not defname:
03517                 stop('maskhandler 3b failed')
03518             if (names!=defname):
03519                 stop('maskhandler 3b did not recover the default mask name')
03520             #
03521             names.append('fish')
03522             ok = myim.maskhandler('rename', names)
03523             if not ok[0]=="T":
03524                 stop('maskhandler 4a failed')
03525             ok = myim2.maskhandler('rename', names)
03526             if not ok[0]=="T":
03527                 stop('maskhandler 4b failed')
03528             #
03529             names = myim.maskhandler('get')
03530             if not names:
03531                 stop('maskhandler 5a failed')
03532             if names[0]!='fish':
03533                 stop('maskhandler 5a did not recover the correct mask name')
03534             names = myim2.maskhandler('get')
03535             if not names:
03536                 stop('maskhandler 5b failed')
03537             if (names[0]!='fish'):
03538                 stop('maskhandler 5b did not recover the correct mask name')
03539             #
03540             names = ['fish', 'mask1']
03541             ok = myim.maskhandler('copy', names)
03542             if not ok:
03543                 stop('maskhandler 6a failed')
03544             ok = myim2.maskhandler('copy', names)
03545             if not ok:
03546                 stop('maskhandler 6b failed')
03547             #
03548             names = myim.maskhandler('get')
03549             if not names:
03550                 stop('maskhandler 7a failed')
03551             if (len(names)!=2):
03552                 stop('maskhandler 7a unexpectedly recovered more than 2 mask')
03553             if (names[0] !='fish' or names[1]!='mask1'):
03554                 stop('maskhandler 7a did not recover the correct mask names')
03555             names = myim2.maskhandler('get')
03556             if not names:
03557                 stop('maskhandler 7b failed')
03558             if (len(names)!=2):
03559                 stop('maskhandler 7b unexpectedly recovered more than 2 mask')
03560             if (names[0] !='fish' or names[1]!='mask1'):
03561                 stop('maskhandler 7b did not recover the correct mask names')
03562             #
03563             ok = myim.maskhandler('set', 'mask1')
03564             if not ok:
03565                 stop('maskhandler 8b failed')
03566             ok = myim2.maskhandler('set', 'mask1')
03567             if not ok:
03568                 stop('maskhandler 8b failed')
03569             #
03570             defname = myim.maskhandler('default')
03571             if not defname:
03572                 stop('maskhandler 9a failed')
03573             if (defname[0] !='mask1'):
03574                 stop('maskhandler 9a did not recover the correct default mask name')
03575             defname = myim2.maskhandler('default')
03576             if not defname:
03577                 stop('maskhandler 9b failed')
03578             if (defname[0] !='mask1'):
03579                 stop('maskhandler 9b did not recover the correct default mask name')
03580             #
03581             names = myim.maskhandler('get')
03582             if not names:
03583                 stop('maskhandler 10a failed')
03584             names = myim2.maskhandler('get')
03585             if not names:
03586                 stop('maskhandler 10b failed')
03587             #
03588             ok = myim.maskhandler('delete', names)
03589             if not ok:
03590                 stop('maskhandler 11a failed')
03591             ok = myim2.maskhandler('delete', names)
03592             if not ok:
03593                 stop('maskhandler 11b failed')
03594             #
03595             names = myim.maskhandler('get')
03596             if not names:
03597                 stop('maskhandler 12a failed')
03598             if (names[0]!="T"):
03599                 return('maskhandler 12a failed to delete the masks')
03600             names = myim2.maskhandler('get')
03601             if not names:
03602                 stop('maskhandler 12b failed')
03603             if (names[0]!="T"):
03604                 return('maskhandler 12b failed to delete the masks')
03605             if not (myim2.done()):
03606                 fail('failed done in test16')
03607             #
03608             ok = myim.done()
03609             ###
03610         return cleanup(testdir)
03611         #end test16
03612 
03613     def test17():
03614         #
03615         # Test methods
03616         #   subimage, insert
03617         #
03618         info('')
03619         info('')
03620         info('')
03621         info('Test 17 - subimage, insert')
03622         # Make the directory
03623         testdir = 'imagetest_temp'
03624         if not cleanup(testdir):
03625             return False
03626         try:
03627             os.mkdir(testdir)
03628         except IOError, e:
03629             note(e, "SEVERE")
03630             raise RuntimeError, "mkdir " + testdir + " fails!"
03631         # Make image
03632         imname = testdir +'/'+'ia.fromshape.image1'
03633         imshape = [10,20,6]
03634         myim = ia.newimagefromshape(outfile=imname, shape=imshape)
03635         if not myim:
03636             stop('ia.fromshape constructor 1 failed')
03637         #
03638         # Subimage
03639         #
03640         info('')
03641         info('Testing subimage function')
03642         imname2 = testdir+'/'+'subimage.image'
03643         pixels = myim.getregion()
03644         mask = myim.getregion(getmask=true)
03645         if len(pixels)==0 or len(mask)==0:
03646             stop('getregion 1 failed')
03647         mask[imshape[0]/2,imshape[1]/2,imshape[2]/2] = F
03648         ok = myim.putregion(pixelmask=mask)
03649         if not ok:
03650             stop('putregion 1 failed')
03651         #
03652         dowait = F
03653         try:
03654             note('Expect SEVERE error and Exception here')
03655             myim2 = myim.subimage(outfile=imname2, region='doggies')
03656         except Exception, e:
03657             note('Caught expected Exception')
03658             myim2 = false
03659         if myim2:
03660             stop('subimage 1 unexpectedly did not fail')
03661         #
03662         #r1 = rg.quarter()
03663         #r1 = myim.setboxregion([0.25,0.25],[0.75,0.75],frac=true)
03664         r1 = rg.box([0.25,0.25],[0.75,0.75],frac=true)
03665         myim2 = myim.subimage(outfile=imname2, region=r1)
03666         if not myim2:
03667             stop('subimage 2 failed')
03668         #
03669         bb = myim.boundingbox(region=r1)
03670         shape = bb['regionShape']
03671         shape2 = myim2.shape()
03672         if not all(shape,shape2):
03673             stop ('Output subimage has wrong shape');
03674         #
03675         pixels = myim.getregion(region=r1)
03676         mask = myim.getregion(getmask=true, region=r1)
03677         if len(pixels)==0 or len(mask)==0:
03678             stop('getregion 2 failed')
03679         pixels2 = myim2.getregion()
03680         mask2 = myim2.getregion(getmask=true)
03681         if not ok:
03682             stop('getregion 3 failed')
03683         if not alleq(pixels,pixels2,tolerance=0.0001):
03684             stop('The data values are wrong in the subimage')
03685         if not allbooleq(mask,mask2):
03686             stop('The mask values are wrong in the subimage')
03687         ok = myim2.remove(done=T)
03688         if not ok:
03689             stop('Failed to remove' + imname2)
03690         ok = myim.done()
03691         if not ok:
03692             stop('Done 1 failed')
03693         #
03694         # Insert
03695         #
03696         info('')
03697         info('Testing insert function')
03698         imname = testdir+'/'+'ia.fromshape.image'
03699         a = ia.makearray(1,[10,20])
03700         myim = ia.newimagefromarray(outfile=imname, pixels=a)
03701         if not myim:
03702             stop('ia.fromarray constructor 2 failed')
03703         #
03704         try:
03705             note("Expect SEVERE error and Exception here")
03706             ok = myim.insert(region='fish')
03707         except Exception, e:
03708             note("Caught expected exception.")
03709             ok = false
03710         if ok:
03711             stop('insert 1 unexpectedly did not fail')
03712         #
03713         pixels = myim.getchunk()
03714         if len(pixels)==0:
03715             stop('getchunk 1 failed')
03716         #
03717         padshape = [myim.shape()[0]+2,myim.shape()[1]+2]
03718         padname = testdir+'/'+'insert.image'
03719         myim2 = ia.newimagefromshape(shape=padshape)
03720         if not myim2:
03721             fail('failed to create myim2 from padshape')
03722         #
03723         ok = myim2.insert(infile=myim.name(F), locate=[0,0,0])
03724         if not ok:
03725             fail('failed to insert myim')
03726         pixels2 = myim2.getchunk()
03727         if len(pixels2)==0:
03728             stop('getchunk 2 failed')
03729         pixels3 = pixels2[0:(padshape[0]-2), 0:(padshape[1]-2)]
03730         if not alleqnum(pixels3,1.0,tolerance=0.0001):
03731             stop('inserted image pixels have wrong value (1)')
03732         #
03733         myim2.set(0.0)
03734         ok = myim2.insert(infile=myim.name(F));  # Placed symmetrically
03735         if not ok:
03736             fail('failed insert')
03737         pixels2 = myim2.getchunk()
03738         if len(pixels2)==0:
03739             fail('failed to getchunk')
03740         if (pixels2[0,0]!=0.0):
03741             stop('inserted image pixels have wrong value (3)')
03742         if not alleqnum(pixels2[1:(padshape[0]-1),1:(padshape[1]-1)],1.0,tolerance=0.0001):
03743             stop('inserted image pixels have wrong value (2)')
03744         if not myim2.done():
03745             fail('failed myim2.done')
03746         #
03747         ok = myim.done()
03748         if not ok:
03749             stop('Done 3 failed')
03750         ###
03751         return cleanup(testdir)
03752 
03753     def test18():
03754         #
03755         # Test methods
03756         #   hanning
03757         #
03758         info('');
03759         info('');
03760         info('');
03761         info('Test 18 - hanning');
03762         # Make the directory
03763         testdir = 'imagetest_temp'
03764         if not cleanup(testdir):
03765             return False
03766         try:
03767             os.mkdir(testdir)
03768         except IOError, e:
03769             note(e, "SEVERE")
03770             raise RuntimeError, "mkdir " + testdir + " fails!"
03771         # Make image
03772         imname = testdir+'/'+'ia.fromshape.image'
03773         imshape = [10,20]
03774         myim = ia.newimagefromshape(outfile=imname, shape=imshape)
03775         if not myim:
03776             stop('ia.fromshape constructor 1 failed')
03777         pixels = myim.getchunk()
03778         if len(pixels)==0:
03779             stop('getchunk 1 failed')
03780         for i in range(pixels.shape[0]):
03781             for j in range(pixels.shape[1]):
03782                 if pixels[i][j]>-10000:
03783                     pixels[i][j]=1
03784         ok = myim.putchunk(pixels)
03785         if not ok:
03786             stop('putchunk 1 failed')
03787         #
03788         try:
03789             note('Expect SEVERE error and Exception here')
03790             myim2 = myim.hanning(region='fish');
03791         except Exception, e:
03792             note('Caught expected Exception')
03793             myim2 = false
03794         if myim2:
03795             stop('hanning 1 unexpectedly did not fail')
03796         try:
03797             note('Expect SEVERE error and Exception here')
03798             myim2 = myim.hanning(axis=19)
03799         except Exception, e:
03800             note('Caught expected Exception')
03801             myim2 = false
03802         if myim2:
03803             stop('hanning 2 unexpectedly did not fail')
03804         try:
03805             note('Expect SEVERE error and Exception here')
03806             myim2 = myim.hanning(drop='fish')
03807         except Exception, e:
03808             note('Caught expected Exception:'+str(e))
03809             myim2 = false
03810         if myim2:
03811             stop('hanning 3 unexpectedly did not fail')
03812         try:
03813             note('Expect SEVERE error and Exception here')
03814             myim2 = myim.hanning(outfile=[1,2,3])
03815         except Exception, e:
03816             note('Caught expected Exception:'+str(e))
03817             myim2 = false
03818         if myim2:
03819             stop('hanning 4 unexpectedly did not fail')
03820         #
03821         hanname = testdir+'/'+'hanning.image'
03822         myim2 = myim.hanning(outfile=hanname, axis=0, drop=F)
03823         if not myim2:
03824             stop('hanning 5 failed')
03825         if not all(myim2.shape(),myim.shape()):
03826             stop('Output image has wrong shape (1)')
03827         pixels2 = myim2.getchunk()
03828         if len(pixels2)==0:
03829             stop('getchunk 2 failed')
03830         if not alleqnum(pixels2,1,tolerance=0.0001):
03831             stop('hanning image pixels have wrong value (1)')
03832         ok = myim2.remove(done=T)
03833         if not ok:
03834             stop('Failed to remove'+hanname)
03835         #
03836         myim2 = myim.hanning(outfile=hanname, axis=0, drop=T)
03837         if not myim2:
03838             stop('hanning 6 failed')
03839         shape2 = [myim.shape()[0]/2-1,myim.shape()[1]]
03840         if not all(myim2.shape(),shape2):
03841             stop('Output image has wrong shape (2)')
03842         pixels2 = myim2.getchunk()
03843         if len(pixels2)==0:
03844             stop('getchunk 3 failed')
03845         if not alleqnum(pixels2,1,tolerance=0.0001):
03846             stop('Hanning image pixels have wrong value (2)')
03847         ok = myim2.remove(done=T)
03848         if not ok:
03849             stop('Failed to remove'+hanname)
03850         #
03851         pixels = myim.getregion()
03852         mask = myim.getregion(getmask=true)
03853         if len(pixels)==0 or len(mask)==0:
03854             stop('getregion 1 failed')
03855         mask[0,0] = F
03856         mask[1,0] = F
03857         mask[2,0] = F
03858         mask[3,0] = F
03859         ok = myim.putregion(pixelmask=mask)
03860         if not ok:
03861             stop('putregion 1 failed')
03862         myim2 = myim.hanning(outfile=hanname, axis=0, drop=F)
03863         if not myim2:
03864             stop('hanning 7 failed')
03865         pixels2 = myim2.getregion()
03866         mask2 = myim2.getregion(getmask=true)
03867         if not ok:
03868             stop('getregion 2 failed')
03869         ok = (mask2[0,0]==F and mask2[1,0]==F)
03870         ok = ok and mask2[2,0]==F
03871         ok = ok and mask2[3,0]==F
03872         if not ok:
03873             stop('Hanning image mask is wrong (1)')
03874         ok = pixels2[0,0]==0 and pixels2[1,0]==0
03875         ok = ok and pixels2[2,0]==0
03876         ok = ok and pixels2[3,0]==0.25
03877         if not ok:
03878             stop('Hanning image pixels have wrong value (3)')
03879         ok = myim2.done()
03880         if not ok:
03881             stop('Done 1 failed')
03882         #
03883         ok = myim.done()
03884         if not ok:
03885             stop('Done 2 failed')
03886         ###
03887         return cleanup(testdir)
03888 
03889     def test19():
03890         #
03891         # Test methods
03892         #   convolve
03893         #
03894         info('')
03895         info('')
03896         info('')
03897         info('Test 19 - convolve')
03898         # Make the directory
03899         testdir = 'imagetest_temp'
03900         if not cleanup(testdir):
03901             return False
03902         try:
03903             os.mkdir(testdir)
03904         except IOError, e:
03905             note(e, "SEVERE")
03906             raise RuntimeError, "mkdir " + testdir + " fails!"
03907         # Make image
03908         imname = testdir+'/'+'ia.fromshape.image'
03909         imshape = [10,10]
03910         myim = ia.newimagefromshape(outfile=imname, shape=imshape)
03911         if not myim:
03912             stop('ia.fromshape constructor 1 failed')
03913         pixels = myim.getchunk()
03914         if len(pixels)==0:
03915             stop('getchunk 1 failed')
03916         for i in range(pixels.shape[0]):
03917             for j in range(pixels.shape[1]):
03918                 if pixels[i][j]>-10000:
03919                     pixels[i][j]=1
03920         ok = myim.putchunk(pixels)
03921         if not ok:
03922             stop('putchunk 1 failed')
03923         # 
03924         try:
03925             note('Expect SEVERE error and Exception here - 1')
03926             kernel = ia.makearray(0.0,[3,3])
03927             myim2 = myim.convolve(kernel=kernel, region='fish');
03928         except Exception, e:
03929             note('Caught expected Exception:'+str(e))
03930             myim2 = false
03931         if myim2:
03932             stop('convolve 1 unexpectedly did not fail')
03933         try:
03934             note('Expect SEVERE error and Exception here - 2')
03935             #kernel = array(0,2,4,6,8)
03936             kernel = ia.makearray(0,[2,4,6,8])
03937             myim2 = myim.convolve(kernel=kernel)
03938         except Exception, e:
03939             note('Caught expected Exception: '+str(e))
03940             myim2 = false
03941         if myim2:
03942             stop('convolve 3 unexpectedly did not fail')
03943         try:
03944             note('Expect SEVERE error and Exception here - 3')
03945             myim2 = myim.convolve(outfile=[1,2,3])
03946         except Exception, e:
03947             note('Caught expected Exception: '+str(e))
03948             myim2 = false
03949         if myim2:
03950             stop('convolve 4 unexpectedly did not fail')
03951         #
03952         outname = testdir+'/'+'convolve.image'
03953         kernel = ia.makearray(0.0,[3,3])
03954         kernel[1,1] = 1;                   # Delta function
03955         #
03956         myim2 = myim.convolve(outfile=outname, kernel=kernel)
03957         if not myim2:
03958             stop('convolve 5 failed')
03959         if not all(myim2.shape(),myim.shape()):
03960             stop('Output image has wrong shape (1)')
03961         pixels2 = myim2.getchunk()
03962         if len(pixels2)==0:
03963             stop('getchunk 2 failed')
03964         if not alleq(pixels2, pixels, 0.0001):
03965             stop('convolve image pixels have wrong value (1)')
03966         ok = myim2.remove(done=T)
03967         if not ok:
03968             stop('Failed to remove'+outname)
03969         #
03970         kernelname = testdir+'/'+'convolve.kernel'
03971         kernelimage = ia.newimagefromarray(outfile=kernelname, pixels=kernel)
03972         kernelimage.done()
03973         myim2 = myim.convolve(outfile=outname, kernel=kernelname)
03974         if not myim2:
03975             stop('convolve 5b failed')
03976         if not all(myim2.shape(),myim.shape()):
03977             stop('Output image has wrong shape (1)')
03978         pixels2 = myim2.getchunk()
03979         if len(pixels2)==0:
03980             stop('getchunk 2b failed')
03981         if not alleq(pixels2,pixels,0.0001):
03982             stop('convolve image pixels have wrong value (1b)')
03983         ok = myim2.remove(done=T)
03984         if not ok:
03985             stop('Failed to remove' + outname)
03986         r1 = rg.box([0,0], [8,8])
03987         myim2 = myim.convolve(outfile=outname, kernel=kernel, region=r1)
03988         if not myim2:
03989             stop('convolve 6 failed')
03990         if myim2.shape()[0] != 9 or myim2.shape()[1] !=9:
03991             stop('Output image has wrong shape (2)')
03992         pixels2 = myim2.getchunk()
03993         if len(pixels2)==0:
03994             stop('getchunk 3 failed')
03995         pixels = myim.getregion(region=r1)
03996         mask = myim.getregion(getmask=true, region=r1)
03997         if len(pixels)==0 or len(mask)==0:
03998             stop('getregion 3 failed')
03999         if not alleq(pixels2,pixels,0.0001):
04000             stop('convolve image pixels have wrong value (2)')
04001         ok = myim2.remove(done=T)
04002         if not ok:
04003             stop('Failed to remove' + outname)
04004         #
04005         pixels = myim.getregion()
04006         mask = myim.getregion(getmask=true)
04007         if len(pixels)==0 or len(mask)==0:
04008             stop('getregion 1 failed')
04009         mask[0,0] = F
04010         mask[1,0] = F
04011         mask[0,1] = F
04012         mask[1,1] = F
04013         ok = myim.putregion(pixelmask=mask)
04014         if not ok:
04015             stop('putregion 1 failed')
04016         myim2 = myim.convolve(outfile=outname, kernel=kernel)
04017         if not myim2:
04018             stop('convolve 7 failed')
04019         pixels2 = myim2.getregion()
04020         mask2 = myim2.getregion(getmask=true)
04021         if len(pixels2)==0 or len(mask2)==0:
04022             stop('getregion 2 failed')
04023         ok = mask2[0,0]==F and mask2[1,0]==F
04024         ok = ok and mask2[0,1]==F
04025         ok = ok and mask2[1,1]==F
04026         if not ok:
04027             stop('convolved image mask is wrong (1)')
04028         ok = abs(pixels2[0,0])<0.0001 and abs(pixels2[1,0])<0.0001
04029         ok = ok and abs(pixels2[0,1])<0.0001
04030         ok = ok and abs(pixels2[1,1])<0.0001
04031         ok = ok and abs(pixels2[2,2]-1.0)<0.0001
04032         if not ok:
04033             stop('convolved image pixels have wrong value (3)')
04034         ok = myim2.done()
04035         if not ok:
04036             stop('Done 1 failed')
04037         #
04038         ok = myim.done()
04039         if not ok:
04040             stop('Done 2 failed')
04041         ###
04042         return cleanup(testdir)
04043 
04044     def test20():
04045         #
04046         # Test methods
04047         #   sepconvolve
04048         #
04049         info('')
04050         info('')
04051         info('')
04052         info('Test 20 - sepconvolve')
04053         # Make the directory
04054         testdir = 'imagetest_temp'
04055         if not cleanup(testdir):
04056             return False
04057         try:
04058             os.mkdir(testdir)
04059         except IOError, e:
04060             note(e, "SEVERE")
04061             raise RuntimeError, "mkdir " + testdir + " fails!"
04062         # Make image
04063         imname = testdir+'/'+'ia.fromshape.image'
04064         imshape = [128,128]
04065         centre = [imshape[0]/2,imshape[1]/2]
04066         myim = ia.newimagefromshape(outfile=imname, shape=imshape)
04067         if not myim:
04068             stop('ia.fromshape constructor 1 failed')
04069         pixels = myim.getchunk()
04070         if len(pixels)==0:
04071             stop('getchunk 1 failed')
04072         pixels[centre] = 1
04073         pixels[centre[0]-1, centre[1]-1] = 1
04074         pixels[centre[0]-1, centre[1]+1] = 1
04075         pixels[centre[0]+1, centre[1]+1] = 1
04076         pixels[centre[0]+1, centre[1]+1] = 1
04077         #
04078         ok = myim.putchunk(pixels)
04079         if not ok:
04080             stop('putchunk 1 failed')
04081         #
04082         try:
04083             note('Expect SEVERE error and Exception here')
04084             myim2 = myim.sepconvolve(region='fish');
04085         except Exception, e:
04086             note('Caught expected Exception')
04087             myim2 = false
04088         if myim2:
04089             stop('sepconvolve 1 unexpectedly did not fail')
04090         try:
04091             note('Expect SEVERE error and Exception here')
04092             myim2 = myim.sepconvolve(types=["doggies"], widths=[1], axes=[0])
04093         except Exception, e:
04094             note('Caught expected Exception')
04095             myim2 = false
04096         if myim2:
04097             stop('sepconvolve 2 unexpectedly did not fail')
04098         try:
04099             note('Expect SEVERE error and Exception here')
04100             myim2 = myim.sepconvolve(types=["gauss","gauss","gauss","gauss"],
04101                                      widths=[5,5,5,5], axes=[0,1,2,3])
04102         except Exception, e:
04103             note('Caught expected Exception')
04104             myim2 = false
04105         if myim2:
04106             stop('sepconvolve 3 unexpectedly did not fail')
04107         try:
04108             note('Expect SEVERE error and Exception here')
04109             myim2 = myim.sepconvolve(types=["gauss","gauss"], widths=[1], axes=[0,1])
04110         except Exception, e:
04111             note('Caught expected Exception')
04112             myim2 = false
04113         if myim2:
04114             stop('sepconvolve 4 unexpectedly did not fail')
04115         try:
04116             note('Expect SEVERE error and Exception here')
04117             myim2 = myim.sepconvolve(outfile=[1,2,3])
04118         except Exception, e:
04119             note('Caught expected Exception')
04120             myim2 = false
04121         if myim2:
04122             stop('sepconvolve 5 unexpectedly did not fail')
04123         #
04124         outname2 = testdir+'/'+'sepconvolve.image'
04125         myim2 = myim.sepconvolve(outfile=outname2, axes=[0,1],
04126                                  types=["gauss","box"], widths=[3,3])
04127         if not myim2:
04128             stop('sepconvolve 6 failed')
04129         ok = myim2.remove(done=T)
04130         if not ok:
04131             stop('Failed to remove' + outname2)
04132         #
04133         outname2 = testdir+'/'+'sepconvolve.image'
04134         myim2 = myim.sepconvolve(outfile=outname2, axes=[0,1],
04135                                  types=["hann","gauss"], widths=[3,10])
04136         if not myim2:
04137             fail('Failed in sepconvolve')
04138         ok = myim2.remove(done=T)
04139         if not ok:
04140             stop('Failed to remove' + outname2)
04141         #
04142         myim2 = myim.sepconvolve(outfile=outname2, axes=[0,1],
04143                                types=["gauss","gauss"], widths=[5,5])
04144         if not myim2:
04145             fail('failed in sepconvole')
04146         stats1 = myim.statistics(list=F);
04147         if not stats1:
04148             fail('failed to get statistics')
04149         stats2 = myim2.statistics(list=F)
04150         if not stats2:
04151             fail('failed to get stat2')
04152         #if not (abs((stats1['sum'])-(stats2['sum']))<0.0001):
04153         #    stop('Convolution did not preserve flux (1)')
04154         ok = myim2.remove(done=T)
04155         if not ok:
04156             stop('Failed to remove' + outname2)
04157         #
04158         cen = [imshape[0]/2-1,imshape[1]/2-1]
04159         blc = [cen[0]-10,cen[1]-10]
04160         trc = [cen[0]+10,cen[1]+10]
04161         r1 = rg.box(blc, trc)
04162         myim2 = myim.sepconvolve(outfile=outname2, axes=[0],
04163                                  types="hann", widths=[3], region=r1)
04164         if not myim2:
04165             fail('failed in sepconvolve')
04166         if not all(myim2.shape(),[trc[0]-blc[0]+1,trc[1]-blc[1]+1]):
04167             stop('Output image has wrong shape (2)')
04168         pixels2 = myim2.getchunk()
04169         if len(pixels2)==0:
04170             stop('getchunk 3 failed')
04171         #     if (!(abs(sum(pixels)-sum(pixels2))<0.0001)) {
04172         #        stop('Convolution did not preserve flux (2)')
04173         ok = myim2.remove(done=T)
04174         if not ok:
04175             stop('Failed to remove', outname2)
04176         #
04177         pixels = myim.getregion()
04178         mask = myim.getregion(getmask=true)
04179         if len(pixels)==0 or len(mask)==0:
04180             fail('failed getregion in sepconvolve')
04181         mask[0,0] = F
04182         mask[1,0] = F
04183         mask[0,1] = F
04184         mask[1,1] = F
04185         ok = myim.putregion(pixels=pixels, pixelmask=mask)
04186         if not ok:
04187             stop('putregion 1 failed')
04188         myim2 = myim.sepconvolve(outfile=outname2, types="gauss",
04189                                  widths=[10], axes=[0])
04190         if not myim2:
04191             stop('sepconvolve 8 failed')
04192         pixels2 = myim2.getregion()
04193         mask2 = myim2.getregion(getmask=true)
04194         if not ok:
04195             stop('getregion 2 failed')
04196         ok = mask2[0,0]==F and mask2[1,0]==F
04197         ok = ok and mask2[0,1]==F
04198         ok = ok and mask2[1,1]==F
04199         if not ok:
04200             stop('convolved image mask is wrong (1)')
04201         ok = myim2.done()
04202         if not ok:
04203             stop('Done 1 failed')
04204         #
04205         # Some more tests just on the widths interface.
04206         #
04207         myim2 = myim.sepconvolve(widths=[10,10], axes=[0,1])
04208         if not myim2: stop ('sepconvolve 9 failed')
04209         if not myim2.done(): fail('failed myim2.done')
04210         #
04211         #myim2 = myim.sepconvolve(widths="10 10", axes=[0,1])
04212         myim2 = myim.sepconvolve(widths="10pix 10pix", axes=[0,1])
04213         if not myim2: stop ('sepconvolve 10 failed')
04214         if not myim2.done(): fail('failed myim2.done')
04215         #
04216         myim2 = myim.sepconvolve(widths="0.01rad 10pix", axes=[0,1])
04217         if not myim2: stop ('sepconvolve 11 failed')
04218         if not myim2.done(): fail('failed myim2.done')
04219         #
04220         #myim2 = myim.sepconvolve(widths="20 10pix", axes=[0,1])
04221         myim2 = myim.sepconvolve(widths="20pix 10pix", axes=[0,1])
04222         if not myim2: stop ('sepconvolve 12 failed')
04223         if not myim2.done(): fail('failed myim2.done')
04224         #
04225         #myim2 = myim.sepconvolve(widths='10 10', axes=[0,1])
04226         myim2 = myim.sepconvolve(widths='10pix 10pix', axes=[0,1])
04227         if not myim2: stop ('sepconvolve 13 failed')
04228         if not myim2.done(): fail('failed myim2.done')
04229         #
04230         #widths = qa.quantity("0.01rad 0.02rad")
04231         widths = "0.01rad 0.02rad"
04232         myim2 = myim.sepconvolve(widths=widths, axes=[0,1])
04233         if not myim2: stop ('sepconvolve 14 failed')
04234         if not myim2.done(): fail('failed myim2.done')
04235         #
04236         ok = myim.done()
04237         if not ok:
04238             stop('Done 2 failed')
04239         ###
04240 
04241         return cleanup(testdir)
04242 
04243     def test21():
04244         #
04245         # Test methods
04246         #   lel
04247         #
04248         info('')
04249         info('')
04250         info('')
04251         info('Test 21 - LEL')
04252         # Make the directory
04253         testdir = 'imagetest_temp'
04254         if not cleanup(testdir):
04255             return False
04256         try:
04257             os.mkdir(testdir)
04258         except IOError, e:
04259             note(e, "SEVERE")
04260             raise RuntimeError, "mkdir " + testdir + " fails!"
04261 
04262         # Define some arrays to be stored in the test images.
04263         # Define 2 local symbols to hold the results.
04264         # Delete the image files in case they are still present.
04265         #a1 = array(1:96, 8,12)
04266         #a2 = a1 + 100
04267         a1 = ia.makearray(0.0,[8,12])
04268         a2 = ia.makearray(0.0,[8,12])
04269         sum = ia.makearray(0.0,[8,12])
04270         num = 1
04271         for j in range(8):
04272             for k in range(12):
04273                 a1[j][k] = num
04274                 a2[j][k] = a1[j][k]+100
04275                 sum[j][k] = a1[j][k]+a2[j][k]
04276                 num = num+1
04277         #local mask, pixels, names
04278         names=""
04279 
04280         # Create 2 images.
04281         # Keep the first one in a global symbol (with a strange name),
04282         # so it can be used in a LEL expression with the $-notation.
04283         imname1 = testdir+'/'+'im.1'
04284         global_iet_im1 = ia.newimagefromarray(imname1, a1)
04285         if not global_iet_im1:
04286             stop('ia.fromarray failed (1)')
04287         imname2 = testdir+'/'+'im.2'
04288         im2 = ia.newimagefromarray(imname2, a2)
04289         if not im2:
04290             ok = global_iet_im1.done()
04291             stop('ia.fromarray failed (2)')
04292         ok = im2.done()
04293         if not ok:
04294             stop('done failed (1)')
04295 
04296         # Form a simple expression and check if the result is correct.
04297         ex = '"'+imname1+'" + "'+imname2+'"'
04298         outf = testdir+'/ex1.1'
04299         global_iet_ex1 = ia.imagecalc(outfile=outf, pixels=ex, overwrite=true)
04300         if not global_iet_ex1:
04301             ok = global_iet_im1.done()
04302             stop('expr failed (1)')
04303         pixels = global_iet_ex1.getchunk()
04304         if not alleq(pixels, sum, tolerance=0.0001):  #sum=a1+a2
04305             ok = global_iet_im1.done()
04306             ok = global_iet_ex1.done()
04307             stop('expr values are wrong (1)')
04308 
04309         # Now form and check an expression using the $-notation.
04310         # The mask should be all true (in fact, there is no mask).
04311         #ex2 = imagecalc(pixels='$global_iet_ex1 - $global_iet_im1')
04312         #$-notation no longer works
04313         ok = global_iet_ex1.done() #need to close before re-opening
04314         ex2 = ia.imagecalc(pixels='"'+outf+'" - "'+imname1+'"')
04315         if not ok:
04316             stop('done failed (2)')
04317         if not ex2:
04318             ok = global_iet_im1.done()
04319             stop('expr failed (2)')
04320         pixels = ex2.getregion()
04321         mask = ex2.getregion(getmask=true)
04322         if len(pixels)==0 or len(mask)==0:
04323             stop('getregion failed (1)')
04324         ok = ex2.done()
04325         if not alleq(pixels,a2,tolerance=0.0001):
04326             ok = global_iet_im1.done()
04327             stop('expr values are wrong (2)')
04328         for j in range(a2.shape[0]):
04329             for k in range(a2.shape[1]):
04330                 if not mask[j][k]:
04331                     ok = global_iet_im1.done()
04332                     stop('expr mask is wrong (1)')
04333 
04334         # Define a region as a global symbol.
04335         # Use it in an expression using the $-notation.
04336         # The mask should be all true (in fact, there is no mask).
04337         #global_iet_reg1 = rg.quarter()
04338         global_iet_reg1 = rg.box(blc=[.25,.25],trc=[.75,.75], frac=true)
04339         #ex3 = imagecalc(pixels='$global_iet_im1[$global_iet_reg1]')
04340         ex3all = ia.imagecalc(pixels='"'+imname1+'"')
04341         if not ex3all:
04342             ok = global_iet_im1.done()
04343             stop('expr failed (3all)')
04344         ex3 = ex3all.subimage(region=global_iet_reg1)
04345         if not ex3:
04346             ok = ex3all.done()
04347             ok = global_iet_im1.done()
04348             stop('expr failed (3)')
04349         ok = ex3all.done()
04350         pixels = ex3.getregion()
04351         mask = ex3.getregion(getmask=true)
04352         ## ex3.maskhandler ("get", names)
04353         ok = ex3.done()
04354         #if not alleq(pixels, a1[3:6,4:9], tolerance=0.0001):
04355         if not alleq(pixels, a1[2:6,3:9], tolerance=0.0001):
04356             ok = global_iet_im1.done()
04357             stop('expr values are wrong (3)')
04358         for j in range(mask.shape[0]):
04359             for k in range(mask.shape[1]):
04360                 if not mask[j][k]:
04361                     ok = global_iet_im1.done()
04362                     stop('expr mask is wrong (2)')
04363         ##    if (len(names) != 0) {
04364         ##      global_iet_im1.done()
04365         ##      fail ("imageexprtest: there is a mask in '$im1[$reg1]'")
04366 
04367         # Close the first image.
04368         # Note that after im4.done te image server might be closed because
04369         # there are no active objects anymore.
04370         imname4 = testdir+'/'+'im.4'
04371         ex = '"'+imname1+'"['+'"'+imname1+'"%2==0]'
04372         im4 = ia.imagecalc (imname4, ex)
04373         if not im4:
04374             stop('imagecalc failed (1)')
04375         pixels = im4.getregion()
04376         mask = im4.getregion(getmask=true)
04377         ok = im4.maskhandler ("get",names)
04378         ok = im4.done()
04379         if not alleq(pixels, a1, tolerance=0.0001):
04380             ok = global_iet_im1.done()
04381             stop('imagecalc values are wrong (1)')
04382         a1mod2 = ia.makearray(0,[a1.shape[0],a1.shape[1]])
04383         for i in range(a1.shape[0]):
04384             for j in range(a1.shape[1]):
04385                 a1mod2[i][j] = (a1[i][j]%2==0)
04386         if not allbooleq(mask,a1mod2):
04387             ok = global_iet_im1.done()
04388             stop('imagecalc mask is wrong (1)')
04389         if (len(names) != 0):
04390             ok = global_iet_im1.done()
04391             stop('imagecalc has too many masks (1)')
04392 
04393         # Move the image to test if its mask table can still be found
04394         # and if the default mask was set.
04395         imname5= testdir+'/'+'im.5'
04396         ia.close()  # close imname4
04397         ok = os.renames(imname4, imname5)
04398         ex = '"'+imname5+'"'
04399         ex3 = ia.imagecalc(pixels=ex)
04400         if not ex3:
04401             ok = global_iet_im1.done()
04402             stop('expr  failed (4)')
04403         pixels = ex3.getregion()
04404         mask = ex3.getregion(getmask=true)
04405         ok = ex3.done()
04406         if not alleq(pixels, a1, tolerance=0.0001):
04407             ok = global_iet_im1.done()
04408             stop ('expr values are wrong (4)')
04409         if not allbooleq(mask,a1mod2):
04410             ok = global_iet_im1.done()
04411             stop('expr mask is wrong (3)')
04412 
04413         # Now issue some incorrect expressions.
04414         ex = '"'+imname1+'"+'+'"im..2"'
04415         try:
04416             note('Expect SEVERE error and Exception here')
04417             ex4 = ia.imagecalc(pixels=ex)
04418         except Exception, e:
04419             note('Caught expected Exception')
04420             ex4 = false
04421         if ex4:
04422             ok = ex4.close()
04423             ok = global_iet_im1.done()
04424             stop('expr unexpectedly did not fail (5)')
04425         ex = '"'+imname2+'" - max("'+imname1+'", "'+imname2+'", "'+imname1+'")'
04426         try:
04427             note('Expect SEVERE error and Exception here')
04428             ex4 = ia.imagecalc(pixels=ex)
04429         except Exception, e:
04430             note('Caught expected Exception')
04431             ex4 = false
04432         if ex4:
04433             ex4.close()
04434             global_iet_im1.done()
04435             stop('expr unexpectedly did not fail (5)')
04436 
04437         # Close last open image.
04438         # Remove the image files created.
04439         # Note that im.4 has been moved into im.1.
04440         ok = global_iet_im1.done()
04441         #ok = dos.remove (imname1, T, F)
04442         #ok = dos.remove (imname2, T, F)
04443         if not cleanup(imname1): fail()
04444         if not cleanup(imname2): fail()
04445 
04446         # Check if we can create im.1 and im.2 again.
04447         # If an image was left open, that will fail.
04448         im1 = ia.newimagefromarray(imname1, a1)
04449         if not im1:
04450             stop ('Image', imname1, ' was still open')
04451         im2 = ia.newimagefromarray(imname2, a2)
04452         if not im2:
04453             ok = im1.done()
04454             stop ('Image', imname2, ' was still open')
04455         ok = im1.done()
04456         ok = im2.done()
04457         #ok = dos.remove (imname1, T, F)
04458         #ok = dos.remove (imname2, T, F)
04459         if not cleanup(imname1): fail()
04460         if not cleanup(imname2): fail()
04461         ###
04462         return cleanup(testdir)
04463 
04464 
04465     def test22():
04466         #
04467         # Test methods
04468         #   statistics
04469         #
04470         info('')
04471         info('')
04472         info('')
04473         info('Test 22 - statistics')
04474         # Make the directory
04475         testdir = 'imagetest_temp'
04476         if not cleanup(testdir):
04477             return False
04478         try:
04479             os.mkdir(testdir)
04480         except IOError, e:
04481             note(e, "SEVERE")
04482             raise RuntimeError, "mkdir " + testdir + " fails!"
04483         # Make image
04484         pixels = ia.makearray(0.0, [10, 20])
04485         pixels[0,0] = -100
04486         pixels[9,19] = 100
04487         imname = testdir+'/'+'ia.fromarray.image'
04488         myim = ia.newimagefromarray(outfile=imname, pixels=pixels)
04489         if not myim:
04490             stop('ia.fromarray constructor 1 failed')
04491         #
04492         try:
04493             note('Expect SEVERE error and Exception here')
04494             ok = myim.statistics(axes=[10,20])
04495         except Exception, e:
04496             note('Caught expected Exception')
04497             ok = false
04498         if ok:
04499             stop('Statistics unexpectedly did not fail (1)')
04500         try:
04501             note('Expect SEVERE error and Exception here')
04502             ok = myim.statistics(includepix=[-100,100], excludepix=[-100,100])
04503         except Exception, e:
04504             note('Caught expected Exception')
04505             ok = false
04506         if ok:
04507             stop('Statistics unexpectedly did not fail (2)')
04508         #
04509         stats = myim.statistics(list=F)
04510         if not stats:
04511             stop('Statistics failed (1)')
04512         ok = stats.has_key('npts') and stats.has_key('sum')
04513         ok = ok and stats.has_key('sumsq')
04514         ok = ok and stats.has_key('min')
04515         ok = ok and stats.has_key('max')
04516         ok = ok and stats.has_key('mean')
04517         ok = ok and stats.has_key('sigma')
04518         ok = ok and stats.has_key('rms')
04519         if not ok:
04520             stop('Statistics record does not have the correct fields')
04521         prod = 1
04522         for i in myim.shape(): prod *= i
04523         ok = stats['npts']==prod and stats['sum']==0.0
04524         ok = ok and stats['sumsq']==2e4
04525         ok = ok and stats['min']==-100.0
04526         ok = ok and stats['max']==100.0
04527         ok = ok and stats['mean']==0.0
04528         if not ok:
04529             stop('Statistics values are wrong (1)')
04530         ##
04531         blc = [0,0]; trc = [4,4]
04532         r1 = rg.box(blc=blc, trc=trc)
04533         stats = myim.statistics(list=F, region=r1)
04534         if not stats:
04535             stop('Statistics failed (2)')
04536         ok = stats['npts']==((trc[0]-blc[0]+1)*(trc[1]-blc[1]+1))
04537         ok = ok and stats['sum']==-100.0
04538         ok = ok and stats['sumsq']==10000.0
04539         ok = ok and stats['min']==-100.0
04540         ok = ok and stats['max']==0.0
04541         ok = ok and stats['mean']==(-100/stats['npts'])
04542         if not ok:
04543             stop('Statistics values are wrong (2)')
04544         ##
04545         stats = myim.statistics(list=F, axes=[0])
04546         if not ok:
04547             stop('Statistics failed (3)')
04548         imshape = myim.shape()
04549         ok = len(stats['npts'])==imshape[1]
04550         ok = ok and len(stats['sum'])==imshape[1]
04551         ok = ok and len(stats['sumsq'])==imshape[1]
04552         ok = ok and len(stats['min'])==imshape[1]
04553         ok = ok and len(stats['max'])==imshape[1]
04554         ok = ok and len(stats['mean'])==imshape[1]
04555         if not ok:
04556             stop('Statistics record fields are wrong length (1)')
04557         ok = alleqnum(stats['npts'],10,tolerance=0.0001)
04558         ok = ok and stats['sum'][0]==-100
04559         ok = ok and stats['sum'][imshape[1]-1]==100
04560         ok = ok and alleqnum(stats['sum'][1:imshape[1]-1],0,tolerance=0.0001)
04561         ok = ok and stats['sumsq'][0]==10000
04562         ok = ok and stats['sumsq'][imshape[1]-1]==10000
04563         ok = ok and alleqnum(stats['sumsq'][1:(imshape[1]-1)],0,tolerance=0.0001)
04564         ok = ok and stats['min'][0]==-100
04565         ok = ok and alleqnum(stats['min'][1:imshape[1]],0,tolerance=0.0001)
04566         ok = ok and stats['max'][imshape[1]-1]==100
04567         ok = ok and alleqnum(stats['max'][0:(imshape[1]-1)],0,tolerance=0.0001)
04568         ok = ok and stats['mean'][0]==-10
04569         ok = ok and stats['mean'][imshape[1]-1]==10
04570         ok = ok and alleqnum(stats['mean'][1:(imshape[1]-1)],0,tolerance=0.0001)
04571         if not ok:
04572             stop('Statistics values are wrong (3)')
04573         ##
04574         stats = myim.statistics(list=F, includepix=[-5,5])
04575         if not stats:
04576             stop('Statistics failed (4)')
04577         prod = 1
04578         for i in imshape: prod *= i
04579         ok = stats['npts']==prod-2
04580         ok = ok and stats['sum']==0.0
04581         ok = ok and stats['sumsq']==0.0
04582         ok = ok and stats['min']==0.0
04583         ok = ok and stats['max']==0.0
04584         ok = ok and stats['mean']==0.0
04585         if not ok:
04586             stop('Statistics values are wrong (4)')
04587         #
04588         stats = myim.statistics(list=F, excludepix=[-5,5])
04589         if not stats:
04590             stop('Statistics failed (4)')
04591         ok = stats['npts']==2 and stats['sum']==0.0
04592         ok = ok and stats['sumsq']==20000.0
04593         ok = ok and stats['min']==-100.0
04594         ok = ok and stats['max']==100.0
04595         ok = ok and stats['mean']==0.0
04596         if not ok:
04597             stop('Statistics values are wrong (5)')
04598         ##
04599         ok = myim.statistics(list=F, disk=T, force=T)
04600         if not ok:
04601             stop('Statistics failed (5)')
04602         ok = myim.statistics(list=F, disk=F, force=T)
04603         if not ok:
04604             stop('Statistics failed (6)')
04605         #
04606         ok = myim.done()
04607         if not ok:
04608             stop('Done failed (1)')
04609 
04610         return cleanup(testdir)
04611 
04612     def test24():
04613         #
04614         # Test methods
04615         #   moments
04616         info('')
04617         info('')
04618         info('')
04619         info('Test 24 - moments')
04620         # Make the directory
04621         testdir = 'imagetest_temp'
04622         if not cleanup(testdir):
04623             return False
04624         try:
04625             os.mkdir(testdir)
04626         except IOError, e:
04627             note(e, "SEVERE")
04628             raise RuntimeError, "mkdir " + testdir + " fails!"
04629         # Make image
04630         imshape = [50,100]
04631         pixels = ia.makearray(0.0, imshape)
04632         imname = testdir+'/'+'ia.fromarray.image'
04633         myim = ia.newimagefromarray(outfile=imname, pixels=pixels)
04634         if not myim:
04635             fail('failed to create test image in test24')
04636         #
04637         try:
04638             note('Expect SEVERE error and Exception here')
04639             ok = myim.moments(axis=0, moments=[22])
04640         except Exception, e:
04641             note('Caught expected Exception')
04642             ok = false
04643         if ok:
04644             stop('moments unexpectedly did not fail (1)')
04645         try:
04646             note('Expect SEVERE error and Exception here')
04647             ok = myim.moments(axis=99)
04648         except Exception, e:
04649             note('Caught expected Exception')
04650             ok = false
04651         if ok:
04652             stop('moments unexpectedly did not fail (2)')
04653         try:
04654             note('Expect SEVERE error and Exception here')
04655             ok = myim.moments(method='doggies')
04656         except Exception, e:
04657             note('Caught expected Exception')
04658             ok = false
04659         if ok:
04660             stop('moments unexpectedly did not fail (3)')
04661         try:
04662             note('Expect SEVERE error and Exception here')
04663             ok = myim.moments(smoothaxes=[9,19])
04664         except Exception, e:
04665             note('Caught expected Exception')
04666             ok = false
04667         if ok:
04668             stop('moments unexpectedly did not fail (4)')
04669         try:
04670             note('Expect SEVERE error and Exception here')
04671             ok = myim.moments(smoothaxes=[9,19], smoothtypes="gauss gauss", smoothwidths=[10,10])
04672         except Exception, e:
04673             note('Caught expected Exception')
04674             ok = false
04675         if ok:
04676             stop('moments unexpectedly did not fail (5)')
04677         try:
04678             note('Expect SEVERE error and Exception here')
04679             ok = myim.moments(smoothaxes=[0,1], smoothtypes="fish gauss", smoothwidths=[10,10])
04680         except Exception, e:
04681             note('Caught expected Exception')
04682             ok = false
04683         if ok:
04684             stop('moments unexpectedly did not fail (6)')
04685         try:
04686             note('Expect SEVERE error and Exception here')
04687             ok = myim.moments(smoothaxes=[0,1], smoothtypes="gauss gauss", smoothwidths=[-100,10])
04688         except Exception, e:
04689             note('Caught expected Exception')
04690             ok = false
04691         if ok:
04692             stop('moments unexpectedly did not fail (7)')
04693         try:
04694             note('Expect SEVERE error and Exception here')
04695             ok = myim.moments(includepix=[-100,100], excludepix=[-100,100])
04696         except Exception, e:
04697             note('Caught expected Exception')
04698             ok = false
04699         if ok:
04700             stop('moments unexpectedly did not fail (8)')
04701         #
04702         base1 = testdir+'/'+'base1'
04703         base2 = testdir+'/'+'base2'
04704         im2 = myim.moments(outfile=base1, axis=0)
04705         if not im2:
04706             fail('failed to get moments')
04707         ok = im2.done()
04708         if not ok: fail('failed to done image')
04709         im2 = myim.moments(outfile=base2, axis=1)
04710         if not im2:
04711             fail('failed to get moments (2)')
04712         ok = im2.done()
04713         if not ok: fail('failed to done image')
04714         #
04715         base3 = testdir+'/'+'base3'
04716         #im2 = myim.moments(outfile=base3, axis=0, moments=[-1,0,1,2,3,5,6,7,8,9,10,11])
04717         im2 = myim.moments(outfile=base3, axis=0,
04718                            moments=range(-1,4)+range(5,12))
04719         if not im2:
04720             fail('failed to get moments (3)')
04721         ok = im2.done()
04722         if not ok: fail('failed to done image')
04723         #
04724         base4 = testdir+'/'+'base4'
04725         pixels = myim.getchunk()
04726         pixels[0,0] = 10
04727         ok = myim.putchunk(pixels)
04728         if not ok: fail('failed to putchunk')
04729         # Average
04730         im2 = myim.moments(outfile=base4, axis=0, moments=[-1],
04731                            smoothaxes=[0,1], smoothtypes="gauss box",
04732                            smoothwidths=[5,10], includepix=[-100,100])
04733         if not im2: fail('failed to get moments (4)')
04734         pixels2 = im2.getchunk()
04735         v = 10.0 / imshape[0]
04736         if abs(pixels2[0]-v)>0.00001:
04737             stop('Moment pixel values are wrong')
04738         #
04739         ok = myim.done()
04740         if not ok: fail('failed done')
04741         ok = im2.done()
04742         if not ok: fail('failed done')
04743         return cleanup(testdir)
04744 
04745     def test25():
04746         #
04747         # Test methods
04748         #   modify and fitcomponents
04749         info('')
04750         info('')
04751         info('')
04752         info('Test 25 - modify, fitcomponents')
04753         # Make the directory
04754         testdir = 'imagetest_temp'
04755         if not cleanup(testdir):
04756             return False
04757         try:
04758             os.mkdir(testdir)
04759         except IOError, e:
04760             note(e, "SEVERE")
04761             raise RuntimeError, "mkdir " + testdir + " fails!"
04762         #
04763         # Make image
04764         #
04765         imname = testdir+'/'+'ia.fromshape.image'
04766         imshape = [128,128,1]
04767         myim = ia.newimagefromshape(imname, imshape)
04768         if not myim:
04769             stop('ia.fromshape constructor 1 failed')
04770         #
04771         # Add units and restoring beam
04772         #
04773         ok = myim.setbrightnessunit('Jy/beam')
04774         if not ok: fail('failed in setbrightnessunit')
04775         ok = myim.setrestoringbeam(major='5arcmin', minor='2.5arcmin',
04776                                    pa='60deg', log=F)
04777         if not ok: fail('failed in setrestoringbeam')
04778         #
04779         # Pretty hard to test properly.  Add model
04780         #
04781         qmaj = '10arcmin'  #qa.quantity(10, 'arcmin')
04782         qmin = '5arcmin'   #qa.quantity(5, 'arcmin')
04783         qpa = '45.0deg'    #qa.quantity(45.0,'deg')
04784         flux = 100.0
04785         cl0 = gaussian(flux, qmaj, qmin, qpa)
04786         if not (myim.modify(cl0.torecord(), subtract=F)):
04787             fail('failed in modify')
04788         stats = myim.statistics(list=F)
04789         if not stats:
04790             fail('failed to get statistics')
04791         diff = abs(stats['flux']-flux)/flux
04792         if (diff > 0.001):
04793             stop('model image 1 has wrong values');
04794         #
04795         # Subtract it again
04796         #
04797         if not myim.modify(cl0.torecord(), subtract=T): fail()
04798         stats = myim.statistics(list=F)
04799         if not stats: fail()
04800         p = myim.getchunk()
04801         if not alleqnum(p,0.0,tolerance=1e-6):
04802             stop('model image 2 has wrong values');
04803         #
04804         # Now add the model for fitting
04805         #
04806         if not myim.modify(cl0.torecord(), subtract=F): fail()
04807         #
04808 
04809         cl1 = myim.fitcomponents(
04810             region=rg.box(blc=[32, 32, 0],
04811             trc=[96, 96, 0])
04812         )
04813         if not cl1:
04814             stop('fitcomponents 1 failed')
04815         if not cl1['converged']:
04816             stop('fitcomponents 1 did not converge')
04817         cl1tool=cltool()
04818         cl1tool.fromrecord(cl1['results'])
04819         if not compareComponentList(cl0,cl1tool):
04820             stop('failed fitcomponents 1')
04821         return cleanup(testdir)
04822 
04823    
04824     def test26():
04825         #
04826         # Test methods
04827         #   fft
04828         info('')
04829         info('')
04830         info('')
04831         info('Test 26 - fft')
04832         # Make the directory
04833         testdir = 'imagetest_temp'
04834         if not cleanup(testdir):
04835             return False
04836         try:
04837             os.mkdir(testdir)
04838         except IOError, e:
04839             note(e, "SEVERE")
04840             raise RuntimeError, "mkdir " + testdir + " fails!"
04841 
04842         # Open test image (has sky coordinates)
04843         aipspath = os.environ.get("CASAPATH").split()[0]
04844         testname = aipspath+'/data/demo/Images/test_image'
04845         testim = ia.newimage(testname)
04846         if not testim:
04847             stop('image constructor failed')
04848         testshape = testim.shape()
04849         if len(testshape)!=3:
04850             stop('testimage has unexpected shaped')
04851 
04852         #
04853         # FFT sky
04854         #
04855         rname = testdir+'/'+'real'
04856         iname = testdir+'/'+'imag'
04857         aname = testdir+'/'+'amp'
04858         pname = testdir+'/'+'phase'
04859         ok = testim.fft(real=rname, imag=iname, phase=pname, amp=aname)
04860         if not ok:
04861             stop('skyfft failed')
04862         #
04863         im1 = ia.newimage(rname)
04864         if not im1:
04865             stop('Failed to open real image (1)')
04866         im2 = ia.newimage(iname)
04867         if not im2:
04868             stop('Failed to open imaginary image (1)')
04869         im3 = ia.newimage(aname)
04870         if not im3:
04871             stop('Failed to open amplitude image (1)')
04872         im4 = ia.newimage(pname)
04873         if not im4:
04874             stop('Failed to open phase image (1)')
04875         #
04876         trc = testim.shape()
04877         trc[2] = 0
04878         a1 = im1.getchunk(trc=trc)
04879         a2 = im2.getchunk(trc=trc)
04880         a3 = im3.getchunk(trc=trc)
04881         a4 = im4.getchunk(trc=trc)
04882         #
04883         #include 'fftserver.g'
04884         #fft = fftserver()
04885         from numpy.fft import fft2
04886         p = testim.getchunk(trc=trc)
04887         #c = fft.realtocomplexfft(p)
04888         c = fft2(p)
04889         b1 = c.real
04890         b2 = c.imag
04891         b3 = abs(c)  # sqrt( real(x)^2 + imag(x)^2 )
04892         note('NEED TO SORT OUT COMPARISON WITH NUMPY.FFT RESULT')
04893         #b4 = arg(c)  # atan( imag(x) / real(x) )
04894         #from numpy import atan2
04895         #b4 = atan2(c.imag , c.real)
04896         ##
04897         ##diff = abs(a1-b1)
04898         #if not alleq(a1,b1,tolerance=1e-6):
04899         #    stop('real values incorrect (1)')
04900         ##diff = abs(a2-b2)
04901         #if not alleq(a2,b2,tolerance=1e-6):
04902         #    stop('imaginary values incorrect (1)')
04903         ##diff = abs(a3-b3)
04904         #if not alleq(a3,b3,tolerance=1e-5):
04905         #    stop('amplitude values incorrect (1)')
04906         ##diff = abs(a4-b4)
04907         #if not alleq(a4,b4,tolerance=1e-6):
04908         #    stop('phase values incorrect (1)')
04909         #
04910         ok =im1.remove(T) and im2.remove(T) and im3.remove(T) and im4.remove(T)
04911         if not ok:
04912             stop('Done 1 failed')
04913         #
04914         # FFT whole image
04915         #
04916         ndim = len(testim.shape())
04917         axes = range(ndim)
04918         ok = testim.fft(real=rname, imag=iname, phase=pname, amp=aname, axes=axes)
04919         if not ok:
04920             stop('whole image fft failed')
04921         #
04922         im1 = ia.newimage(rname)
04923         if not im1:
04924             stop('Failed to open real image (2)')
04925         im2 = ia.newimage(iname)
04926         if not im2:
04927             stop('Failed to open imaginary image (2)')
04928         im3 = ia.newimage(aname)
04929         if not im3:
04930             stop('Failed to open amplitude image (2)')
04931         im4 = ia.newimage(pname)
04932         if not im4:
04933             stop('Failed to open phase image (2)')
04934         #
04935         a1 = im1.getchunk()
04936         a2 = im2.getchunk()
04937         a3 = im3.getchunk()
04938         a4 = im4.getchunk()
04939         #
04940         #include 'fftserver.g'
04941         #fft = fftserver()
04942         p = testim.getchunk()
04943         #c = fft.realtocomplexfft(p)
04944         c = fft2(p)
04945         b1 = c.real
04946         b2 = c.imag
04947         b3 = abs(c)
04948         note('NEED TO SORT OUT COMPARISON WITH NUMPY.FFT RESULT')
04949         #b4 = arg(c)
04950         ##
04951         ##diff = abs(a1-b1)
04952         #if not alleq(a1,b1,tolerance=1e-6):
04953         #    stop('real values incorrect (2)')
04954         #diff = abs(a2-b2)
04955         #if not alleq(a2,b2,tolerance=1e-6):
04956         #    stop('imaginary values incorrect (2)')
04957         #diff = abs(a3-b3)
04958         #if not alleq(a3,b3,tolerance=2e-5):
04959         #    stop('amplitude values incorrect (2)')
04960         #diff = abs(a4-b4)
04961         #if not alleq(a4,b4,tolerance=1e-6):
04962         #    stop('phase values incorrect (2)')
04963         #
04964         ok = testim.done() and im1.done() and im2.done() and im3.done() and im4.done()
04965         if not ok:
04966             stop('Done 2 failed')
04967         #
04968         return cleanup(testdir)
04969 
04970     def test28():
04971         #
04972         # Test methods
04973         #   convolve2d
04974         info('')
04975         info('')
04976         info('')
04977         info('Test 28 - convolve2d')
04978         # Make the directory
04979         testdir = 'imagetest_temp'
04980         if not cleanup(testdir):
04981             return False
04982         try:
04983             os.mkdir(testdir)
04984         except IOError, e:
04985             note(e, "SEVERE")
04986             raise RuntimeError, "mkdir " + testdir + " fails!"
04987         # Make sky image
04988         nx = 128
04989         ny = 128
04990         imshape = [nx,ny]
04991         centre = [imshape[0]/2,imshape[1]/2]
04992         myim = ia.newimagefromshape(shape=imshape)
04993         if not myim: stop('ia.fromshape constructor 1 failed')
04994         mycs = myim.coordsys()
04995         #mycs.setincrement(value="-1arcsec 1arcsec")
04996         mycs.setincrement(value=["-1arcsec","1arcsec"])
04997         ok = myim.setcoordsys(mycs.torecord())
04998         if not ok: stop ('Failed to set coordsys 1')
04999         mycs.done()
05000         #
05001         # These tests don't test the pixel values, just units and interface
05002         # Whack a gaussian in and set restoring beam to its shape
05003         #
05004         gausspixels = gaussianarray (nx, ny, 1.0, 20.0, 10.0, 0.0)
05005         ok = myim.putchunk(gausspixels)
05006         if not ok: stop('putchunk 1 failed')
05007         ok = myim.setrestoringbeam(major='20arcsec', minor='10arcsec',
05008                                    pa='0.0deg', log=F)
05009         if not ok: stop('setrestoringbeam 1 failed')
05010         ok = myim.setbrightnessunit('Jy/beam')
05011         if not ok: stop('setbrightnessunits 1 failed')
05012         #
05013         # First test a Jy/beam convolution
05014         #
05015         #r = rg.quarter()
05016         r = rg.box(blc=[.25,.25],trc=[.75,.75],frac=true)
05017         myim2 = myim.convolve2d(major='20arcsec', minor='10arcsec', pa='0deg')
05018         if not myim2: stop('convolve2d 1 failed')
05019         bUnit = myim2.brightnessunit()
05020         if (bUnit!='Jy/beam'): stop ('convolve2d 1 set wrong brightness unit')
05021         major = math.sqrt(400 + 400)
05022         minor = math.sqrt(100 + 100)
05023         rb = myim2.restoringbeam()
05024         d1 = abs(rb['major']['value'] - major)
05025         d2 = abs(rb['minor']['value'] - minor)
05026         d3 = abs(rb['positionangle']['value'] - 0.0)
05027         if (d3 > 1e-5): d3 = abs(rb['positionangle']['value'] - 180.0)
05028         if (d1 >1e-5 or d2>1e-5 or d3>1e-5):
05029             stop ('convolve2d 1 set wrong restoring beam')
05030         if not myim2.done(): stop ('done 1 failed')
05031         #
05032         # Now set values in pixels (increment=1arcsec)
05033         #
05034         ok = myim.putchunk(gausspixels)
05035         if not ok: stop('putchunk 2 failed')
05036         ok = myim.setrestoringbeam(major='20arcsec', minor='10arcsec',
05037                                    pa='0.0deg', log=F)
05038         if not ok: stop('setrestoringbeam 2 failed')
05039         ok = myim.setbrightnessunit('Jy/beam')
05040         if not ok: stop('setbrightnessunits 2 failed')
05041         #
05042         #myim2 = myim.convolve2d (major=20, minor=10, pa=0, region=r)
05043         myim2 = myim.convolve2d (major='20arcsec', minor='10arcsec', pa='0deg',
05044                                  region=r)
05045         if not myim2: stop('convolve2d 2 failed')
05046         bUnit = myim2.brightnessunit()
05047         if (bUnit!='Jy/beam'): stop ('convolve2d 2 set wrong brightness unit')
05048         major = math.sqrt(20*20 + 20*20)
05049         minor = math.sqrt(10*10 + 10*10)
05050         rb = myim2.restoringbeam()
05051         d1 = abs(rb['major']['value'] - major)
05052         d2 = abs(rb['minor']['value'] - minor)
05053         d3 = abs(rb['positionangle']['value'] - 0.0)
05054         if (d3 > 1e-5): d3 = abs(rb['positionangle']['value'] - 180.0)
05055         if (d1 >1e-5 or d2>1e-5 or d3>1e-5):
05056             stop ('convolve2d 2 set wrong restoring beam')
05057         if not myim2.done(): stop ('done 2 failed')
05058         #
05059         # Now test a Jy/pixel convolution
05060         #
05061         ok = myim.set(0.0)
05062         if not ok: stop ('set 1 failed')
05063         pixels = myim.getchunk()
05064         if len(pixels)==0: stop ('getchunk 1 failed')
05065         pixels[nx/2,ny/2] = 1.0
05066         ok = myim.putchunk(pixels)
05067         if not ok: stop ('putchunk 3 failed')
05068         ok = myim.setrestoringbeam(remove=T, log=F)
05069         if not ok: stop('setrestoringbeam 3 failed')
05070         ok = myim.setbrightnessunit('Jy/pixel')
05071         if not ok: stop('setbrightnessunits 3 failed')
05072         #
05073         myim2 = myim.convolve2d (major='20arcsec', minor='10arcsec',
05074                                  pa='20deg', region=r)
05075         if not myim2: stop('convolve2d 3 failed')
05076         bUnit = myim2.brightnessunit()
05077         if (bUnit!='Jy/beam'): stop ('convolve2d 3 set wrong brightness unit')
05078         major = 20
05079         minor = 10
05080         rb = myim2.restoringbeam()
05081         d1 = abs(rb['major']['value'] - major)
05082         d2 = abs(rb['minor']['value'] - minor)
05083         q = qa.convert(rb['positionangle'],'deg')
05084         if not q: fail('failed convert')
05085         d3 = abs(qa.getvalue(q) - 20.0)
05086         if (d1 >1e-5 or d2>1e-5 or d3>1e-5):
05087             stop ('convolve2d 3 set wrong restoring beam')
05088         if not myim2.done(): stop ('done 3 failed')
05089         #
05090         # Now test axes other than the sky
05091         #
05092         mycs = cs.newcoordsys(linear=2)
05093         ok = mycs.setunits(value=["km","km"], overwrite=T)
05094         if not ok: fail('failed setunits')
05095         ok = myim.setcoordsys(mycs.torecord())
05096         if not ok: stop ('Failed to set coordsys 2')
05097         mycs.done()
05098         ok = myim.set(0.0)
05099         if not ok: stop ('set 2 failed')
05100         pixels = myim.getchunk()
05101         if len(pixels)==0: stop ('getchunk 2 failed')
05102         pixels[nx/2,ny/2] = 1.0
05103         ok = myim.putchunk(pixels)
05104         if not ok: stop ('putchunk 4 failed')
05105         ok = myim.setrestoringbeam(remove=T, log=F)
05106         if not ok: stop('setrestoringbeam 3 failed')
05107         ok = myim.setbrightnessunit('kg')
05108         if not ok: stop('setbrightnessunits 4 failed')
05109         #
05110         myim2 = myim.convolve2d(major='20km', minor='10km',
05111                                 pa='20deg', region=r)
05112         if not myim2: stop('convolve2d 4 failed')
05113         if not myim2.done(): stop ('done 4 failed')
05114         if not myim.done(): stop('done 5 failed')
05115         #
05116         # Now try a mixed axis convolution
05117         #
05118         mycs = cs.newcoordsys(direction=T, linear=1)
05119         nz = 32
05120         imshape = [nx,ny,nz]
05121         centre = [imshape[0]/2,imshape[1]/2,imshape[2]/2]
05122         myim = ia.newimagefromshape(shape=imshape, csys=mycs.torecord())
05123         if not myim: stop('ia.fromshape constructor 2 failed')
05124         if not mycs.done(): stop ('done 6 failed')
05125         #
05126         #myim2 = myim.convolve2d (major=20, minor=10, axes=[1,3])
05127         note('EXPECT WARNING MESSAGE HERE')
05128         myim2 = myim.convolve2d (major='20pix', minor='10pix', axes=[0,2])
05129         if not myim2: stop('convolve2d 5 failed')
05130         if not myim2.done(): stop ('done 7 failed')
05131         if not myim.done(): stop('done 8 failed')
05132         #
05133         # Now do some non autoscaling
05134         #
05135         imshape = [nx,ny]
05136         centre = [imshape[0]/2,imshape[1]/2]
05137         myim = ia.newimagefromshape(shape=imshape)
05138         if not myim: stop('ia.fromshape constructor 3 failed')
05139         mycs = myim.coordsys()
05140         #mycs.setincrement(value="-1arcsec 1arcsec")
05141         mycs.setincrement(value=["-1arcsec","1arcsec"])
05142         ok = myim.setcoordsys(mycs.torecord())
05143         if not ok: stop ('Failed to set coordsys 3')
05144         if not mycs.done(): stop('done 10 failed')
05145         #
05146         pixels = myim.getchunk()
05147         if len(pixels)==0: stop ('getchunk 3 failed')
05148         pixels[nx/2,ny/2] = 1.0
05149         ok = myim.putchunk(pixels)
05150         if not ok: stop ('putchunk 5 failed')
05151         ok = myim.setbrightnessunit('Jy/pixel')
05152         if not ok: stop('setbrightnessunits 5 failed')
05153         #
05154         # Convolution kernel has peak 1.0*scale
05155         #
05156         myim2 = myim.convolve2d (scale=2.0, major='20arcsec', minor='10arcsec', pa="0deg")
05157         if not myim2: stop('convolve2d 6 failed')
05158         stats = myim2.statistics(list=F)
05159         if not stats: fail('failed to get statistics')
05160         maxVal = stats['max']
05161         d1 = abs(maxVal - 2.0)
05162         if (d1>1e-5): stop ('convolve2d 6 got scaling wrong')
05163         if not myim2.done(): stop ('done 11 failed')
05164         if not myim.done(): stop('done 12 failed')
05165         #
05166         # Now some forced errors
05167         #
05168         imshape = [nx,ny,nz]
05169         centre = [imshape[0]/2,imshape[1]/2,imshape[2]/2]
05170         myim = ia.newimagefromshape(shape=imshape)
05171         if not myim: stop('ia.fromshape constructor 4 failed')
05172         #
05173         try:
05174             note('Expect SEVERE error and Exception here')
05175             myim2 = myim.convolve2d (major='1km', minor='20arcsec', axes=[0,1])
05176         except Exception, e:
05177             note('Caught expected Exception')
05178             myim2 = false
05179         if myim2: stop ('Forced failure 1 did not occur')
05180         try:
05181             note('Expect SEVERE error and Exception here')
05182             myim2 = myim.convolve2d (major='10arcsec', minor='10Hz', axes=[0,2])
05183         except Exception, e:
05184             note('Caught expected Exception')
05185             myim2 = false
05186         if myim2: stop ('Forced failure 2 did not occur')
05187         try:
05188             note('Expect SEVERE error and Exception here')
05189             myim2 = myim.convolve2d (major='10pix', minor='10arcsec', axes=[0,1])
05190         except Exception, e:
05191             note('Caught expected Exception')
05192             myim2 = false
05193         if myim2: stop ('Forced failure 3 did not occur')
05194         if not myim.done(): stop('done 14 failed')
05195         ###
05196         return cleanup(testdir)
05197 
05198     def test29():
05199         #
05200         # Test methods
05201         #   deconvolvecomponentlist
05202         #
05203         info('')
05204         info('')
05205         info('')
05206         info('Test 29 - deconvolvecomponentlist')
05207         # Make the directory
05208         testdir = 'imagetest_temp'
05209         if not cleanup(testdir):
05210             return False
05211         try:
05212             os.mkdir(testdir)
05213         except IOError, e:
05214             note(e, "SEVERE")
05215             raise RuntimeError, "mkdir " + testdir + " fails!"
05216         # Make sky image
05217         nx = 128
05218         ny = 128
05219         imshape = [nx,ny]
05220         centre = [imshape[0]/2,imshape[1]/2]
05221         myim = ia.newimagefromshape(shape=imshape)
05222         if not myim: stop('ia.fromshape constructor 1 failed')
05223         ok = myim.summary()
05224         #
05225         ok = deconvolveTest (myim, 20.0, 10.0, 0.0, 1)
05226         if not ok: fail('failed deconvolveTest')
05227         #
05228         ok = deconvolveTest (myim, 20.0, 10.0, 45.0, 2)
05229         if not ok: fail('failed deconvolveTest 2')
05230         #
05231         ok = deconvolveTest (myim, 20.0, 10.0, -20.0, 3)
05232         if not ok: fail('failed deconvolveTest 3')
05233         #
05234         if not myim.done(): stop ('done 1 failed')
05235         ###
05236         return cleanup(testdir)
05237 
05238     def test30():
05239         #
05240         # Test methods
05241         #   findsources, maxfit
05242         #
05243         info('')
05244         info('')
05245         info('')
05246         info('Test 30 - findsources, maxfit')
05247         #
05248         # Make image
05249         #
05250         imshape = [128,128,1]
05251         myim = ia.newimagefromshape(shape=imshape)
05252         if not myim:
05253             stop('ia.fromshape constructor 1 failed')
05254         #
05255         # Add units and restoring beam
05256         #
05257         ok = myim.setbrightnessunit('Jy/beam')
05258         if not ok: fail()
05259         #
05260         qmaj = qa.quantity('5.00000000001 arcmin')
05261         qmin = qa.quantity('5.0 arcmin')
05262         qpa = qa.quantity('0.0 deg')
05263         ok = myim.setrestoringbeam(major=qmaj, minor=qmin, pa=qpa, log=F)
05264         if not ok: fail()
05265         #
05266         # Add four gaussians
05267         #
05268         mycs = myim.coordsys()
05269         if not mycs: fail()
05270         #
05271         rp = mycs.referencepixel()['numeric']
05272         p1 = [-30.0,-30.0,0.0] + rp
05273         d1 = mycs.toworld(p1, 'm')['measure']['direction']
05274         if not d1: fail()
05275         #
05276         p2 = [-30.0, 30.0,0.0] + rp
05277         d2 = mycs.toworld(p2, 'm')['measure']['direction']
05278         if not d2: fail()
05279         #
05280         p3 = [ 30.0, 30.0,0.0] + rp
05281         d3 = mycs.toworld(p3, 'm')['measure']['direction']
05282         if not d3: fail()
05283         #
05284         p4 = [ 30.0, -30.0,0.0] + rp
05285         d4 = mycs.toworld(p4, 'm')['measure']['direction']
05286         if not d4: fail()
05287         #
05288         f1 = 100.0
05289         cl1 = gaussian(f1, qmaj, qmin, qpa, dir=d1)
05290         if not cl1: fail()
05291         cl1Point = cltool()
05292         cl1Point.simulate(1)
05293         ok = cl1Point.setflux(0, cl1.getfluxvalue(0))
05294         if not ok: fail()
05295         ok = cl1Point.setshape(0, 'point', log=F)
05296         if not ok: fail()
05297         rd = cl1.getrefdir(0)
05298         ok = cl1Point.setrefdir(0, me.getvalue(rd)['m0'],
05299                                 me.getvalue(rd)['m1'], log=F)
05300         if not ok: fail()
05301         #
05302         f2 = 80.0
05303         cl2 = gaussian(f2, qmaj, qmin, qpa, dir=d2)
05304         if not cl2: fail()
05305         #
05306         f3 = 60.0
05307         cl3 = gaussian(f3, qmaj, qmin, qpa, dir=d3)
05308         if not cl3: fail()
05309         #
05310         f4 = 40.0
05311         cl4 = gaussian(f4, qmaj, qmin, qpa, dir=d4)
05312         if not cl4: fail()
05313         #
05314         clIn = cltool()
05315         clIn.concatenate(cl1.torecord(), log=F)
05316         clIn.concatenate(cl2.torecord(), log=F)
05317         clIn.concatenate(cl3.torecord(), log=F)
05318         clIn.concatenate(cl4.torecord(), log=F)
05319         cl1.done()
05320         cl2.done()
05321         cl3.done()
05322         cl4.done()
05323         #
05324         if not myim.modify(clIn.torecord(), subtract=F): fail()
05325 
05326         # Now find them
05327         clOut = myim.findsources(10, cutoff=0.3)
05328         if not clOut: fail()
05329         clOuttool = cltool()
05330         clOuttool.fromrecord(clOut);
05331         if not compareComponentList(clIn,clOuttool,dotype=F):
05332             stop('failed findsources 1')
05333         if not clOuttool.done(): fail()
05334         #
05335         # Now try and find just first 3 sources
05336         #
05337         clOut = myim.findsources(10, cutoff=0.5)
05338         if not clOut: fail()
05339         clOuttool = cltool()
05340         clOuttool.fromrecord(clOut)
05341         clIn2 = cltool()
05342         clIn2.concatenate (clIn.torecord(), [0,1,2], log=F)
05343         if not compareComponentList(clIn2,clOuttool,dotype=F):
05344             stop('failed findsources 2')
05345         #
05346         if not clIn.done(): fail()
05347         if not clIn2.done(): fail()
05348         if not clOuttool.done(): fail()
05349 
05350         # Maxfit
05351         clOut = myim.maxfit()
05352         if not clOut: fail()
05353         clOuttool = cltool()
05354         clOuttool.fromrecord(clOut)
05355         if not compareComponentList(cl1Point,clOuttool,dotype=F):
05356             stop('failed maxfit')
05357         if not cl1Point.done(): fail()
05358         if not clOuttool.done(): fail()
05359         #
05360         ok = myim.done()
05361         if not ok:
05362             stop('Done failed (1)')
05363         ok = cs.done()
05364         if not ok:
05365             stop('Done failed (2)')
05366         #
05367         return True
05368 
05369     def test32():
05370         #
05371         # Test methods
05372         #   addnoise
05373         #
05374         info('')
05375         info('')
05376         info('')
05377         info('Test 32 - addnoise')
05378         #
05379         # Make tempimage
05380         #
05381         imshape = [512,512]
05382         myim = ia.newimagefromshape(shape=imshape)
05383         if not myim:
05384             stop('ia.fromshape constructor 1 failed')
05385         n = imshape[0]*imshape[1]
05386         # Add noisesesesese
05387         n1 = "binomial discreteuniform erlang geometric hypergeometric "
05388         n2 = "normal lognormal negativeexponential poisson uniform weibull"
05389         noises = (n1 + n2).split()
05390         #
05391         rec = {}
05392         rec['binomial'] = {}
05393         rec['binomial']['pars'] = [1, 0.5]
05394         #
05395         rec['discreteuniform'] = {}
05396         rec['discreteuniform']['pars'] = [-100, 100]
05397         rec['discreteuniform']['mean'] = 0.5 * (rec['discreteuniform']['pars'][1] + rec['discreteuniform']['pars'][0])
05398         #
05399         rec['erlang'] = {}
05400         rec['erlang']['pars'] = [1,1]
05401         rec['erlang']['mean'] = rec['erlang']['pars'][0]
05402         rec['erlang']['var'] = rec['erlang']['pars'][1]
05403         #
05404         rec['geometric'] = {}
05405         rec['geometric']['pars'] = [0.5]
05406         rec['geometric']['mean'] = rec['geometric']['pars'][0]
05407         #
05408         rec['hypergeometric'] = {}
05409         rec['hypergeometric']['pars'] = [0.5, 0.5]
05410         rec['hypergeometric']['mean'] = rec['hypergeometric']['pars'][0]
05411         rec['hypergeometric']['var'] = rec['hypergeometric']['pars'][1]
05412         #
05413         rec['normal'] = {}
05414         rec['normal']['pars'] = [0, 1]
05415         rec['normal']['mean'] = rec['normal']['pars'][0]
05416         rec['normal']['var'] = rec['normal']['pars'][1]
05417         #
05418         rec['lognormal'] = {}
05419         rec['lognormal']['pars'] = [1, 1]
05420         rec['lognormal']['mean'] = rec['lognormal']['pars'][0]
05421         rec['lognormal']['var'] = rec['lognormal']['pars'][1]
05422         #
05423         rec['negativeexponential'] = {}
05424         rec['negativeexponential']['pars'] = [1]
05425         rec['negativeexponential']['mean'] = rec['negativeexponential']['pars'][0]
05426         #
05427         rec['poisson'] = {}
05428         rec['poisson']['pars'] = [1]
05429         rec['poisson']['mean'] = rec['poisson']['pars'][0]
05430         #
05431         rec['uniform'] = {}
05432         rec['uniform']['pars'] = [-1, 1]
05433         rec['uniform']['mean'] = 0.5 * (rec['uniform']['pars'][1] + rec['uniform']['pars'][0])
05434         #
05435         rec['weibull'] = {}
05436         rec['weibull']['pars'] = [0.5, 1]
05437         #
05438         for n in noises:
05439             ok = myim.addnoise(zero=T, type=n, pars=rec[n]['pars'])
05440             if not ok: fail()
05441             #
05442             stats = myim.statistics (list=F)
05443             if not stats: fail()
05444             errMean = stats['sigma'] / math.sqrt(stats['npts'])
05445             sig = stats['sigma']
05446             #
05447             if rec[n].has_key('mean'):
05448                 d = abs(stats['mean'] - rec[n]['mean'])
05449                 if (d > errMean):
05450                     #fail('Mean wrong for distribution ' + n)
05451                     #note('MEAN WRONG FOR DISTRIBUTION ' + n)
05452                     #print "d=", d, "errMean=", errMean
05453                     pass
05454             #
05455             if rec[n].has_key('var'):
05456                 d = abs(sig*sig - rec[n]['var'])
05457                 #if (d > errMean):    # What is the error in the variance ???
05458                 #    #fail('Variance wrong for distribution '+ n)
05459                 #    note('VARIANCE WRONG FOR DISTRIBUTION '+ n)
05460                 #    print "d=", d, "errMean=", errMean
05461                 pass
05462             #
05463         if not myim.done(): fail()
05464         return True
05465 
05466     def test33():
05467         info('')
05468         info('')
05469         info('')
05470         info('Test 33 - {set}miscinfo, {set}history, {set}brightnessunit')
05471         info('        - {set}restoringbeam, convertflux')
05472         info('           with many Image types')
05473         # Make the directory
05474         testdir = 'imagetest_temp'
05475         if not cleanup(testdir):
05476             return False
05477         try:
05478             os.mkdir(testdir)
05479         except IOError, e:
05480             note(e, "SEVERE")
05481             raise RuntimeError, "mkdir " + testdir + " fails!"
05482         #
05483         # Make images of all the wondrous flavours that we have
05484         #
05485         root = testdir+'/'+'testimage'
05486         imshape = [10,10]
05487         rec = makeAllImageTypes(imshape, root)
05488         #
05489         mii = {}
05490         mii['x'] = 'x'
05491         mii['y'] = 'y'
05492         #
05493         bui = 'Jy/beam'
05494         hii = "I like doggies"
05495         #
05496         rbi = {}
05497         rbi['major'] = qa.quantity('10arcsec')
05498         rbi['minor'] = qa.quantity('5arcsec')
05499         rbi['positionangle'] = qa.quantity('30deg')
05500         names = rec.keys()
05501         for mytype in names:
05502             info('Testing Image type '+rec[mytype]['type'])
05503             #
05504             myim = rec[mytype]['tool']
05505             ok = myim.sethistory(history=hii)
05506             if not ok: fail()
05507             hio = myim.history(list=F, browse=F)
05508             if not hio: fail()
05509             if (len(hii)!=len(hio[0])):
05510                 fail('History length does not reflect')
05511             for i in range(len(hii)):
05512                 if (hii[i]!=hio[0][i]):
05513                     fail('History fields do not reflect')
05514             #
05515             ok = myim.setmiscinfo(mii)
05516             if not ok: fail()
05517             mio = myim.miscinfo()
05518             if not mio: fail()
05519             for f in mii.keys():
05520                 if mio.has_key(f):
05521                     if (mii[f] != mio[f]):
05522                         fail('miscinfo field values do not reflect')
05523                 else:
05524                     fail('miscinfo fields  do not reflect')
05525             #
05526             ok = myim.setrestoringbeam(beam=rbi, log=F)
05527             if not ok: fail()
05528             rbo = myim.restoringbeam();
05529             if not rbo: fail()
05530             for f in rbi.keys():
05531                 if rbo.has_key(f):
05532                     if (qa.getvalue(rbi[f]) != qa.getvalue(rbo[f])):
05533                         fail('restoring beam values do not reflect')
05534                     if (qa.getunit(rbi[f]) != qa.getunit(rbo[f])):
05535                         fail('restoring beam units do not reflect')
05536                 else:
05537                     fail('restoring beam fields do not reflect')
05538             #
05539             ok = myim.setbrightnessunit(bui)
05540             if not ok: fail()
05541             buo = myim.brightnessunit();
05542             if not buo: fail()
05543             if (bui != buo):
05544                 fail('brightness units do not reflect')
05545             # Test convert flux.
05546             ok = myim.setrestoringbeam(beam=rbi, log=F)
05547             if not ok: fail()
05548             ok = myim.setbrightnessunit('Jy/beam')
05549             if not ok: fail()
05550             # First a point source
05551             for mytype in ["gauss","disk"]:
05552                 peakFlux = qa.quantity('1.0 mJy/beam')
05553                 major = rbi['major']
05554                 minor = rbi['minor']
05555                 integralFlux = myim.convertflux(value=peakFlux, major=major,
05556                                                 minor=minor, topeak=F,
05557                                                 type=mytype)
05558                 if not integralFlux: fail()
05559                 peakFlux2 = myim.convertflux(value=integralFlux, major=major,
05560                                              minor=minor, topeak=T, type=mytype)
05561                 if not peakFlux2: fail()
05562                 #
05563                 d = abs(qa.getvalue(peakFlux)) - abs(1000.0*qa.getvalue(integralFlux))
05564                 if (d > 1e-5):
05565                     fail('Point source flux conversion reflection 1 failed')
05566                 d = abs(qa.getvalue(peakFlux)) - abs(1000.0*qa.getvalue(peakFlux2))
05567                 if (d > 1e-5):
05568                     fail('Point source flux conversion reflection 2 failed')
05569                 # Now an extended source
05570                 peakFlux = qa.quantity('1.0 mJy/beam')
05571                 major = qa.quantity("30arcsec")
05572                 minor = qa.quantity("20arcsec")
05573                 integralFlux = myim.convertflux(value=peakFlux, major=major,
05574                                                 minor=minor, topeak=F, type=mytype)
05575                 if not integralFlux: fail()
05576                 peakFlux2 = myim.convertflux(value=integralFlux, major=major,
05577                                              minor=minor, topeak=T)
05578                 if not peakFlux2: fail()
05579                 #
05580                 d = abs(qa.getvalue(peakFlux)) - abs(1000.0*qa.getvalue(integralFlux))
05581                 if (d > 1e-5):
05582                     fail('Extended source flux conversion reflection 1 failed')
05583                 d = abs(qa.getvalue(peakFlux)) - abs(1000.0*qa.getvalue(peakFlux2))
05584                 if (d > 1e-5):
05585                     fail('Extended source flux conversion reflection 2 failed')
05586             #
05587         ok = doneAllImageTypes(rec)
05588         if not ok: fail()
05589         #
05590         return cleanup(testdir)
05591            
05592     def test34():
05593         info('')
05594         info('')
05595         info('')
05596         info('Test 34 - ia.fromascii constructor and toascii')
05597         # Make the directory
05598         testdir = 'imagetest_temp'
05599         if not cleanup(testdir):
05600             return False
05601         try:
05602             os.mkdir(testdir)
05603         except IOError, e:
05604             note(e, "SEVERE")
05605             raise RuntimeError, "mkdir " + testdir + " fails!"
05606         #
05607         info('Testing toascii')
05608         info('')
05609         shape = [2,4,6]
05610         pixels = ia.makearray(0,shape)
05611         num = 0
05612         for i in range(shape[0]):
05613             for j in range(shape[1]):
05614                 for k in range(shape[2]):
05615                     num = num+1
05616                     pixels[i][j][k]=num
05617         #
05618         imname = testdir+'/'+'ia.fromarray.image'
05619         myim = ia.newimagefromarray(pixels=pixels)
05620         if not myim: fail()
05621         #
05622         filename = testdir+'/'+'ia.fromarray.ascii'
05623         ok = myim.toASCII(outfile=filename)
05624         if not ok: fail()
05625         #
05626         info('Testing ia.fromascii')
05627         info('')
05628         #myim2 = ia.fromascii(infile=filename, shape=shape)
05629         #if not myim2: fail()
05630         ok = ia.fromascii(infile=filename, shape=shape)
05631         if not ok: fail()
05632         #pixels2 = myim2.getchunk()
05633         pixels2 = ia.getchunk()
05634         if len(pixels2)==0: fail()
05635         #
05636         if not alleq(pixels,pixels2,tolerance=0.0001):
05637             stop('ia.fromascii reflection failed')
05638         #
05639         if not myim.done(): fail()
05640         #if not myim2.done(): fail()
05641         if not ia.close(): fail()
05642         ###
05643         return cleanup(testdir)
05644 
05645     def test36():
05646         #
05647         # Test methods
05648         #   twopointcorrelation
05649         #
05650         # Not very extensive
05651         #
05652         info('')
05653         info('')
05654         info('')
05655         info('Test 36 - twopointcorrelation')
05656         # Make RA/DEC/Spectral image
05657         imshape = [5,10,20]
05658         myim = ia.newimagefromshape(shape=imshape)
05659         if not myim:
05660             stop('ia.fromshape constructor 1 failed')
05661         if not myim.set(1.0): fail()
05662         #
05663         # Forced failures
05664         #
05665         try:
05666             myim2 = true
05667             note('Expect SEVERE error and Exception here')
05668             myim2 = myim.twopointcorrelation(axes=[20])
05669         except Exception, e:
05670             note('Caught expected Exception: '+str(e))
05671             myim2 = false
05672         if myim2: stop('twopointcorrelation 1 unexpectedly did not fail')
05673         try:
05674             myim2 = true
05675             note('Expect SEVERE error and Exception here')
05676             myim2 = myim.twopointcorrelation(method='fish')
05677         except Exception, e:
05678             note('Caught expected Exception:'+str(e))
05679             myim2 = false
05680         if myim2: stop('twopointcorrelation 2 unexpectedly did not fail')
05681         try:
05682             myim2 = true
05683             note('Expect SEVERE error and Exception here')
05684             myim2 = myim.twopointcorrelation(region='fish')
05685         except Exception, e:
05686             note('Caught expected Exception: '+str(e))
05687             myim2 = false
05688         if myim2: stop('twopointcorrelation 3 unexpectedly did not fail')
05689         try:
05690             myim2 = true
05691             note('Expect SEVERE error and Exception here')
05692             myim2 = myim.twopointcorrelation(mask='fish')
05693         except Exception, e:
05694             note('Caught expected Exception: '+str(e))
05695             myim2 = false
05696         if myim2: stop('twopointcorrelation 4 unexpectedly did not fail')
05697         #
05698         # Some simple tests.  Doing it in Glish is way too slow, so
05699         # just run tests, no value validation
05700         #
05701         myim2 = myim.twopointcorrelation()
05702         if not myim2:
05703             stop('twopointcorrelation 5 failed')
05704         # twopointcorrelation now returns boolean rather than new image
05705         #ok = myim2.done()
05706         #if not ok: fail()
05707         #
05708         myim2 = myim.twopointcorrelation(axes=[0,1])
05709         if not myim2:
05710             stop('twopointcorrelation 6 failed')
05711         #ok = myim2.done()
05712         #if not ok: fail()
05713         #
05714         ok = myim.done()
05715         if not ok: fail()
05716         # Make another image only with Linear coordinates
05717         imshape = [5,10,20]
05718         myim = ia.newimagefromshape(shape=imshape, linear=T)
05719         if not myim:
05720             stop('ia.fromshape constructor 1 failed')
05721         #
05722         myim2 = myim.twopointcorrelation(axes=[0,2])
05723         if not myim2:
05724             stop('twopointcorrelation 7 failed')
05725         #ok = myim2.done()
05726         #if not ok: fail()
05727         #
05728         myim2 = myim.twopointcorrelation(axes=[1,2])
05729         if not myim2:
05730             stop('twopointcorrelation 8 failed')
05731         #
05732         #ok = myim2.done()
05733         #if not ok: fail()
05734         #
05735         ok = myim.done()
05736         if not ok: fail()
05737         #
05738         return True
05739 
05740     def test37():
05741         #
05742         # Test methods
05743         #   continuumsub
05744         #
05745         # Not very extensive.  Remove this when this function goes elsewhere.
05746         #
05747         info('')
05748         info('')
05749         info('')
05750         info('Test 37 - continuumsub')
05751         # Make the directory
05752         testdir = 'imagetest_temp'
05753         if not cleanup(testdir):
05754             return False
05755         try:
05756             os.mkdir(testdir)
05757         except IOError, e:
05758             note(e, "SEVERE")
05759             raise RuntimeError, "mkdir " + testdir + " fails!"
05760         lineOut = testdir + '/line.im'
05761         contOut = testdir + '/cont.im'
05762 
05763         # Make image with Stokes and Spectral axis
05764 
05765         mycs = cs.newcoordsys(spectral=T, stokes='I')
05766         if not mycs: fail()
05767         #
05768         d = ia.makearray(0,[1,100])
05769         for i in range(d.size): d[0][i]=i+1
05770         myim = ia.newimagefromarray(pixels=d, csys=mycs.torecord())
05771         if not myim:
05772             stop('ia.fromarray constructor 1 failed')
05773         if not mycs.done(): fail()
05774         #
05775         # Forced failures
05776         #
05777         try:
05778             myim2 = true
05779             note('Expect SEVERE error and Exception here')
05780             myim2 = myim.continuumsub(lineOut, contOut, region='fish',
05781                                       overwrite=T)
05782         except Exception, e:
05783             note('Caught expected Exception: '+str(e) )
05784             myim2 = false
05785         if myim2:
05786             stop('continuumsub 1 unexpectedly did not fail')
05787         try:
05788             myim2 = true
05789             note('Expect SEVERE error and Exception here')
05790             #myim2 = myim.continuumsub(lineOut, contOut, channels='rats',
05791             #                          overwrite=T)
05792             myim2 = myim.continuumsub(lineOut, contOut, channels=[-99],
05793                                       overwrite=T)
05794         except Exception, e:
05795             note('Caught expected Exception: '+str(e))
05796             myim2 = false
05797         if myim2:
05798             stop('continuumsub 2 unexpectedly did not fail')
05799         try:
05800             myim2 = true
05801             note('Expect SEVERE error and Exception here')
05802             #myim2 = myim.continuumsub(lineOut, contOut, pol='DOGGIES',
05803             #                          overwrite=T)
05804             myim2 = myim.continuumsub(lineOut, contOut, pol='??',
05805                                       overwrite=T)
05806         except Exception, e:
05807             note('Caught expected Exception: '+str(e))
05808             myim2 = false
05809         if myim2:
05810             stop('continuumsub 3 unexpectedly did not fail')
05811         try:
05812             myim2 = true
05813             note('Expect SEVERE error and Exception here')
05814             myim2 = myim.continuumsub(lineOut, contOut, fitorder=-2,
05815                                       overwrite=T)
05816         except Exception, e:
05817             note('Caught expected Exception: '+str(e))
05818             myim2 = false
05819         if myim2:
05820             stop('continuumsub 4 unexpectedly did not fail')
05821         #
05822         # Some simple run tests.
05823         #
05824         myim2 = myim.continuumsub (lineOut, contOut, overwrite=T)
05825 
05826         if not myim2:
05827             stop('continuumsub 5 failed')
05828         ok = myim2.done()
05829         if not ok: fail()
05830         #
05831         return cleanup(testdir)
05832 
05833     def test39():
05834         #
05835         # Test methods
05836         #   fitprofile
05837         #
05838         info('')
05839         info('')
05840         info('')
05841         info('Test 39 - fitprofile')
05842         y = [ 
05843             8.30588e-19,1.16698e-17,1.50353e-16,1.77636e-15,1.92451e-14,
05844             1.91198e-13,1.74187e-12,1.45519e-11,1.1148e-10,7.83146e-10,
05845             5.045e-09,2.98023e-08,1.6144e-07,8.01941e-07,3.65297e-06,
05846             1.52588e-05,5.84475e-05,0.000205297,0.000661258,0.00195312,
05847             0.00529006,0.013139,0.0299251,0.0625,0.1197,0.210224,0.338564,
05848             0.5,0.677128,0.840896,0.957603,1,0.957603,0.840896,0.677128,0.5,
05849             0.338564,0.210224,0.1197,0.0625,0.0299251,0.013139,0.00529006,
05850             0.00195312,0.000661258,0.000205297,5.84475e-05,1.52588e-05,
05851             3.65297e-06,8.01941e-07,1.6144e-07,2.98023e-08,5.045e-09,
05852             7.83146e-10,1.1148e-10,1.45519e-11,1.74187e-12,1.91198e-13,
05853             1.92451e-14,1.77636e-15,1.50353e-16,1.16698e-17,8.30588e-19,
05854             5.42101e-20
05855         ]
05856         # Make image
05857         myim = ia.newimagefromarray(pixels=y)
05858         if not myim:
05859             stop('ia.fromarray constructor 1 failed')
05860         testdir = 'imagetest_temp'
05861         os.mkdir(testdir)
05862         model = testdir +'/xmodel.im'
05863         fit = myim.fitprofile(axis=0, model=model)
05864         myim.close()
05865         if not fit:
05866             stop('fitprofile 2 failed')
05867         #
05868         tol = 1e-4
05869         myim.open(model)
05870         values = myim.getchunk().flatten()
05871         for i in range(len(y)):
05872             if not abs(y[i]-values[i]) < tol:
05873                 stop('fitprofile gives wrong values')
05874         #
05875         ok = myim.done()
05876         if not ok: fail()
05877         return True
05878 
05879     def test40():
05880         #
05881         # Test methods
05882         #   momentsgui, sepconvolvegui, maskhandlergui, view
05883         #
05884         info('')
05885         info('')
05886         info('')
05887         info('Test 40 - GUIS: momentsgui, sepconvolvegui, maskhandlergui, view')
05888         if true:
05889             info ('No GUI available, cannot test GUI methods')
05890             #return True
05891         # Make the directory
05892         testdir = 'imagetest_temp'
05893         if not cleanup(testdir):
05894             return False
05895         try:
05896             os.mkdir(testdir)
05897         except IOError, e:
05898             note(e, "SEVERE")
05899             raise RuntimeError, "mkdir " + testdir + " fails!"
05900         # Make image
05901         imshape = [100,100]
05902         pixels = ia.makearray(0.0, imshape)
05903         for j in range(39,60):
05904             for i in range(39,60):
05905                 if (i>=44 and j>=44 and i<=54 and j<=54):
05906                     pixels[i,j] = 10
05907                 else:
05908                     pixels[i,j] = 5
05909         imname = testdir+'/'+'ia.fromarray1.image'
05910         myim = ia.newimagefromarray(outfile=imname, pixels=pixels)
05911         if not myim:
05912             stop('ia.fromarray constructor 1 failed')
05913         #
05914         ok = true
05915         info('')
05916         #info('Testing function view')
05917         #ok = myim.view(raster=T, contour=T)
05918         if not ok:
05919             stop('view failed')
05920         #
05921         info('')
05922         #info('Testing maskhandlerguiview')
05923         #ok = myim.maskhandlergui()
05924         if not ok:
05925             stop('maskhandlergui failed')
05926         #
05927         info('')
05928         #info('Testing momentsgui')
05929         #ok = myim.momentsgui()
05930         if not ok:
05931             stop('momentsgui failed')
05932         #
05933         info('')
05934         #info('Testing sepconvolvegui')
05935         #ok = myim.sepconvolvegui()
05936         if not ok:
05937             stop('sepconvolvegui failed')
05938         #
05939         ok = myim.done()
05940         if not ok:
05941             stop('Done failed (1)')
05942         #
05943         return cleanup(testdir)
05944 
05945 
05946     test1()
05947     test2()
05948     test3()
05949     test4()
05950     test5()
05951     test6()
05952     test7()
05953     test8()
05954     test9()
05955     test10()
05956     #test11()
05957     test12()
05958     test13()  # segmentation fault on multiple runs
05959     test14()
05960     test15()
05961     test16()
05962     test17()
05963     test18()
05964     test19()
05965     test20()
05966     test21()
05967     test22()
05968     test24()
05969     test25()
05970     test26()  # needs comparison to numpy.fft result implemented
05971     test28()
05972     test29()
05973     test30()  # are abs/rel/world/pixel output values correct?
05974     test32()  # original has commented out bits. Why?
05975     test33()
05976     test34()
05977     test36()
05978     test37()
05979     test39()  # update once functionals is available
05980     test40()  # doesn't do much without gui
05981     print ''
05982     print 'Regression PASSED'
05983     print ''
05984     
05985 imagedemo()
05986 
05987 Benchmarking = True
05988 if Benchmarking:
05989     startTime = time.time()
05990     regstate = False
05991     for i in range(1):  #get seg fault when reran
05992         imagetest()
05993     endTime = time.time()
05994     regstate = True
05995 else:
05996     imagetest()
05997 
05998 print "End of imagetest.py"
05999 #exit()