Changeset 3136 for trunk/GSASIIimage.py


Ignore:
Timestamp:
Oct 23, 2017 11:39:16 AM (4 years ago)
Author:
vondreele
Message:

make GSAS-II python 3.6 compliant & preserve python 2.7 use;changes:
do from future import division, print_function for all GSAS-II py sources
all menu items revised to be py 2.7/3.6 compliant
all wx.OPEN --> wx.FD_OPEN in file dialogs
all integer divides (typically for image pixel math) made explicit with ; ambiguous ones made floats as appropriate
all print "stuff" --> print (stuff)
all print >> pFile,'stuff' --> pFile.writeCIFtemplate('stuff')
all read file opens made explicit 'r' or 'rb'
all cPickle imports made for py2.7 or 3.6 as cPickle or _pickle; test for '2' platform.version_tuple[0] for py 2.7
define cPickleload to select load(fp) or load(fp,encoding='latin-1') for loading gpx files; provides cross compatibility between py 2.7/3.6 gpx files
make dict.keys() as explicit list(dict.keys()) as needed (NB: possible source of remaining py3.6 bugs)
make zip(a,b) as explicit list(zip(a,b)) as needed (NB: possible source of remaining py3.6 bugs)
select unichr/chr according test for '2' platform.version_tuple[0] for py 2.7 (G2pwdGUI * G2plot) for special characters
select wg.EVT_GRID_CELL_CHANGE (classic) or wg.EVT_GRID_CELL_CHANGED (phoenix) in grid Bind
maxint --> maxsize; used in random number stuff
raise Exception,"stuff" --> raise Exception("stuff")
wx 'classic' sizer.DeleteWindows?() or 'phoenix' sizer.Clear(True)
wx 'classic' SetToolTipString?(text) or 'phoenix' SetToolTip?(wx.ToolTip?(text)); define SetToolTipString?(self,text) to handle the choice in plots
status.SetFields? --> status.SetStatusText?
'classic' AddSimpleTool? or 'phoenix' self.AddTool? for plot toolbar; Bind different as well
define GetItemPydata? as it doesn't exist in wx 'phoenix'
allow python versions 2.7 & 3.6 to run GSAS-II
Bind override commented out - no logging capability (NB: remove all logging code?)
all import ContentsValidator? open filename & test if valid then close; filepointer removed from Reader
binary importers (mostly images) test for 'byte' type & convert as needed to satisfy py 3.6 str/byte rules

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIimage.py

    r3106 r3136  
    1515
    1616'''
    17 
     17from __future__ import division, print_function
    1818import math
    1919import time
     
    9191        ''' gives ellipse center coordinates
    9292        '''
    93         b,c,d,f,a = p[1]/2, p[2], p[3]/2, p[4]/2, p[0]
     93        b,c,d,f,a = p[1]/2., p[2], p[3]/2., p[4]/2., p[0]
    9494        num = b*b-a*c
    9595        x0=(c*d-b*f)/num
     
    101101        range will be -90 to 90 deg
    102102        '''
    103         b,c,a = p[1]/2, p[2], p[0]
     103        b,c,a = p[1]/2., p[2], p[0]
    104104        return 0.5*npatand(2*b/(a-c))
    105105   
     
    107107        ''' gives ellipse radii in [minor,major] order
    108108        '''
    109         b,c,d,f,g,a = p[1]/2, p[2], p[3]/2, p[4]/2, p[5], p[0]
     109        b,c,d,f,g,a = p[1]/2., p[2], p[3]/2., p[4]/2, p[5], p[0]
    110110        up = 2*(a*f*f+c*d*d+g*b*b-2*b*d*f-a*c*g)
    111111        down1=(b*b-a*c)*( (c-a)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a))
     
    138138       
    139139    def CalibPrint(ValSig,chisq,Npts):
    140         print 'Image Parameters: chi**2: %12.3g, Np: %d'%(chisq,Npts)
     140        print ('Image Parameters: chi**2: %12.3g, Np: %d'%(chisq,Npts))
    141141        ptlbls = 'names :'
    142142        ptstr =  'values:'
     
    152152            else:
    153153                sigstr += 12*' '
    154         print ptlbls
    155         print ptstr
    156         print sigstr       
     154        print (ptlbls)
     155        print (ptstr)
     156        print (sigstr)       
    157157       
    158158    def ellipseCalcD(B,xyd,varyList,parmDict):
     
    225225        Zmin = np.argmin(ZMin)
    226226        xpix += Zmax%w2-w
    227         ypix += Zmax/w2-w
     227        ypix += Zmax//w2-w
    228228        return xpix,ypix,np.ravel(ZMax)[Zmax],max(0.0001,np.ravel(ZMin)[Zmin])   #avoid neg/zero minimum
    229229    else:
     
    236236        if radii[0] < 0:        #hyperbola
    237237            theta = npacosd(1./np.sqrt(1.+(radii[0]/radii[1])**2))
    238             print theta
     238#            print (theta)
    239239            return 0
    240240        apb = radii[1]+radii[0]
     
    492492    blkSize = 512
    493493    Nx,Ny = data['size']
    494     nXBlks = (Nx-1)/blkSize+1
    495     nYBlks = (Ny-1)/blkSize+1
     494    nXBlks = (Nx-1)//blkSize+1
     495    nYBlks = (Ny-1)//blkSize+1
    496496    tam = ma.make_mask_none(data['size'])
    497497    for iBlk in range(nXBlks):
     
    521521    '''
    522522    import ImageCalibrants as calFile
    523     print 'Image recalibration:'
     523    print ('Image recalibration:')
    524524    time0 = time.time()
    525525    pixelSize = data['pixelSize']
     
    533533        data['DetDepth'] /= data['distance']
    534534    if not data['calibrant']:
    535         print 'no calibration material selected'
     535        print ('no calibration material selected')
    536536        return []   
    537537    skip = data['calibskip']
     
    560560        tam = ma.mask_or(tam,MakeFrameMask(data,frame))
    561561    for iH,H in enumerate(HKL):
    562         if debug:   print H
     562        if debug:   print (H)
    563563        dsp = H[3]
    564564        tth = 2.0*asind(wave/(2.*dsp))
    565565        if tth+abs(data['tilt']) > 90.:
    566             print 'next line is a hyperbola - search stopped'
     566            print ('next line is a hyperbola - search stopped')
    567567            break
    568568        ellipse = GetEllipse(dsp,data)
     
    579579            continue
    580580    if not data['rings']:
    581         print 'no rings found; try lower Min ring I/Ib'
     581        print ('no rings found; try lower Min ring I/Ib')
    582582        return []   
    583583       
     
    596596        ellipse = GetEllipse(H[3],data)
    597597        data['ellipses'].append(copy.deepcopy(ellipse+('b',)))   
    598     print 'calibration time = %.3f'%(time.time()-time0)
     598    print ('calibration time = %.3f'%(time.time()-time0))
    599599    G2plt.PlotImage(G2frame,newImage=True)       
    600600    return [vals,varyList,sigList,parmDict]
     
    606606    import copy
    607607    import ImageCalibrants as calFile
    608     print 'Image calibration:'
     608    print ('Image calibration:')
    609609    time0 = time.time()
    610610    ring = data['ring']
     
    616616    varyDict = data['varyList']
    617617    if varyDict['dist'] and varyDict['wave']:
    618         print 'ERROR - you can not simultaneously calibrate distance and wavelength'
     618        print ('ERROR - you can not simultaneously calibrate distance and wavelength')
    619619        return False
    620620    if len(ring) < 5:
    621         print 'ERROR - not enough inner ring points for ellipse'
     621        print ('ERROR - not enough inner ring points for ellipse')
    622622        return False
    623623       
     
    629629    fmt2 = '%s X: %.3f, Y: %.3f, phi: %.3f, R1: %.3f, R2: %.3f, chi**2: %.3f, Np: %d'
    630630    if outE:
    631         print fmt%('start ellipse: ',outE[0][0],outE[0][1],outE[1],outE[2][0],outE[2][1])
     631        print (fmt%('start ellipse: ',outE[0][0],outE[0][1],outE[1],outE[2][0],outE[2][1]))
    632632        ellipse = outE
    633633    else:
     
    642642        ellipse = FitEllipse(Ring)
    643643    else:
    644         print '1st ring not sufficiently complete to proceed'
     644        print ('1st ring not sufficiently complete to proceed')
    645645        return False
    646646    if debug:
    647         print fmt2%('inner ring:    ',ellipse[0][0],ellipse[0][1],ellipse[1],
    648             ellipse[2][0],ellipse[2][1],0.,len(Ring))     #cent,phi,radii
     647        print (fmt2%('inner ring:    ',ellipse[0][0],ellipse[0][1],ellipse[1],
     648            ellipse[2][0],ellipse[2][1],0.,len(Ring)))     #cent,phi,radii
    649649    data['ellipses'].append(ellipse[:]+('r',))
    650650    data['rings'].append(np.array(Ring))
     
    654654    data['rings'] = []
    655655    if not data['calibrant']:
    656         print 'no calibration material selected'
     656        print ('no calibration material selected')
    657657        return True
    658658   
     
    675675    elcent,phi,radii = ellipse              #from fit of 1st ring
    676676    dsp = HKL[0][3]
    677     print '1st ring: try %.4f'%(dsp)
     677    print ('1st ring: try %.4f'%(dsp))
    678678    if varyDict['dist']:
    679679        wave = data['wavelength']
     
    690690        tilt = npasind(np.sqrt(max(0.,1.-(radii[0]/radii[1])**2))*ctth)
    691691        if not tilt:
    692             print 'WARNING - selected ring was fitted as a circle'
    693             print ' - if detector was tilted we suggest you skip this ring - WARNING'
     692            print ('WARNING - selected ring was fitted as a circle')
     693            print (' - if detector was tilted we suggest you skip this ring - WARNING')
    694694    else:
    695695        tilt = data['tilt']
     
    714714        while fail:
    715715            dsp = HKL[i2][3]
    716             print '2nd ring: try %.4f'%(dsp)
     716            print ('2nd ring: try %.4f'%(dsp))
    717717            tth = 2.0*asind(wave/(2.*dsp))
    718718            ellipsep = GetEllipse2(tth,0.,dist,centp,tilt,phi)
    719             print fmt%('plus ellipse :',ellipsep[0][0],ellipsep[0][1],ellipsep[1],ellipsep[2][0],ellipsep[2][1])
     719            print (fmt%('plus ellipse :',ellipsep[0][0],ellipsep[0][1],ellipsep[1],ellipsep[2][0],ellipsep[2][1]))
    720720            Ringp = makeRing(dsp,ellipsep,3,cutoff,scalex,scaley,G2frame.ImageZ)[0]
    721721            parmDict = {'dist':dist,'det-X':centp[0],'det-Y':centp[1],
     
    731731                chip = 1e6
    732732            ellipsem = GetEllipse2(tth,0.,dist,centm,-tilt,phi)
    733             print fmt%('minus ellipse:',ellipsem[0][0],ellipsem[0][1],ellipsem[1],ellipsem[2][0],ellipsem[2][1])
     733            print (fmt%('minus ellipse:',ellipsem[0][0],ellipsem[0][1],ellipsem[1],ellipsem[2][0],ellipsem[2][1]))
    734734            Ringm = makeRing(dsp,ellipsem,3,cutoff,scalex,scaley,G2frame.ImageZ)[0]
    735735            if len(Ringm) > 10:
     
    768768        tth = 2.0*asind(wave/(2.*dsp))
    769769        if tth+abs(data['tilt']) > 90.:
    770             print 'next line is a hyperbola - search stopped'
     770            print ('next line is a hyperbola - search stopped')
    771771            break
    772         if debug:   print 'HKLD:',H[:4],'2-theta: %.4f'%(tth)
     772        if debug:   print ('HKLD:'+str(H[:4])+'2-theta: %.4f'%(tth))
    773773        elcent,phi,radii = ellipse = GetEllipse(dsp,data)
    774774        data['ellipses'].append(copy.deepcopy(ellipse+('g',)))
    775         if debug:   print fmt%('predicted ellipse:',elcent[0],elcent[1],phi,radii[0],radii[1])
     775        if debug:   print (fmt%('predicted ellipse:',elcent[0],elcent[1],phi,radii[0],radii[1]))
    776776        Ring = makeRing(dsp,ellipse,pixLimit,cutoff,scalex,scaley,G2frame.ImageZ)[0]
    777777        if Ring:
     
    787787                data['chisq'] = chisq
    788788                elcent,phi,radii = ellipse = GetEllipse(dsp,data)
    789                 if debug:   print fmt2%('fitted ellipse:   ',elcent[0],elcent[1],phi,radii[0],radii[1],chisq,len(rings))
     789                if debug:   print (fmt2%('fitted ellipse:   ',elcent[0],elcent[1],phi,radii[0],radii[1],chisq,len(rings)))
    790790            data['ellipses'].append(copy.deepcopy(ellipse+('r',)))
    791791#            G2plt.PlotImage(G2frame,newImage=True)
    792792        else:
    793             if debug:   print 'insufficient number of points in this ellipse to fit'
     793            if debug:   print ('insufficient number of points in this ellipse to fit')
    794794#            break
    795795    G2plt.PlotImage(G2frame,newImage=True)
    796796    fullSize = len(G2frame.ImageZ)/scalex
    797797    if 2*radii[1] < .9*fullSize:
    798         print 'Are all usable rings (>25% visible) used? Try reducing Min ring I/Ib'
     798        print ('Are all usable rings (>25% visible) used? Try reducing Min ring I/Ib')
    799799    N = len(data['ellipses'])
    800800    if N > 2:
     
    809809        ellipse = GetEllipse(H[3],data)
    810810        data['ellipses'].append(copy.deepcopy(ellipse+('b',)))
    811     print 'calibration time = %.3f'%(time.time()-time0)
     811    print ('calibration time = %.3f'%(time.time()-time0))
    812812    G2plt.PlotImage(G2frame,newImage=True)       
    813813    return True
     
    880880    'Integrate an image; called from OnIntegrateAll and OnIntegrate in G2imgGUI'    #for q, log(q) bins need data['binType']
    881881    import histogram2d as h2d
    882     print 'Begin image integration'
     882    print ('Begin image integration')
    883883    CancelPressed = False
    884884    LUtth = np.array(data['IOtth'])
     
    906906    H0 = np.zeros(shape=(numAzms,numChans),order='F',dtype=np.float32)
    907907    Nx,Ny = data['size']
    908     nXBlks = (Nx-1)/blkSize+1
    909     nYBlks = (Ny-1)/blkSize+1
     908    nXBlks = (Nx-1)//blkSize+1
     909    nYBlks = (Ny-1)//blkSize+1
    910910    tbeg = time.time()
    911911    times = [0,0,0,0,0]
     
    965965        H0 /= np.array([G2pwd.Polarization(data['PolaVal'][0],H2[:-1],Azm=azm-90.)[0] for azm in (H1[:-1]+np.diff(H1)/2.)])
    966966    times[4] += time.time()-t0
    967     print 'Step times: \n apply masks  %8.3fs xy->th,azm   %8.3fs fill map     %8.3fs \
    968         \n binning      %8.3fs cleanup      %8.3fs'%(times[0],times[1],times[2],times[3],times[4])
    969     print "Elapsed time:","%8.3fs"%(time.time()-tbeg)
    970     print 'Integration complete'
     967    print ('Step times: \n apply masks  %8.3fs xy->th,azm   %8.3fs fill map     %8.3fs \
     968        \n binning      %8.3fs cleanup      %8.3fs'%(times[0],times[1],times[2],times[3],times[4]))
     969    print ("Elapsed time:","%8.3fs"%(time.time()-tbeg))
     970    print ('Integration complete')
    971971    if returnN:     #As requested by Steven Weigand
    972972        return H0,H1,H2,NST,CancelPressed
     
    10231023            ring['Ivar'] = np.var(ringint)
    10241024            ring['covMat'] = covMat
    1025             print 'Variance in normalized ring intensity: %.3f'%(ring['Ivar'])
     1025            print ('Variance in normalized ring intensity: %.3f'%(ring['Ivar']))
    10261026    CalcStrSta(StrSta,Controls)
    10271027   
     
    10421042            ringint = np.array([float(Image[int(x*scalex),int(y*scaley)]) for y,x in np.array(ringxy)[:,:2]])
    10431043            ringint /= np.mean(ringint)
    1044             print ' %s %.3f %s %.3f'%('d-spacing',ring['Dcalc'],'sig(MRD):',np.sqrt(np.var(ringint)))
     1044            print (' %s %.3f %s %.3f'%('d-spacing',ring['Dcalc'],'sig(MRD):',np.sqrt(np.var(ringint))))
    10451045            RingsAI.append(np.array(zip(ringazm,ringint)).T)
    10461046    return RingsAI
     
    10941094    'Needs a doc string'
    10951095    def StrainPrint(ValSig,dset):
    1096         print 'Strain tensor for Dset: %.6f'%(dset)
     1096        print ('Strain tensor for Dset: %.6f'%(dset))
    10971097        ptlbls = 'names :'
    10981098        ptstr =  'values:'
     
    11051105            else:
    11061106                sigstr += 12*' '
    1107         print ptlbls
    1108         print ptstr
    1109         print sigstr
     1107        print (ptlbls)
     1108        print (ptstr)
     1109        print (sigstr)
    11101110       
    11111111    def strainCalc(p,xyd,dset,wave,phi,StaType):
     
    11331133   
    11341134def AutoSpotMasks(Image,Masks,Controls):
    1135     print 'auto spot search'
     1135    print ('auto spot search')
    11361136    maxPks = 500
    11371137    dmax = 1.5         #just beyond diamond 111 @ 2.0596
     
    11561156        MX = ma.array(M,mask=(M<10.))
    11571157        Indx = ma.nonzero(ma.getmask(MX))
    1158         print 'Spots found: ',mul,len(pts),distort,len(Indx[0])
     1158        print ('Spots found: %d %d %.2f %d'%(mul,len(pts),distort,len(Indx[0])))
    11591159        if distort < .3:
    11601160            break
    11611161    if not len(Indx[0]):
    1162         print 'no auto search spots found'
     1162        print ('no auto search spots found')
    11631163        return None
    11641164    if distort > 2.:
    1165         print 'no big spots found'
     1165        print ('no big spots found')
    11661166        return None
    11671167    #use clustered points to get position & spread
Note: See TracChangeset for help on using the changeset viewer.