Changeset 3136 for trunk/GSASIIsasd.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/GSASIIsasd.py

    r2863 r3136  
    1313# $Id$
    1414########### SVN repository information ###################
     15from __future__ import division, print_function
    1516import os
    1617import math
     
    924925
    925926        if report:
    926             print " MaxEnt trial/max: %3d/%3d" % ((iter+1), IterMax)
    927             print " Residual: %5.2lf%% Entropy: %8lg" % (100*test, S)
    928             print " Function sum: %.6lg Change from last: %.2lf%%\n" % (fSum,100*fChange/fSum)
     927            print (" MaxEnt trial/max: %3d/%3d" % ((iter+1), IterMax))
     928            print (" Residual: %5.2lf%% Entropy: %8lg" % (100*test, S))
     929            print (" Function sum: %.6lg Change from last: %.2lf%%\n" % (fSum,100*fChange/fSum))
    929930
    930931        # See if we have finished our task.
    931932        # do the hardest test first
    932933        if (abs(chisq/chizer-1.0) < CHI_SQR_LIMIT) and  (test < TEST_LIMIT):
    933             print ' Convergence achieved.'
     934            print (' Convergence achieved.')
    934935            return chisq,f,image_to_data(f, G)     # solution FOUND returns here
    935     print ' No convergence! Try increasing Error multiplier.'
     936    print (' No convergence! Try increasing Error multiplier.')
    936937    return chisq,f,image_to_data(f, G)       # no solution after IterMax iterations
    937938
     
    991992        err = chisq/len(datum)
    992993        if report:
    993             print ' Iteration: %d, chisq: %.3g, sum(shift^2): %.3g'%(nIter,chisq,np.sum(shift**2))
     994            print (' Iteration: %d, chisq: %.3g, sum(shift^2): %.3g'%(nIter,chisq,np.sum(shift**2)))
    994995    return chisq,Xw,calc
    995996
     
    10721073    Ib[:] = Back[0]
    10731074    Ic[Ibeg:Ifin] += Back[0]
    1074     print ' Final chi^2: %.3f'%(chisq)
     1075    print (' Final chi^2: %.3f'%(chisq))
    10751076    data['Size']['Distribution'] = [Bins,Dbins,BinMag/(2.*Dbins)]
    10761077       
     
    11431144       
    11441145    def SetModelParms():
    1145         print ' Refined parameters: Histogram scale: %.4g'%(parmDict['Scale'])
     1146        print (' Refined parameters: Histogram scale: %.4g'%(parmDict['Scale']))
    11461147        if 'Back' in varyList:
    11471148            Model['Back'][0] = parmDict['Back']
    1148             print '  %15s %15.4f esd: %15.4g'%('Background:',parmDict['Back'],sigDict['Back'])
     1149            print ('  %15s %15.4f esd: %15.4g'%('Background:',parmDict['Back'],sigDict['Back']))
    11491150        partData = Model['Particle']
    11501151        for i,level in enumerate(partData['Levels']):
     
    11521153            Type = controls['DistType']
    11531154            if Type in ['LogNormal','Gaussian','LSW','Schulz-Zimm','Monodisperse']:
    1154                 print ' Component %d: Type: %s: Structure Factor: %s Contrast: %12.3f'  \
    1155                     %(i,Type,controls['StrFact'],controls['Contrast'])               
     1155                print (' Component %d: Type: %s: Structure Factor: %s Contrast: %12.3f'  \
     1156                    %(i,Type,controls['StrFact'],controls['Contrast']))             
    11561157            else:
    1157                 print ' Component %d: Type: %s: '%(i,Type,)
     1158                print (' Component %d: Type: %s: '%(i,Type,))
    11581159            cid = str(i)+';'
    11591160            if Type in ['LogNormal','Gaussian','LSW','Schulz-Zimm','Monodisperse']:
     
    11611162                    if cid+item in varyList:
    11621163                        controls['FFargs'][item][0] = parmDict[cid+item]
    1163                         print ' %15s: %15.4g esd: %15.4g'%(cid+item,parmDict[cid+item],sigDict[cid+item])
     1164                        print (' %15s: %15.4g esd: %15.4g'%(cid+item,parmDict[cid+item],sigDict[cid+item]))
    11641165                for item in SFparmOrder:
    11651166                    if cid+item in varyList:
    11661167                        controls['SFargs'][item][0] = parmDict[cid+item]
    1167                         print ' %15s: %15.4g esd: %15.4g'%(cid+item,parmDict[cid+item],sigDict[cid+item])
     1168                        print (' %15s: %15.4g esd: %15.4g'%(cid+item,parmDict[cid+item],sigDict[cid+item]))
    11681169            distDict = controls['DistType']
    11691170            for item in level[distDict]:
    11701171                if cid+item in varyList:
    11711172                    level[distDict][item][0] = parmDict[cid+item]
    1172                     print ' %15s: %15.4g esd: %15.4g'%(cid+item,parmDict[cid+item],sigDict[cid+item])
     1173                    print (' %15s: %15.4g esd: %15.4g'%(cid+item,parmDict[cid+item],sigDict[cid+item]))
    11731174                   
    11741175    def calcSASD(values,Q,Io,wt,Ifb,levelTypes,parmDict,varyList):
     
    12801281            sig = np.sqrt(np.diag(covM)*Rvals['GOF'])
    12811282            sigDict = dict(zip(varyList,sig))
    1282         print ' Results of small angle data modelling fit:'
    1283         print 'Number of function calls:',ncalc,' Number of observations: ',Ifin-Ibeg,' Number of parameters: ',len(varyList)
    1284         print 'Rwp = %7.2f%%, chi**2 = %12.6g, reduced chi**2 = %6.2f'%(Rvals['Rwp'],chisq,Rvals['GOF'])
     1283        print (' Results of small angle data modelling fit:')
     1284        print ('Number of function calls: %d Number of observations: %d Number of parameters: %d'%(ncalc,Ifin-Ibeg,len(varyList)))
     1285        print ('Rwp = %7.2f%%, chi**2 = %12.6g, reduced chi**2 = %6.2f'%(Rvals['Rwp'],chisq,Rvals['GOF']))
    12851286        SetModelParms()
    12861287        covMatrix = covM*Rvals['GOF']
     
    14351436    '''print the contents of a vector to the console'''
    14361437    n = a.shape[0]
    1437     print "%s[ = (" % text,
     1438    print ("%s[ = (" % text,end='')
    14381439    for i in range(n):
    14391440        s = " %g, " % a[i]
    1440         print s,
    1441     print ")"
     1441        print (s,end='')
     1442    print (")")
    14421443
    14431444def print_arr(text, a):
    14441445    '''print the contents of an array to the console'''
    14451446    n, m = a.shape
    1446     print "%s[][] = (" % text
     1447    print ("%s[][] = (" % text)
    14471448    for i in range(n):
    1448         print " (",
     1449        print (" (",end='')
    14491450        for j in range(m):
    1450             print " %g, " % a[i][j],
    1451         print "),"
    1452     print ")"
     1451            print (" %g, " % a[i][j],end='')
     1452        print ("),")
     1453    print (")")
    14531454
    14541455def test_MaxEnt_SB(report=True):
     
    14631464        dI = np.array(buf[2], dtype=np.float64)
    14641465        return q, I, dI
    1465     print "MaxEnt_SB: "
     1466    print ("MaxEnt_SB: ")
    14661467    test_data_file = os.path.join( 'testinp', 'test.sas')
    14671468    rhosq = 100     # scattering contrast, 10^20 1/cm^-4
     
    14821483    chisq,f_dr,Ic = MaxEnt_SB(I - bkg, dI*errFac, b, IterMax, G, report=report)
    14831484    if f_dr is None:
    1484         print "no solution"
     1485        print ("no solution")
    14851486        return
    14861487   
    1487     print "solution reached"
     1488    print ("solution reached")
    14881489    for a,b,c in zip(r.tolist(), dr.tolist(), f_dr.tolist()):
    1489         print '%10.4f %10.4f %12.4g'%(a,b,c)
     1490        print ('%10.4f %10.4f %12.4g'%(a,b,c))
    14901491
    14911492def tests():
Note: See TracChangeset for help on using the changeset viewer.