Changeset 4021


Ignore:
Timestamp:
Jun 11, 2019 10:05:07 PM (2 years ago)
Author:
toby
Message:

implement filter for screen messages; start to replace print() with G2Print(); scripting changes for PDF

Location:
trunk
Files:
11 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIctrlGUI.py

    r3977 r4021  
    11541154        self.onChoice = None
    11551155        self.SetSelection(wx.NOT_FOUND)
    1156         if self.indLoc is not None and self.indLoc.get(self.indKey) is not None:
    1157             self.SetSelection(self.indLoc[self.indKey])
    1158             if self.strLoc is not None:
     1156        if self.indLoc is not None and self.strLoc is not None:
     1157            try:
     1158                self.SetSelection(self.indLoc[self.indKey])
    11591159                self.strLoc[self.strKey] = self.GetStringSelection()
    11601160                log.LogVarChange(self.strLoc,self.strKey)
    1161         elif self.strLoc is not None and self.strLoc.get(self.strKey) is not None:
     1161            except ValueError:
     1162                pass
     1163        elif self.strLoc is not None and self.strKey is not None:
    11621164            try:
    11631165                self.SetSelection(choiceList.index(self.strLoc[self.strKey]))
  • trunk/GSASIIdataGUI.py

    r4015 r4021  
    41624162                dirname,filename = os.path.split(filename)
    41634163                filename = os.path.splitext(filename)[0]
     4164            Inst = None
     4165            Limits = None
    41644166            for export in exports:
    41654167                if len(exports) > 1:
  • trunk/GSASIIfiles.py

    r4018 r4021  
    4242            pass
    4343    return 0.0
     44
     45G2printLevel = 'all'
     46'''This defines the level of output from calls to :func:`G2Print`,
     47which should  be used in place of print() within this module.
     48Settings for this are 'all', 'warn', 'error' or 'none'. Also see:
     49:func:`G2Print` and :func:`G2SetPrintLevel`.
     50'''
     51
     52def G2SetPrintLevel(level):
     53    '''Set the level of output from calls to :func:`G2Print`, which should
     54    be used in place of print() within GSASII. Settings for the mode are
     55    'all', 'warn', 'error' or 'none'
     56   
     57    :param str level: a string used to set the print level, which may be
     58    'all', 'warn', 'error' or 'none'.
     59    Note that capitalization and extra letters in level are ignored, so
     60    'Warn', 'warnings', etc. will all set the mode to 'warn'
     61    '''
     62    global G2printLevel
     63    for mode in  'all', 'warn', 'error', 'none':
     64        if mode in level.lower():
     65            G2printLevel = mode
     66            return
     67    else:
     68        G2Print('G2SetPrintLevel Error: level={} cannot be interpreted.',
     69                    'Use all, warn, error or none.')
     70       
     71def G2Print(*args,mode=None,**kwargs):
     72    '''Print with filtering based level of output (see :func:`G2SetPrintLevel`).
     73    Use G2Print() as replacement for print().
     74
     75    :param str mode: if specified, this should contain the mode for printing
     76    ('error', 'warn' or anything else). If not specified, the first argument
     77    of the print command (args[0]) should contain the string 'error' for
     78    error messages and 'warn' for warning messages.
     79    '''
     80    if G2printLevel is 'none': return
     81    if mode is None:
     82        testStr = args[0].lower()
     83    else:
     84        testStr = mode[:].lower()
     85    level = 2
     86    for i,mode in enumerate(('error', 'warn')):
     87        if mode in testStr:
     88            level = i
     89            break
     90    if G2printLevel == 'error' and level > 0: return
     91    if G2printLevel == 'warn' and level > 1: return
     92    print(*args,**kwargs)
    4493
    4594def get_python_versions(packagelist):
     
    360409                            readerlist.append(reader)
    361410        except AttributeError:
    362             print ('Import_' + errprefix + ': Attribute Error ' + filename)
     411            G2Print ('Import_' + errprefix + ': Attribute Error ' + filename)
    363412            if traceback:
    364413                traceback.print_exc(file=sys.stdout)
    365414        except Exception as exc:
    366             print ('\nImport_' + errprefix + ': Error importing file ' + filename)
    367             print (u'Error message: {}\n'.format(exc))
     415            G2Print ('\nImport_' + errprefix + ': Error importing file ' + filename)
     416            G2Print (u'Error message: {}\n'.format(exc))
    368417            if traceback:
    369418                traceback.print_exc(file=sys.stdout)
     
    409458                    pass
    410459                except Exception as exc:
    411                     print ('\nExport init: Error substantiating class ' + clss[0])
    412                     print (u'Error message: {}\n'.format(exc))
     460                    G2Print ('\nExport init: Error substantiating class ' + clss[0])
     461                    G2Print (u'Error message: {}\n'.format(exc))
    413462                    if traceback:
    414463                        traceback.print_exc(file=sys.stdout)
     
    416465                exporterlist.append(exporter)
    417466        except AttributeError:
    418             print ('Export Attribute Error ' + filename)
     467            G2Print ('Export Attribute Error ' + filename)
    419468            if traceback:
    420469                traceback.print_exc(file=sys.stdout)
    421470        except Exception as exc:
    422             print ('\nExport init: Error importing file ' + filename)
    423             print (u'Error message: {}\n'.format(exc))
     471            G2Print ('\nExport init: Error importing file ' + filename)
     472            G2Print (u'Error message: {}\n'.format(exc))
    424473            if traceback:
    425474                traceback.print_exc(file=sys.stdout)
     
    564613    parfiles = glob.glob(os.path.join(GSASIIpath.GetConfigValue('Column_Metadata_directory'),'*.par'))
    565614    if len(parfiles) == 0:
    566         print('Sorry, No Column metadata (.par) file found in '+
     615        G2Print('Sorry, No Column metadata (.par) file found in '+
    567616              GSASIIpath.GetConfigValue('Column_Metadata_directory'))
    568617        return {}
     
    574623                break
    575624        else:
    576             print('Warning: No labels definitions found for '+parFil)
     625            G2Print('Warning: No labels definitions found for '+parFil)
    577626            continue
    578627        labels,lbldict,keyCols,keyExp,errors = readColMetadataLabels(lblFil)
     
    582631            continue
    583632        else:
    584             print('Read '+lblFil)
     633            G2Print('Read '+lblFil)
    585634        # scan through each line in this .par file, looking for the matching image rootname
    586635        fp = open(parFil,'Ur')
     
    600649            metadata['par file'] = parFil
    601650            metadata['lbls file'] = lblFil
    602             print("Metadata read from {} line {}".format(parFil,iline+1))
     651            G2Print("Metadata read from {} line {}".format(parFil,iline+1))
    603652            fp.close()
    604653            return metadata
    605654        else:
    606             print("Image {} not found in {}".format(imageName,parFil))
     655            G2Print("Image {} not found in {}".format(imageName,parFil))
    607656            fp.close()
    608657            continue
    609658        fp.close()
    610659    else:
    611         print("Warning: No .par metadata for image {}".format(imageName))
     660        G2Print("Warning: No .par metadata for image {}".format(imageName))
    612661        return {}
    613662
     
    700749        reader.Data['wavelength'] = parParms['wavelength']
    701750    else:
    702         print('Error: wavelength not defined in {}'.format(parParms['lbls file']))
     751        G2Print('Error: wavelength not defined in {}'.format(parParms['lbls file']))
    703752    if "distance" in parParms:
    704753        reader.Data['distance'] = parParms['distance']
    705754        reader.Data['setdist'] = parParms['distance']
    706755    else:
    707         print('Error: distance not defined in {}'.format(parParms['lbls file']))
     756        G2Print('Error: distance not defined in {}'.format(parParms['lbls file']))
    708757
    709758def LoadControls(Slines,data):
     
    778827                primaryReaders.append(rd)
    779828    if len(secondaryReaders) + len(primaryReaders) == 0:
    780         print('Error: No matching format for file '+imagefile)
     829        G2Print('Error: No matching format for file '+imagefile)
    781830        raise Exception('No image read')
    782831    errorReport = ''
     
    796845                raise Exception('No image read. Strange!')
    797846            if GSASIIpath.GetConfigValue('Transpose'):
    798                 print ('Transposing Image!')
     847                G2Print ('Warning: Transposing Image!')
    799848                rd.Image = rd.Image.T
    800849            #rd.readfilename = imagefile
    801850            return rd.Image
    802851    else:
    803         print('Error reading file '+imagefile)
    804         print('Error messages(s)\n'+errorReport)
     852        G2Print('Error reading file '+imagefile)
     853        G2Print('Error messages(s)\n'+errorReport)
    805854        raise Exception('No image read')
    806855
     
    870919            iqfile.write("%15.6g %15.6g\n" % (q,iq))
    871920        iqfile.close()
    872         print (' I(Q) saved to: '+iqfilename)
     921        G2Print (' I(Q) saved to: '+iqfilename)
    873922
    874923    if PDFsaves[1]:     #S(Q)
     
    884933            sqfile.write("%15.6g %15.6g\n" % (q,sq))
    885934        sqfile.close()
    886         print (' S(Q) saved to: '+sqfilename)
     935        G2Print (' S(Q) saved to: '+sqfilename)
    887936
    888937    if PDFsaves[2]:     #F(Q)
     
    898947            fqfile.write("%15.6g %15.6g\n" % (q,fq))
    899948        fqfile.close()
    900         print (' F(Q) saved to: '+fqfilename)
     949        G2Print (' F(Q) saved to: '+fqfilename)
    901950
    902951    if PDFsaves[3]:     #G(R)
     
    912961            grfile.write("%15.6g %15.6g\n" % (r,gr))
    913962        grfile.close()
    914         print (' G(R) saved to: '+grfilename)
     963        G2Print (' G(R) saved to: '+grfilename)
    915964
    916965    if PDFsaves[4]: #pdfGUI file for G(R)
     
    9701019            grfile.write("%15.2F %15.6F\n" % (r,gr))
    9711020        grfile.close()
    972         print (' G(R) saved to: '+grfilename)
     1021        G2Print (' G(R) saved to: '+grfilename)
  • trunk/GSASIIimage.py

    r4009 r4021  
    3434import GSASIIspc as G2spc
    3535import GSASIImath as G2mth
     36import GSASIIfiles as G2fil
    3637
    3738# trig functions in degrees
     
    566567    '''
    567568    import ImageCalibrants as calFile
    568     print ('Image recalibration:')
     569    G2fil.G2Print ('Image recalibration:')
    569570    time0 = time.time()
    570571    pixelSize = data['pixelSize']
     
    578579        data['DetDepth'] /= data['distance']
    579580    if not data['calibrant']:
    580         print ('no calibration material selected')
     581        G2fil.G2Print ('warning: no calibration material selected')
    581582        return []   
    582583    skip = data['calibskip']
    583584    dmin = data['calibdmin']
    584585    if data['calibrant'] not in calFile.Calibrants:
    585         print(' %s not in local copy of image calibrants file'%data['calibrant'])
     586        G2fil.G2Print('Warning: %s not in local copy of image calibrants file'%data['calibrant'])
    586587        return []
    587588    Bravais,SGs,Cells = calFile.Calibrants[data['calibrant']][:3]
     
    612613        tth = 2.0*asind(wave/(2.*dsp))
    613614        if tth+abs(data['tilt']) > 90.:
    614             print ('next line is a hyperbola - search stopped')
     615            G2fil.G2Print ('next line is a hyperbola - search stopped')
    615616            break
    616617        ellipse = GetEllipse(dsp,data)
     
    627628            continue
    628629    if not data['rings']:
    629         print ('no rings found; try lower Min ring I/Ib')
     630        G2fil.G2Print ('no rings found; try lower Min ring I/Ib',mode='warn')
    630631        return []   
    631632       
     
    644645        ellipse = GetEllipse(H[3],data)
    645646        data['ellipses'].append(copy.deepcopy(ellipse+('b',)))   
    646     print ('calibration time = %.3f'%(time.time()-time0))
     647    G2fil.G2Print ('calibration time = %.3f'%(time.time()-time0))
    647648    if G2frame:
    648649        G2plt.PlotImage(G2frame,newImage=True)       
     
    654655    '''
    655656    import ImageCalibrants as calFile
    656     print ('Image calibration:')
     657    G2fil.G2Print ('Image calibration:')
    657658    time0 = time.time()
    658659    ring = data['ring']
     
    664665    varyDict = data['varyList']
    665666    if varyDict['dist'] and varyDict['wave']:
    666         print ('ERROR - you can not simultaneously calibrate distance and wavelength')
     667        G2fil.G2Print ('ERROR - you can not simultaneously calibrate distance and wavelength')
    667668        return False
    668669    if len(ring) < 5:
    669         print ('ERROR - not enough inner ring points for ellipse')
     670        G2fil.G2Print ('ERROR - not enough inner ring points for ellipse')
    670671        return False
    671672       
     
    677678    fmt2 = '%s X: %.3f, Y: %.3f, phi: %.3f, R1: %.3f, R2: %.3f, chi**2: %.3f, Np: %d'
    678679    if outE:
    679         print (fmt%('start ellipse: ',outE[0][0],outE[0][1],outE[1],outE[2][0],outE[2][1]))
     680        G2fil.G2Print (fmt%('start ellipse: ',outE[0][0],outE[0][1],outE[1],outE[2][0],outE[2][1]))
    680681        ellipse = outE
    681682    else:
     
    690691        ellipse = FitEllipse(Ring)
    691692    else:
    692         print ('1st ring not sufficiently complete to proceed')
     693        G2fil.G2Print ('1st ring not sufficiently complete to proceed',mode='warn')
    693694        return False
    694695    if debug:
    695         print (fmt2%('inner ring:    ',ellipse[0][0],ellipse[0][1],ellipse[1],
     696        G2fil.G2Print (fmt2%('inner ring:    ',ellipse[0][0],ellipse[0][1],ellipse[1],
    696697            ellipse[2][0],ellipse[2][1],0.,len(Ring)))     #cent,phi,radii
    697698    data['ellipses'].append(ellipse[:]+('r',))
     
    702703    data['rings'] = []
    703704    if not data['calibrant']:
    704         print ('no calibration material selected')
     705        G2fil.G2Print ('Warning: no calibration material selected')
    705706        return True
    706707   
     
    715716            SGData = G2spc.SpcGroup(sg)[1]
    716717            hkl = G2pwd.getHKLpeak(dmin,SGData,A)
    717             print(hkl)
     718            G2fil.G2Print(hkl)
    718719            HKL += list(hkl)
    719720        else:
     
    724725    elcent,phi,radii = ellipse              #from fit of 1st ring
    725726    dsp = HKL[0][3]
    726     print ('1st ring: try %.4f'%(dsp))
     727    G2fil.G2Print ('1st ring: try %.4f'%(dsp))
    727728    if varyDict['dist']:
    728729        wave = data['wavelength']
     
    739740        tilt = npasind(np.sqrt(max(0.,1.-(radii[0]/radii[1])**2))*ctth)
    740741        if not tilt:
    741             print ('WARNING - selected ring was fitted as a circle')
    742             print (' - if detector was tilted we suggest you skip this ring - WARNING')
     742            G2fil.G2Print ('WARNING - selected ring was fitted as a circle')
     743            G2fil.G2Print (' - if detector was tilted we suggest you skip this ring - WARNING')
    743744    else:
    744745        tilt = data['tilt']
     
    763764        while fail:
    764765            dsp = HKL[i2][3]
    765             print ('2nd ring: try %.4f'%(dsp))
     766            G2fil.G2Print ('2nd ring: try %.4f'%(dsp))
    766767            tth = 2.0*asind(wave/(2.*dsp))
    767768            ellipsep = GetEllipse2(tth,0.,dist,centp,tilt,phi)
    768             print (fmt%('plus ellipse :',ellipsep[0][0],ellipsep[0][1],ellipsep[1],ellipsep[2][0],ellipsep[2][1]))
     769            G2fil.G2Print (fmt%('plus ellipse :',ellipsep[0][0],ellipsep[0][1],ellipsep[1],ellipsep[2][0],ellipsep[2][1]))
    769770            Ringp = makeRing(dsp,ellipsep,3,cutoff,scalex,scaley,G2frame.ImageZ)[0]
    770771            parmDict = {'dist':dist,'det-X':centp[0],'det-Y':centp[1],
     
    780781                chip = 1e6
    781782            ellipsem = GetEllipse2(tth,0.,dist,centm,-tilt,phi)
    782             print (fmt%('minus ellipse:',ellipsem[0][0],ellipsem[0][1],ellipsem[1],ellipsem[2][0],ellipsem[2][1]))
     783            G2fil.G2Print (fmt%('minus ellipse:',ellipsem[0][0],ellipsem[0][1],ellipsem[1],ellipsem[2][0],ellipsem[2][1]))
    783784            Ringm = makeRing(dsp,ellipsem,3,cutoff,scalex,scaley,G2frame.ImageZ)[0]
    784785            if len(Ringm) > 10:
     
    817818        tth = 2.0*asind(wave/(2.*dsp))
    818819        if tth+abs(data['tilt']) > 90.:
    819             print ('next line is a hyperbola - search stopped')
     820            G2fil.G2Print ('next line is a hyperbola - search stopped')
    820821            break
    821822        if debug:   print ('HKLD:'+str(H[:4])+'2-theta: %.4f'%(tth))
     
    845846    fullSize = len(G2frame.ImageZ)/scalex
    846847    if 2*radii[1] < .9*fullSize:
    847         print ('Are all usable rings (>25% visible) used? Try reducing Min ring I/Ib')
     848        G2fil.G2Print ('Are all usable rings (>25% visible) used? Try reducing Min ring I/Ib')
    848849    N = len(data['ellipses'])
    849850    if N > 2:
     
    858859        ellipse = GetEllipse(H[3],data)
    859860        data['ellipses'].append(copy.deepcopy(ellipse+('b',)))
    860     print ('calibration time = %.3f'%(time.time()-time0))
     861    G2fil.G2Print ('calibration time = %.3f'%(time.time()-time0))
    861862    G2plt.PlotImage(G2frame,newImage=True)       
    862863    return True
     
    971972    'Integrate an image; called from OnIntegrateAll and OnIntegrate in G2imgGUI'    #for q, log(q) bins need data['binType']
    972973    import histogram2d as h2d
    973     print ('Begin image integration; image range: %d %d'%(np.min(image),np.max(image)))
     974    G2fil.G2Print ('Begin image integration; image range: %d %d'%(np.min(image),np.max(image)))
    974975    CancelPressed = False
    975976    LUtth = np.array(data['IOtth'])
     
    10451046            times[3] += time.time()-t0
    10461047#            print('done block %d %d %d %d %d %d %d %d'%(iBlk,iBeg,iFin,jBlk,jBeg,jFin,np.min(Block),np.max(Block)))
    1047     print('End integration loops')
     1048    G2fil.G2Print('End integration loops')
    10481049    t0 = time.time()
    10491050#    H2 = np.array([tth for tth in np.linspace(lutth[0],lutth[1],numChans+1)])
     
    10741075        H0 /= np.array([G2pwd.Polarization(data['PolaVal'][0],H2[:-1],Azm=azm-90.)[0] for azm in (H1[:-1]+np.diff(H1)/2.)])
    10751076    times[4] += time.time()-t0
    1076     print ('Step times: \n apply masks  %8.3fs xy->th,azm   %8.3fs fill map     %8.3fs \
     1077    G2fil.G2Print ('Step times: \n apply masks  %8.3fs xy->th,azm   %8.3fs fill map     %8.3fs \
    10771078        \n binning      %8.3fs cleanup      %8.3fs'%(times[0],times[1],times[2],times[3],times[4]))
    1078     print ("Elapsed time:","%8.3fs"%(time.time()-tbeg))
    1079     print ('Integration complete')
     1079    G2fil.G2Print ("Elapsed time:","%8.3fs"%(time.time()-tbeg))
     1080    G2fil.G2Print ('Integration complete')
    10801081    if returnN:     #As requested by Steven Weigand
    10811082        return H0,H1,H2,NST,CancelPressed
     
    11321133            ring['Ivar'] = np.var(ringint)
    11331134            ring['covMat'] = covMat
    1134             print ('Variance in normalized ring intensity: %.3f'%(ring['Ivar']))
     1135            G2fil.G2Print ('Variance in normalized ring intensity: %.3f'%(ring['Ivar']))
    11351136    CalcStrSta(StrSta,Controls)
    11361137   
     
    11511152            ringint = np.array([float(Image[int(x*scalex),int(y*scaley)]) for y,x in np.array(ringxy)[:,:2]])
    11521153            ringint /= np.mean(ringint)
    1153             print (' %s %.3f %s %.3f %s %d'%('d-spacing',ring['Dcalc'],'sig(MRD):',np.sqrt(np.var(ringint)),'# points:',len(ringint)))
     1154            G2fil.G2Print (' %s %.3f %s %.3f %s %d'%('d-spacing',ring['Dcalc'],'sig(MRD):',np.sqrt(np.var(ringint)),'# points:',len(ringint)))
    11541155            RingsAI.append(np.array(zip(ringazm,ringint)).T)
    11551156    return RingsAI
     
    12981299def AutoSpotMasks(Image,Masks,Controls):
    12991300   
    1300     print ('auto spot search')
     1301    G2fil.G2Print ('auto spot search')
    13011302    nxy = 15
    13021303    rollImage = lambda rho,roll: np.roll(np.roll(rho,roll[0],axis=0),roll[1],axis=1)
     
    13211322    mags = magind[2]
    13221323    size2 = mags.shape[0]
    1323     print ('Initial search done: %d -->%d %.2fs'%(size1,size2,time.time()-time0))
     1324    G2fil.G2Print ('Initial search done: %d -->%d %.2fs'%(size1,size2,time.time()-time0))
    13241325    nx,ny = Image.shape
    13251326    ImMax = np.max(Image)
     
    13321333        minM = mult*np.max(mags)
    13331334        num = ma.count(ma.array(mags,mask=mags<=minM))
    1334         print('try',mult,minM,num)
     1335        G2fil.G2Print('try',mult,minM,num)
    13351336    minM = mult*np.max(mags)
    1336     print ('Find biggest spots:',mult,num,minM)
     1337    G2fil.G2Print ('Find biggest spots:',mult,num,minM)
    13371338    for i,mag in enumerate(mags):
    13381339        if mag > minM:
    13391340            if (nxy2 < indx[0][i] < nx-nxy2-1) and (nxy2 < indx[1][i] < ny-nxy2-1):
    1340 #                    print ('try:%d %d %d %.2f'%(i,indx[0][i],indx[1][i],mags[i]))
     1341#                    G2fil.G2Print ('try:%d %d %d %.2f'%(i,indx[0][i],indx[1][i],mags[i]))
    13411342                peak = FitImageSpots(Image,ImMax,[indx[1][i],indx[0][i]],pixelSize,nxy)
    13421343                if peak and not any(np.isnan(np.array(peak))):
    13431344                    peaks.append(peak)
    1344 #                    print (' Spot found: %s'%str(peak))
     1345#                    G2fil.G2Print (' Spot found: %s'%str(peak))
    13451346    peaks = G2mth.sortArray(G2mth.sortArray(peaks,1),0)
    13461347    Peaks = [peaks[0],]
     
    13501351        if (peak[0]-Peaks[-1][0])**2+(peak[1]-Peaks[-1][1])**2 > peak[2]*Peaks[-1][2] :
    13511352            Peaks.append(peak)
    1352 #            print (' Spot found: %s'%str(peak))
    1353     print ('Spots found: %d time %.2fs'%(len(Peaks),time.time()-time0))
     1353#            G2fil.G2Print (' Spot found: %s'%str(peak))
     1354    G2fil.G2Print ('Spots found: %d time %.2fs'%(len(Peaks),time.time()-time0))
    13541355    Masks['Points'] = Peaks
    13551356    return None
  • trunk/GSASIImpsubs.py

    r3866 r4021  
    3232GSASIIpath.SetVersionNumber("$Revision$")
    3333import GSASIIpwd as G2pwd
     34import GSASIIfiles as G2fil
    3435
    3536sind = lambda x: np.sin(x*np.pi/180.)
     
    5657    useMP = False
    5758    if not allowMP:
    58         print('Multiprocessing disabled')
     59        G2fil.G2Print('Multiprocessing disabled')
    5960        ncores = 0
    6061        return useMP,ncores
     
    6465        useMP = True
    6566    if useMP:
    66         print('Multiprocessing with {} cores enabled'.format(ncores))
     67        G2fil.G2Print('Multiprocessing with {} cores enabled'.format(ncores))
    6768    return useMP,ncores
    6869
  • trunk/GSASIIplot.py

    r4010 r4021  
    32003200                CalcLine = None
    32013201                BackLine = None
    3202                 DifLine = None
     3202                DifLine = [None]
    32033203                if G2frame.Weight:
    32043204                    Plot1.set_yscale("linear")                                                 
  • trunk/GSASIIpwd.py

    r4002 r4021  
    4444    import pydiffax as pyx
    4545except ImportError:
    46     print ('pydiffax is not available for this platform - under develpment')
     46    print ('pydiffax is not available for this platform')
     47import GSASIIfiles as G2fil
    4748
    4849   
     
    440441    parmDict,varyList = MakeParms(peaks)
    441442    if not len(varyList):
    442         print (' Nothing varied')
     443        G2fil.G2Print (' Nothing varied')
    443444        return newpeaks,None,None,None,None,None
    444445   
     
    505506    if showFit:
    506507        rms = Min(xstart)
    507         print('  Optimizing corrections to improve G(r) at low r')
     508        G2fil.G2Print('  Optimizing corrections to improve G(r) at low r')
    508509        if data['Sample Bkg.'].get('Refine',False):
    509510#            data['Flat Bkg'] = 0.
    510             print('  start: Ruland={:.3f}, Sample Bkg mult={:.3f} (RMS:{:.4f})'.format(
     511            G2fil.G2Print('  start: Ruland={:.3f}, Sample Bkg mult={:.3f} (RMS:{:.4f})'.format(
    511512                data['Ruland'],data['Sample Bkg.']['Mult'],rms))
    512513        else:
    513             print('  start: Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.4f})'.format(
     514            G2fil.G2Print('  start: Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.4f})'.format(
    514515                data['Flat Bkg'],data['BackRatio'],data['Ruland'],rms))
    515516    if data['Sample Bkg.'].get('Refine',False):
     
    526527            msg = 'Not Converged'
    527528        if data['Sample Bkg.'].get('Refine',False):
    528             print('  end:   Ruland={:.3f}, Sample Bkg mult={:.3f} (RMS:{:.4f}) *** {} ***\n'.format(
     529            G2fil.G2Print('  end:   Ruland={:.3f}, Sample Bkg mult={:.3f} (RMS:{:.4f}) *** {} ***\n'.format(
    529530                data['Ruland'],data['Sample Bkg.']['Mult'],res['fun'],msg))
    530531        else:
    531             print('  end:   Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f}) *** {} ***\n'.format(
     532            G2fil.G2Print('  end:   Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f}) *** {} ***\n'.format(
    532533                data['Flat Bkg'],data['BackRatio'],data['Ruland'],res['fun'],msg))
    533534    return res
     
    925926            break
    926927        except ValueError:
    927             print ('**** WARNING - backround peak '+str(iD)+' sigma is negative; fix & try again ****')
     928            G2fil.G2Print ('**** WARNING - backround peak '+str(iD)+' sigma is negative; fix & try again ****')
    928929            break
    929930    # fixed background from file
     
    931932        mult = fixedBkg.get('_fixedMult',0.0)
    932933        if len(fixedBkg.get('_fixedValues',[])) != len(yb):
    933             print('Lengths of backgrounds do not agree: yb={}, fixed={}'.format(
     934            G2fil.G2Print('Lengths of backgrounds do not agree: yb={}, fixed={}'.format(
    934935                len(yb),len(fixedBkg.get('_fixedValues',[]))))
    935936        elif mult:
     
    10631064            break
    10641065        except ValueError:
    1065             print ('**** WARNING - backround peak '+str(iD)+' sigma is negative; fix & try again ****')
     1066            G2fil.G2Print ('**** WARNING - backround peak '+str(iD)+' sigma is negative; fix & try again ****')
    10661067            break       
    10671068    return dydb,dyddb,dydpk
     
    16051606    varyList = insVary
    16061607    if not len(varyList):
    1607         print ('**** ERROR - nothing to refine! ****')
     1608        G2fil.G2Print ('**** ERROR - nothing to refine! ****')
    16081609        return False
    16091610    while True:
     
    16171618        Values2Dict(parmDict, varyList, result[0])
    16181619        GOF = chisq/(len(peakPos)-len(varyList))       #reduced chi^2
    1619         print ('Number of function calls: %d Number of observations: %d Number of parameters: %d'%(result[2]['nfev'],len(peakPos),len(varyList)))
    1620         print ('calib time = %8.3fs, %8.3fs/cycle'%(runtime,runtime/ncyc))
    1621         print ('chi**2 = %12.6g, reduced chi**2 = %6.2f'%(chisq,GOF))
     1620        G2fil.G2Print ('Number of function calls: %d Number of observations: %d Number of parameters: %d'%(result[2]['nfev'],len(peakPos),len(varyList)))
     1621        G2fil.G2Print ('calib time = %8.3fs, %8.3fs/cycle'%(runtime,runtime/ncyc))
     1622        G2fil.G2Print ('chi**2 = %12.6g, reduced chi**2 = %6.2f'%(chisq,GOF))
    16221623        try:
    16231624            sig = np.sqrt(np.diag(result[1])*GOF)
    16241625            if np.any(np.isnan(sig)):
    1625                 print ('*** Least squares aborted - some invalid esds possible ***')
     1626                G2fil.G2Print ('*** Least squares aborted - some invalid esds possible ***')
    16261627            break                   #refinement succeeded - finish up!
    16271628        except ValueError:          #result[1] is None on singular matrix
    1628             print ('**** Refinement failed - singular matrix ****')
     1629            G2fil.G2Print ('**** Refinement failed - singular matrix ****')
    16291630       
    16301631    sigDict = dict(zip(varyList,sig))
     
    19431944        Rvals['Rwp'] = np.sqrt(chisq/np.sum(w[xBeg:xFin]*(y+fixback)[xBeg:xFin]**2))*100.      #to %
    19441945        Rvals['GOF'] = chisq/(xFin-xBeg-len(varyList))       #reduced chi^2
    1945         print ('Number of function calls: %d Number of observations: %d Number of parameters: %d'%(result[2]['nfev'],xFin-xBeg,len(varyList)))
     1946        G2fil.G2Print ('Number of function calls: %d Number of observations: %d Number of parameters: %d'%(result[2]['nfev'],xFin-xBeg,len(varyList)))
    19461947        if ncyc:
    1947             print ('fitpeak time = %8.3fs, %8.3fs/cycle'%(runtime,runtime/ncyc))
    1948         print ('Rwp = %7.2f%%, chi**2 = %12.6g, reduced chi**2 = %6.2f'%(Rvals['Rwp'],chisq,Rvals['GOF']))
     1948            G2fil.G2Print ('fitpeak time = %8.3fs, %8.3fs/cycle'%(runtime,runtime/ncyc))
     1949        G2fil.G2Print ('Rwp = %7.2f%%, chi**2 = %12.6g, reduced chi**2 = %6.2f'%(Rvals['Rwp'],chisq,Rvals['GOF']))
    19491950        sig = [0]*len(varyList)
    19501951        if len(varyList) == 0: break  # if nothing was refined
     
    19521953            sig = np.sqrt(np.diag(result[1])*Rvals['GOF'])
    19531954            if np.any(np.isnan(sig)):
    1954                 print ('*** Least squares aborted - some invalid esds possible ***')
     1955                G2fil.G2Print ('*** Least squares aborted - some invalid esds possible ***')
    19551956            break                   #refinement succeeded - finish up!
    19561957        except ValueError:          #result[1] is None on singular matrix
    1957             print ('**** Refinement failed - singular matrix ****')
     1958            G2fil.G2Print ('**** Refinement failed - singular matrix ****')
    19581959            Ipvt = result[2]['ipvt']
    19591960            for i,ipvt in enumerate(Ipvt):
    19601961                if not np.sum(result[2]['fjac'],axis=1)[i]:
    1961                     print ('Removing parameter: '+varyList[ipvt-1])
     1962                    G2fil.G2Print ('Removing parameter: '+varyList[ipvt-1])
    19621963                    badVary.append(varyList[ipvt-1])
    19631964                    del(varyList[ipvt-1])
     
    19851986    if len(binsperFWHM):
    19861987        if min(binsperFWHM) < 1.:
    1987             print ('*** Warning: calculated peak widths are too narrow to refine profile coefficients ***')
     1988            G2fil.G2Print ('*** Warning: calculated peak widths are too narrow to refine profile coefficients ***')
    19881989            if 'T' in Inst['Type'][0]:
    1989                 print (' Manually increase sig-0, 1, or 2 in Instrument Parameters')
     1990                G2fil.G2Print (' Manually increase sig-0, 1, or 2 in Instrument Parameters')
    19901991            else:
    1991                 print (' Manually increase W in Instrument Parameters')
     1992                G2fil.G2Print (' Manually increase W in Instrument Parameters')
    19921993        elif min(binsperFWHM) < 4.:
    1993             print ('*** Warning: data binning yields too few data points across peak FWHM for reliable Rietveld refinement ***')
    1994             print ('*** recommended is 6-10; you have %.2f ***'%(min(binsperFWHM)))
     1994            G2fil.G2Print ('*** Warning: data binning yields too few data points across peak FWHM for reliable Rietveld refinement ***')
     1995            G2fil.G2Print ('*** recommended is 6-10; you have %.2f ***'%(min(binsperFWHM)))
    19951996    return sigDict,result,sig,Rvals,varyList,parmDict,fullvaryList,badVary
    19961997   
     
    20552056
    20562057def REFDRefine(Profile,ProfDict,Inst,Limits,Substances,data):
    2057     print ('fit REFD data by '+data['Minimizer']+' using %.2f%% data resolution'%(data['Resolution'][0]))
     2058    G2fil.G2Print ('fit REFD data by '+data['Minimizer']+' using %.2f%% data resolution'%(data['Resolution'][0]))
    20582059   
    20592060    class RandomDisplacementBounds(object):
     
    21142115            data['Scale'][0] = parmDict['Scale']
    21152116            line += ' esd: %.4g'%(sigDict['Scale'])                                                             
    2116         print (line)
     2117        G2fil.G2Print (line)
    21172118        line = ' Flat background: %15.4g'%(parmDict['FltBack'])
    21182119        if 'FltBack' in varyList:
    21192120            data['FltBack'][0] = parmDict['FltBack']
    21202121            line += ' esd: %15.3g'%(sigDict['FltBack'])
    2121         print (line)
     2122        G2fil.G2Print (line)
    21222123        for ilay,layer in enumerate(data['Layers']):
    21232124            name = layer['Name']
    2124             print (' Parameters for layer: %d %s'%(ilay,name))
     2125            G2fil.G2Print (' Parameters for layer: %d %s'%(ilay,name))
    21252126            cid = str(ilay)+';'
    21262127            line = ' '
     
    21362137                    if cid+parm in varyList:
    21372138                        line += ' esd: %.3g'%(sigDict[cid+parm])
    2138             print (line)
    2139             print (line2)
     2139            G2fil.G2Print (line)
     2140            G2fil.G2Print (line2)
    21402141   
    21412142    def calcREFD(values,Q,Io,wt,Qsig,parmDict,varyList):
     
    22162217            take_step = RandomDisplacementBounds(xyrng[0], xyrng[1])
    22172218            T0 = estimateT0(take_step)
    2218             print (' Estimated temperature: %.3g'%(T0))
     2219            G2fil.G2Print (' Estimated temperature: %.3g'%(T0))
    22192220            result = so.basinhopping(sumREFD,values,take_step=take_step,disp=True,T=T0,stepsize=Bfac,
    22202221                interval=20,niter=200,minimizer_kwargs={'method':'L-BFGS-B','bounds':bounds,
     
    22362237            ncalc = result[3]
    22372238            covM = []
    2238             print (' MC/SA final temperature: %.4g'%(result[2]))
     2239            G2fil.G2Print (' MC/SA final temperature: %.4g'%(result[2]))
    22392240        elif data['Minimizer'] == 'L-BFGS-B':
    22402241            result = so.minimize(sumREFD,values,method='L-BFGS-B',bounds=bounds,   #ftol=Ftol,
     
    22812282            covMatrix = []
    22822283        sigDict = dict(zip(varyList,sig))
    2283         print (' Results of reflectometry data modelling fit:')
    2284         print ('Number of function calls: %d Number of observations: %d Number of parameters: %d'%(ncalc,Ifin-Ibeg,len(varyList)))
    2285         print ('Rwp = %7.2f%%, chi**2 = %12.6g, reduced chi**2 = %6.2f'%(Rvals['Rwp'],chisq,Rvals['GOF']))
     2284        G2fil.G2Print (' Results of reflectometry data modelling fit:')
     2285        G2fil.G2Print ('Number of function calls: %d Number of observations: %d Number of parameters: %d'%(ncalc,Ifin-Ibeg,len(varyList)))
     2286        G2fil.G2Print ('Rwp = %7.2f%%, chi**2 = %12.6g, reduced chi**2 = %6.2f'%(Rvals['Rwp'],chisq,Rvals['GOF']))
    22862287        SetModelParms()
    22872288        return True,result,varyList,sig,Rvals,covMatrix,parmDict,''
    22882289    except (ValueError,TypeError):      #when bad LS refinement; covM missing or with nans
    2289         print (Msg)
     2290        G2fil.G2Print (Msg)
    22902291        return False,0,0,0,0,0,0,Msg
    22912292       
     
    24702471       
    24712472def makeRefdFFT(Limits,Profile):
    2472     print ('make fft')
     2473    G2fil.G2Print ('make fft')
    24732474    Q,Io = Profile[:2]
    24742475    Qmin = Limits[1][0]
     
    25352536        if 'bin' in name:
    25362537            DIFFaX = name+'/DIFFaX.exe'
    2537             print (' Execute '+DIFFaX)
     2538            G2fil.G2Print (' Execute '+DIFFaX)
    25382539            break
    25392540    # make form factor file that DIFFaX wants - atom types are GSASII style
     
    26542655            sumPx += p
    26552656        if sumPx != 1.0:    #this has to be picky since DIFFaX is.
    2656             print ('ERROR - Layer probabilities sum to %.3f DIFFaX will insist it = 1.0'%sumPx)
     2657            G2fil.G2Print ('ERROR - Layer probabilities sum to %.3f DIFFaX will insist it = 1.0'%sumPx)
    26572658            df.close()
    26582659            os.remove('data.sfc')
     
    26652666        subp.call(DIFFaX)
    26662667    except OSError:
    2667         print (' DIFFax.exe is not available for this platform - under development')
    2668     print (' DIFFaX time = %.2fs'%(time.time()-time0))
     2668        G2fil.G2Print('DIFFax.exe is not available for this platform',mode='warn')
     2669    G2fil.G2Print (' DIFFaX time = %.2fs'%(time.time()-time0))
    26692670    if os.path.exists('GSASII-DIFFaX.spc'):
    26702671        Xpat = np.loadtxt('GSASII-DIFFaX.spc').T
     
    28312832    time0 = time.time()
    28322833    pyx.pygetspc(controls,Nspec,spec)
    2833     print (' GETSPC time = %.2fs'%(time.time()-time0))
     2834    G2fil.G2Print (' GETSPC time = %.2fs'%(time.time()-time0))
    28342835    time0 = time.time()
    28352836    U = ateln2*inst['U'][1]/10000.
     
    28622863        profile[2][iBeg:iFin] = np.where(profile[1][iBeg:iFin]>0.,1./profile[1][iBeg:iFin],1.0)
    28632864    profile[5][iBeg:iFin] = profile[1][iBeg:iFin]-profile[3][iBeg:iFin]
    2864     print (' Broadening time = %.2fs'%(time.time()-time0))
     2865    G2fil.G2Print (' Broadening time = %.2fs'%(time.time()-time0))
    28652866   
    28662867def CalcStackingSADP(Layers,debug):
     
    28972898        iB += Nblk
    28982899    Layers['Sadp']['Img'] = Sapd
    2899     print (' GETSAD time = %.2fs'%(time.time()-time0))
     2900    G2fil.G2Print (' GETSAD time = %.2fs'%(time.time()-time0))
    29002901   
    29012902###############################################################################
     
    31873188    for i in range(100):
    31883189        getPeakProfile(parmDict1,xdata,varyList,bakType)
    3189     print ('100+6*Ka1-2 peaks=1200 peaks %.2f'%time.time()-time0)
     3190    G2fil.G2Print ('100+6*Ka1-2 peaks=1200 peaks %.2f'%time.time()-time0)
    31903191   
    31913192def test2(name,delt):
     
    32253226    for name,shft in [['pos',0.0001],['sig',0.01],['gam',0.0001],['shl',0.00005]]:
    32263227        test3(name,shft)
    3227     print ("OK")
     3228    G2fil.G2Print ("OK")
    32283229    plotter.StartEventLoop()
  • trunk/GSASIIscriptable.py

    r4015 r4021  
    800800npsind = lambda x: np.sin(x*np.pi/180.)
    801801
     802def SetPrintLevel(level):
     803    '''Set the level of output from calls to :func:`GSASIIfiles.G2Print`,
     804    which should be used in place of print() where possible. This is a
     805    wrapper for :func:`GSASIIfiles.G2SetPrintLevel` so that this routine is
     806    documented here.
     807   
     808    :param str level: a string used to set the print level, which may be
     809    'all', 'warn', 'error' or 'none'.
     810    Note that capitalization and extra letters in level are ignored, so
     811    'Warn', 'warnings', etc. will all set the mode to 'warn'
     812    '''
     813    G2fil.G2SetPrintLevel(level)
     814    global printLevel
     815    for mode in  'all', 'warn', 'error', 'none':
     816        if mode in level.lower():
     817            printLevel = mode
     818            return
     819       
    802820def LoadG2fil():
    803     """Setup GSAS-II importers. Delay importing this module, it is slow"""
     821    '''Setup GSAS-II importers.
     822    Delay importing this module when possible, it is slow.
     823    Multiple calls are not. Only the first does anything.
     824    '''
    804825    if len(Readers['Pwdr']) > 0: return
    805826    # initialize imports
     
    865886    # Let IOError be thrown if file does not exist
    866887    if not ospath.exists(ProjFile):
    867         print ('\n*** Error attempt to open project file that does not exist: \n    {}'.
     888        G2fil.G2Print ('\n*** Error attempt to open project file that does not exist: \n    {}'.
    868889                   format(ProjFile))
    869890        raise IOError('GPX file {} does not exist'.format(ProjFile))
     
    893914    finally:
    894915        file.close()
    895     print('gpx file saved as %s'%ProjFile)
     916    G2fil.G2Print('gpx file saved as %s'%ProjFile)
    896917
    897918# def ImportPowder(reader,filename):
     
    912933#     rd = rdclass.GSAS_ReaderClass()
    913934#     if not rd.scriptable:
    914 #         print(u'**** ERROR: '+reader+u' is not a scriptable reader')
     935#         G2fil.G2Print(u'**** ERROR: '+reader+u' is not a scriptable reader')
    915936#         return None
    916937#     rdlist = []
     
    929950#                     repeat = True
    930951#         return rdlist
    931 #     print(rd.errors)
     952#     G2fil.G2Print(rd.errors)
    932953#     return None
    933954
     
    11891210            if not rd.ContentsValidator(filename):
    11901211                # Report error
    1191                 print("Warning: File {} has a validation error, continuing".format(filename))
     1212                G2fil.G2Print("Warning: File {} has a validation error, continuing".format(filename))
    11921213            if len(rd.selections) > 1:
    11931214                raise G2ImportException("File {} has {} banks. Specify which bank to read with databank param."
     
    12111232                    repeat = rd.repeat
    12121233                else:
    1213                     if GSASIIpath.GetConfigValue('debug'): print("DBG_{} Reader failed to read {}".format(rd.formatName,filename))
     1234                    G2fil.G2Print("Warning: {} Reader failed to read {}".format(rd.formatName,filename))
    12141235            if rd_list:
    12151236                if rd.warnings:
    1216                     print("Read warning by", rd.formatName, "reader:",
    1217                           rd.warnings, file=sys.stderr)
     1237                    G2fil.G2Print("Read warning by", rd.formatName, "reader:",
     1238                          rd.warnings)
    12181239                elif bank is None:
    1219                     print("{} read by Reader {}"
     1240                    G2fil.G2Print("{} read by Reader {}"
    12201241                              .format(filename,rd.formatName))
    12211242                else:
    1222                     print("{} block # {} read by Reader {}"
     1243                    G2fil.G2Print("{} block # {} read by Reader {}"
    12231244                              .format(filename,bank,rd.formatName))
    12241245                return rd_list
     
    12911312    except ValueError:
    12921313        Iparm1, Iparm2 = load_iprms(instprm, reader, bank=bank)
    1293         print('Instrument parameters read:',reader.instmsg)
     1314        G2fil.G2Print('Instrument parameters read:',reader.instmsg)
    12941315    Ymin = np.min(reader.powderdata[1])
    12951316    Ymax = np.max(reader.powderdata[1])
     
    15301551        if filename is not None and newgpx is not None:
    15311552            raise G2ScriptException('Do not use filename and newgpx together')
    1532         elif newgpx is not None:
     1553        elif newgpx:
    15331554            filename = newgpx
    1534         if gpxfile is None:
     1555        if not gpxfile:
    15351556            filename = os.path.abspath(os.path.expanduser(filename))
    15361557            self.filename = filename
    15371558            self.data, self.names = make_empty_project(author=author, filename=filename)
    1538         elif isinstance(gpxfile, str): # TODO: create replacement for isinstance that checks if path exists
    1539                                        # filename is valid, etc.
    1540             if isinstance(filename, str):
    1541                 self.filename = os.path.abspath(os.path.expanduser(filename)) # both are defined
    1542             else:
    1543                 self.filename = os.path.abspath(os.path.expanduser(gpxfile))
     1559        elif os.path.exists(os.path.expanduser(gpxfile)):
    15441560            # TODO set author
    15451561            self.data, self.names = LoadDictFromProjFile(gpxfile)
    15461562            self.update_ids()
     1563            if filename:
     1564                filename = os.path.abspath(os.path.expanduser(filename))
     1565                dr = os.path.split(filename)[0]
     1566                if not os.path.exists(dr):
     1567                    raise Exception("Directory {} for filename/newgpx does not exist".format(dr))
     1568                self.filename = filename
     1569            else:
     1570                self.filename = os.path.abspath(os.path.expanduser(gpxfile))
    15471571        else:
    1548             raise ValueError("Not sure what to do with gpxfile")
     1572            raise ValueError("Not sure what to do with gpxfile {}. Does not exist?".format(gpxfile))
    15491573
    15501574    @classmethod
     
    16221646                                          [h.name for h in self.histograms()],bank=instbank)
    16231647        if histname in self.data:
    1624             print("Warning - redefining histogram", histname)
     1648            G2fil.G2Print("Warning - redefining histogram", histname)
    16251649        elif self.names[-1][0] == 'Phases':
    16261650            self.names.insert(-1, new_names)
     
    17051729                                                            [h.name for h in self.histograms()])
    17061730        if histname in self.data:
    1707             print("Warning - redefining histogram", histname)
     1731            G2fil.G2Print("Warning - redefining histogram", histname)
    17081732        elif self.names[-1][0] == 'Phases':
    17091733            self.names.insert(-1, new_names)
     
    18701894        errmsg, warnmsg = G2strIO.ReadCheckConstraints(self.filename)
    18711895        if errmsg:
    1872             print('Refinement error',errmsg)
     1896            G2fil.G2Print('Refinement error',errmsg)
    18731897            raise Exception('Constraint error')
    18741898        if warnmsg:
    1875             print(u'Conflict between refinment flag settings and constraints:\n'+
     1899            G2fil.G2Print(u'Warning: Conflict between refinment flag settings and constraints:\n'+
    18761900                  warnmsg+u'\nRefinement not possible')
    18771901            raise Exception('Constraint error')
     
    20742098        """
    20752099        return [G2PDF(self.data[i],i,self) for i in self._pdfs()]
     2100       
     2101    def copy_PDF(self, PDFobj, histogram):
     2102        '''Creates a PDF entry that can be used to compute a PDF
     2103        as a copy of settings in an existing PDF (:class:`G2PDF`)
     2104        object.
     2105        This places an entry in the project but :meth:`G2PDF.calculate`
     2106        must be used to actually perform the PDF computation.
     2107
     2108        :param str PDFobj: A :class:`G2PDF` object which may be
     2109          in a separate project.
     2110        :param histogram: A reference to a histogram,
     2111          which can be reference by object, name, or number.
     2112        :returns: A :class:`G2PDF` object for the PDF entry
     2113        '''
     2114        LoadG2fil()
     2115        PDFname = 'PDF ' + self.histogram(histogram).name[4:]
     2116        PDFdict = {'data':None}
     2117        for i in 'PDF Controls', 'PDF Peaks':
     2118            PDFdict[i] = copy.deepcopy(PDFobj[i])
     2119        self.names.append([PDFname]+['PDF Controls', 'PDF Peaks'])
     2120        self.data[PDFname] = PDFdict
     2121        for i in 'I(Q)','S(Q)','F(Q)','G(R)':
     2122            self.data[PDFname]['PDF Controls'][i] = []
     2123        G2fil.G2Print('Adding "{}" to project'.format(PDFname))
     2124        return G2PDF(self.data[PDFname], PDFname, self)
    20762125       
    20772126    def add_PDF(self, prmfile, histogram):
     
    21202169        self.names.append([PDFname]+['PDF Controls', 'PDF Peaks'])
    21212170        self.data[PDFname] = PDFdict
    2122         print('Adding "{}" to project'.format(PDFname))
     2171        G2fil.G2Print('Adding "{}" to project'.format(PDFname))
    21232172        return G2PDF(self.data[PDFname], PDFname, self)
    21242173
     
    24382487        for rd in readers:
    24392488            if rd.SciPy:        #was default read by scipy; needs 1 time fixes
    2440                 print('TODO: Image {} read by SciPy. Parameters likely need editing'.format(imagefile))
     2489                G2fil.G2Print('Warning: Image {} read by generic SciPy import. Image parameters likely wrong'.format(imagefile))
    24412490                #see this: G2IO.EditImageParms(self,rd.Data,rd.Comments,rd.Image,imagefile)
    24422491                rd.SciPy = False
     
    25642613            return self.data['Controls']['data']['Copy2Next']
    25652614        else:
    2566             print('Defined Controls:',self.data['Controls']['data'].keys())
     2615            G2fil.G2Print('Defined Controls:',self.data['Controls']['data'].keys())
    25672616            raise Exception('{} is an invalid control value'.format(control))
    25682617       
     
    27082757        missing = [i for i in varList if i not in self['Covariance']['data']['varyList']]
    27092758        if missing:
    2710             print('Variable(s) {} were not found in the varyList'.format(missing))
     2759            G2fil.G2Print('Warning: Variable(s) {} were not found in the varyList'.format(missing))
    27112760            return None
    27122761        vals = [self['Covariance']['data']['parmDict'][i] for i in varList]
     
    30483097            import matplotlib.pyplot as plt
    30493098        except ImportError:
    3050             print('Unable to import matplotlib, skipping plot')
     3099            G2fil.G2Print('Warning: Unable to import matplotlib, skipping plot')
    30513100            return
    30523101        data = self.data['data'][1]
     
    31963245        import GSASIImath as G2mth
    31973246        if (not dspace) + (not Q) + (not ttheta) != 2:
    3198             print('add_peak error: too many or no peak position(s) specified')
     3247            G2fil.G2Print('add_peak error: too many or no peak position(s) specified')
    31993248            return
    32003249        pos = ttheta
     
    32673316            File.write(item+':'+str(data[item][1])+'\n')
    32683317        File.close()
    3269         print ('Instrument parameters saved to: '+filename)
     3318        G2fil.G2Print ('Instrument parameters saved to: '+filename)
    32703319
    32713320    def LoadProfile(self,filename,bank=0):
     
    35973646        """
    35983647        if not self.data.get('Histograms',[]):
    3599             print("Error likely: Phase {} has no linked histograms".format(self.name))
     3648            G2fil.G2Print("Error likely: Phase {} has no linked histograms".format(self.name))
    36003649            return
    36013650           
     
    36063655                          if self._decodeHist(h) in self.data['Histograms']]   
    36073656        if not histograms:
    3608             print("Skipping HAP set for phase {}, no selected histograms".format(self.name))
     3657            G2fil.G2Print("Warning: Skipping HAP set for phase {}, no selected histograms".format(self.name))
    36093658            return
    36103659        for key, val in refs.items():
     
    37353784                    self.data['Histograms'][h]['Scale'][1] = bool(val)
    37363785            else:
    3737                 print(u'Unknown HAP key: '+key)
     3786                G2fil.G2Print(u'Warning: Unknown HAP key: '+key)
    37383787
    37393788    def clear_HAP_refinements(self, refs, histograms='all'):
     
    37993848                        self.data['Histograms'][h]['Scale'][1] = False
    38003849                else:
    3801                     print(u'Unknown HAP key: '+key)
     3850                    G2fil.G2Print(u'Warning: Unknown HAP key: '+key)
    38023851
    38033852    def _decodeHist(self,hist):
     
    38663915                del copydict[item]
    38673916            else:
    3868                 print('items in HAP dict are: {}'.format(
     3917                G2fil.G2Print('items in HAP dict are: {}'.format(
    38693918                    list(self.data['Histograms'][sourcehist])))
    38703919                raise Exception('HAP skip list entry {} invalid'.format(item))
     
    38743923                    del copydict[item]
    38753924
    3876         print('Copying item(s) {} from histogram {}'.format(list(copydict.keys()),sourcehist))
    3877         print(' to histogram(s) {}'.format([self._decodeHist(h) for h in targethistlist]))
     3925        G2fil.G2Print('Copying item(s) {} from histogram {}'.format(list(copydict.keys()),sourcehist))
     3926        G2fil.G2Print(' to histogram(s) {}'.format([self._decodeHist(h) for h in targethistlist]))
    38783927        for h in targethistlist:
    38793928            h = self._decodeHist(h)
    38803929            if h not in self.data['Histograms']:
    3881                 print('Unexpected Warning: histogram {} not in phase {}'.format(h,self.name))
     3930                G2fil.G2Print('Unexpected Warning: histogram {} not in phase {}'.format(h,self.name))
    38823931                continue
    38833932            self.data['Histograms'][h].update(copy.deepcopy(copydict))
     
    39243973                del copydict[item]
    39253974            else:
    3926                 print('items in HAP dict are: {}'.format(
     3975                G2fil.G2Print('items in HAP dict are: {}'.format(
    39273976                    list(self.data['Histograms'][sourcehist])))
    39283977                raise Exception('HAP skip list entry {} invalid'.format(item))
     
    39363985            h = self._decodeHist(h)
    39373986            if h not in self.data['Histograms']:
    3938                 print('Warning: histogram {} not in phase {}'.format(h,self.name))
     3987                G2fil.G2Print('Warning: histogram {} not in phase {}'.format(h,self.name))
    39393988                continue
    39403989            if first:
     
    39423991                if 'HStrain' in self.data['Histograms'][h] and 'HStrain' in copydict:
    39433992                    if len(copydict['HStrain'][0]) != len(self.data['Histograms'][h]['HStrain'][0]):
    3944                         print('HStrain has differing numbers of terms. Input: {}, phase {}: {}'.
     3993                        G2fil.G2Print('Error: HStrain has differing numbers of terms. Input: {}, phase {}: {}'.
    39453994                                  format(len(copydict['HStrain'][0]),
    39463995                                        self.name,len(self.data['Histograms'][h]['HStrain'][0])))
    39473996                        raise Exception('HStrain has differing numbers of terms.')
    39483997            self.data['Histograms'][h].update(copy.deepcopy(copydict))           
    3949         print('Copied item(s) {} from dict'.format(list(copydict.keys())))
    3950         print(' to histogram(s) {}'.format([self._decodeHist(h) for h in targethistlist]))
     3998        G2fil.G2Print('Copied item(s) {} from dict'.format(list(copydict.keys())))
     3999        G2fil.G2Print(' to histogram(s) {}'.format([self._decodeHist(h) for h in targethistlist]))
    39514000
    39524001class G2SeqRefRes(G2ObjectWrapper):
     
    41804229            seqData,histData = self.RefData(hist)
    41814230        except:
    4182             print('Histogram {} not found in the sequential fit'.format(hist))
     4231            G2fil.G2Print('Warning: Histogram {} not found in the sequential fit'.format(hist))
    41834232            return
    41844233        missing = [i for i in varList if i not in seqData['varyList']]
    41854234        if missing:
    4186             print('Variable(s) {} were not found in the varyList'.format(missing))
     4235            G2fil.G2Print('Warning: Variable(s) {} were not found in the varyList'.format(missing))
    41874236            return None
    41884237        vals = [seqData['parmDict'][i] for i in varList]
     
    42914340        self.data['PDF Controls']['Form Vol'] = max(10.0,sumVol)
    42924341       
    4293     def calculate(self):
     4342    def calculate(self,xydata=None,limits=None,inst=None):
    42944343        '''Compute the PDF using the current parameters. Results are set
    4295         in the PDF object arrays (self.data['PDF Controls']['G(R)'] etc.)
     4344        in the PDF object arrays (self.data['PDF Controls']['G(R)'] etc.).
     4345        Note that if ``xydata``, is specified, the background histograms(s)
     4346        will not be accessed from the project file associated with the current
     4347        PDF entry. If ``limits`` and ``inst`` are both specified, no histograms
     4348        need be in the current project. However, the self.data['PDF Controls']
     4349        sections ('Sample', 'Sample Bkg.','Container Bkg.') must be 
     4350        non-blank for the corresponding items to be used from``xydata``.
     4351
     4352        :param dict xydata: an array containing the Sample's I vs Q, and
     4353          any or none of the Sample Background, the Container scattering and
     4354          the Container Background. If xydata is None (default), the values are
     4355          taken from histograms, as named in the PDF's self.data['PDF Controls']
     4356          entries with keys 'Sample', 'Sample Bkg.','Container Bkg.' &
     4357          'Container'.
     4358        :param list limits: upper and lower Q values to be used for PDF
     4359          computation. If None (default), the values are
     4360          taken from the Sample histogram's .data['Limits'][1] values.
     4361        :param dict inst: The Sample histogram's instrument parameters
     4362          to be used for PDF computation. If None (default), the values are
     4363          taken from the Sample histogram's .data['Instrument Parameters'][0]
     4364          values.
    42964365        '''
    42974366        data = self.data['PDF Controls']
    4298         xydata = {}
    4299         for key in 'Sample Bkg.','Container Bkg.','Container','Sample':
    4300             name = data[key]['Name'].strip()
    4301             if name:
    4302                 xydata[key] = self.proj.histogram(name).data['data']
    4303                 if key != 'Sample': continue
    4304                 limits = self.proj.histogram(name).data['Limits'][1]
    4305                 inst = self.proj.histogram(name).data['Instrument Parameters'][0]
     4367        if xydata is None:
     4368            xydata = {}
     4369            for key in 'Sample Bkg.','Container Bkg.','Container','Sample':
     4370                name = data[key]['Name'].strip()
     4371                if name:
     4372                    xydata[key] = self.proj.histogram(name).data['data']
     4373        if limits is None:
     4374            name = data['Sample']['Name'].strip()
     4375            limits = self.proj.histogram(name).data['Limits'][1]
     4376        if inst is None:
     4377            name = data['Sample']['Name'].strip()
     4378            inst = self.proj.histogram(name).data['Instrument Parameters'][0]
    43064379        G2pwd.CalcPDF(data,inst,limits,xydata)
    43074380        data['I(Q)'] = xydata['IofQ']
     
    43104383        data['G(R)'] = xydata['GofR']
    43114384
    4312     def optimize(self,showFit=True,maxCycles=5):
     4385    def optimize(self,showFit=True,maxCycles=5,
     4386                     xydata=None,limits=None,inst=None):
    43134387        '''Optimize the low R portion of G(R) to minimize selected
    43144388        parameters. Note that this updates the parameters in the settings
     
    43244398        :returns: the result from the optimizer as True or False, depending
    43254399          on if the refinement converged.
     4400        :param dict xydata: an array containing the Sample's I vs Q, and
     4401          any or none of the Sample Background, the Container scattering and
     4402          the Container Background. If xydata is None (default), the values are
     4403          taken from histograms, as named in the PDF's self.data['PDF Controls']
     4404          entries with keys 'Sample', 'Sample Bkg.','Container Bkg.' &
     4405          'Container'.
     4406        :param list limits: upper and lower Q values to be used for PDF
     4407          computation. If None (default), the values are
     4408          taken from the Sample histogram's .data['Limits'][1] values.
     4409        :param dict inst: The Sample histogram's instrument parameters
     4410          to be used for PDF computation. If None (default), the values are
     4411          taken from the Sample histogram's .data['Instrument Parameters'][0]
     4412          values.
    43264413        '''
    43274414        data = self.data['PDF Controls']
    4328         xydata = {}
    4329         for key in 'Sample Bkg.','Container Bkg.','Container','Sample':
    4330             name = data[key]['Name'].strip()
    4331             if name:
    4332                 xydata[key] = self.proj.histogram(name).data['data']
    4333                 if key != 'Sample': continue
    4334                 limits = self.proj.histogram(name).data['Limits'][1]
    4335                 inst = self.proj.histogram(name).data['Instrument Parameters'][0]
     4415        if xydata is None:
     4416            xydata = {}
     4417            for key in 'Sample Bkg.','Container Bkg.','Container','Sample':
     4418                name = data[key]['Name'].strip()
     4419                if name:
     4420                    xydata[key] = self.proj.histogram(name).data['data']
     4421        if limits is None:
     4422            name = data['Sample']['Name'].strip()
     4423            limits = self.proj.histogram(name).data['Limits'][1]
     4424        if inst is None:
     4425            name = data['Sample']['Name'].strip()
     4426            inst = self.proj.histogram(name).data['Instrument Parameters'][0]
     4427
    43364428        res = G2pwd.OptimizePDF(data,xydata,limits,inst,showFit,maxCycles)
    43374429        return res['success']
     
    44354527            if arg in self.ControlList[typ]: break
    44364528        else:
    4437             print('Allowed args:\n',[nam for nam,typ in self.findControl('')])
     4529            G2fil.G2Print('Allowed args:\n',[nam for nam,typ in self.findControl('')])
    44384530            raise Exception('arg {} not defined in G2Image.setControl'
    44394531                                .format(arg))
     
    44684560        if arg in self.data['Image Controls']:
    44694561            return self.data['Image Controls'][arg]
    4470         print(self.findControl(''))
     4562        G2fil.G2Print(self.findControl(''))
    44714563        raise Exception('arg {} not defined in G2Image.getControl'.format(arg))
    44724564
     
    45054597            self.data['Image Controls']['calibrant'] = calib
    45064598            return
    4507         print('Calibrant {} is not valid. Valid calibrants'.format(calib))
     4599        G2fil.G2Print('Calibrant {} is not valid. Valid calibrants'.format(calib))
    45084600        for i in calFile.Calibrants.keys():
    4509             if i: print('\t"{}"'.format(i))
     4601            if i: G2fil.G2Print('\t"{}"'.format(i))
    45104602       
    45114603    def setControlFile(self,typ,imageRef,mult=None):
     
    45304622            #key = 'Gain map'
    45314623            if mult is not None:
    4532                 print('Ignoring multiplier for Gain map')
     4624                G2fil.G2Print('Warning: Ignoring multiplier for Gain map')
    45334625            mult = None
    45344626        else:
     
    45544646            File.close()
    45554647            G2fil.LoadControls(Slines,self.data['Image Controls'])
    4556             print('file {} read into {}'.format(filename,self.name))
     4648            G2fil.G2Print('file {} read into {}'.format(filename,self.name))
    45574649        elif imgDict:
    45584650            self.data['Image Controls'].update(imgDict)
    4559             print('Image controls set')
     4651            G2fil.G2Print('Image controls set')
    45604652        else:
    45614653            raise Exception("loadControls called without imgDict or filename specified")
     
    45684660        '''
    45694661        G2fil.WriteControls(filename,self.data['Image Controls'])
    4570         print('file {} written from {}'.format(filename,self.name))
    4571 
     4662        G2fil.G2Print('file {} written from {}'.format(filename,self.name))
     4663
     4664    def getControls(self,clean=False):
     4665        '''returns current Image Controls as a dict
     4666
     4667        :param bool clean: causes the calbration information to be deleted
     4668        '''
     4669        ImageControls = copy.deepcopy(self.data['Image Controls'])
     4670        if clean:
     4671            ImageControls['showLines'] = True
     4672            ImageControls['ring'] = []
     4673            ImageControls['rings'] = []
     4674            ImageControls['ellipses'] = []
     4675            ImageControls['setDefault'] = False
     4676            for i in 'range','size','GonioAngles':
     4677                if i in ImageControls: del ImageControls[i]
     4678        return ImageControls
     4679   
     4680    def setControls(self,controlsDict):
     4681        '''uses dict from :meth:`getControls` to set Image Controls for current image
     4682        '''
     4683        self.data['Image Controls'].update(copy.deepcopy(controlsDict))
     4684   
     4685   
    45724686    def loadMasks(self,filename,ignoreThreshold=False):
    45734687        '''load masks from a .immask file
     
    45804694        '''
    45814695        G2fil.readMasks(filename,self.data['Masks'],ignoreThreshold)
    4582         print('file {} read into {}'.format(filename,self.name))
     4696        G2fil.G2Print('file {} read into {}'.format(filename,self.name))
     4697
     4698    def initMasks(self):
     4699        '''Initialize Masks, including resetting the Thresholds values
     4700        '''
     4701        self.data['Masks'] = {'Points':[],'Rings':[],'Arcs':[],'Polygons':[],'Frames':[]}
     4702        ImageZ = _getCorrImage(Readers['Image'],self.proj,self)
     4703        Imin = max(0.,np.min(ImageZ))
     4704        Imax = np.max(ImageZ)
     4705        self.data['Masks']['Thresholds'] = [(0,Imax),[Imin,Imax]]
     4706       
     4707    def getMasks(self):
     4708        '''load masks from an IMG tree entry
     4709        '''
     4710        return self.data['Masks']
     4711       
     4712    def setMasks(self,maskDict,resetThresholds=False):
     4713        '''load masks dict (from :meth:`getMasks`) into current IMG record
     4714
     4715        :param dict maskDict: specifies a dict with image parameters
     4716        :param bool resetThresholds: If True, Threshold Masks in the
     4717          dict are ignored. The default is False which means Threshold
     4718          Masks are retained.
     4719        '''
     4720        self.data['Masks'] = copy.deepcopy(maskDict)
     4721        if resetThresholds:
     4722            ImageZ = _getCorrImage(Readers['Image'],self.proj,self)
     4723            Imin = max(0.,np.min(ImageZ))
     4724            Imax = np.max(ImageZ)
     4725            self.data['Masks']['Thresholds'] [(0,Imax),[Imin,Imax]]
    45834726       
    45844727    def getVary(self,*args):
     
    47804923            for j in self.proj.names:
    47814924                if j[0] == Aname:
    4782                     print('Replacing "{}" in project'.format(Aname))
     4925                    G2fil.G2Print('Replacing "{}" in project'.format(Aname))
    47834926                    break
    47844927            else:
    4785                 print('Adding "{}" to project'.format(Aname))
     4928                G2fil.G2Print('Adding "{}" to project'.format(Aname))
    47864929                self.proj.names.append([Aname]+
    47874930                        [u'Comments',u'Limits',u'Background',u'Instrument Parameters',
     
    48344977    if args.histograms:
    48354978        for h,i in zip(args.histograms,args.iparams):
    4836             print("Adding histogram from",h,"with instparm ",i)
     4979            G2fil.G2Print("Adding histogram from",h,"with instparm ",i)
    48374980            hist_objs.append(proj.add_powder_histogram(h, i))
    48384981
    48394982    if args.phases:
    48404983        for p in args.phases:
    4841             print("Adding phase from",p)
     4984            G2fil.G2Print("Adding phase from",p)
    48424985            proj.add_phase(p, histograms=hist_objs)
    4843         print('Linking phase(s) to histogram(s):')
     4986        G2fil.G2Print('Linking phase(s) to histogram(s):')
    48444987        for h in hist_objs:
    4845             print ('   '+h.name)
     4988            G2fil.G2Print ('   '+h.name)
    48464989
    48474990    proj.save()
     
    48895032    if args.histograms:
    48905033        for h,i in zip(args.histograms,args.iparams):
    4891             print("Adding histogram from",h,"with instparm ",i)
     5034            G2fil.G2Print("Adding histogram from",h,"with instparm ",i)
    48925035            proj.add_powder_histogram(h, i, fmthint=args.histogramformat)
    48935036
     
    48995042
    49005043        for p in args.phases:
    4901             print("Adding phase from",p)
     5044            G2fil.G2Print("Adding phase from",p)
    49025045            proj.add_phase(p, histograms=histlist, fmthint=args.phaseformat)
    49035046           
    49045047        if not args.histlist:
    4905             print('Linking phase(s) to all histogram(s)')
     5048            G2fil.G2Print('Linking phase(s) to all histogram(s)')
    49065049        else:
    4907             print('Linking phase(s) to histogram(s):')
     5050            G2fil.G2Print('Linking phase(s) to histogram(s):')
    49085051            for h in histlist:
    4909                 print ('   '+h.name)
    4910 
     5052                G2fil.G2Print('   '+h.name)
    49115053    proj.save()
    49125054
  • trunk/GSASIIstrIO.py

    r3925 r4021  
    3939import GSASIImapvars as G2mv
    4040import GSASIImath as G2mth
     41import GSASIIfiles as G2fil
    4142
    4243sind = lambda x: np.sin(x*np.pi/180.)
     
    118119        pass
    119120    except Exception as msg:
    120         print('Read Error:',msg)
     121        G2fil.G2Print('Read Error:',msg)
    121122        raise Exception("Error reading file "+str(GPXfile)+". This is not a GSAS-II .gpx file")
    122123    finally:
     
    134135    pos = gpxIndex.get('Controls')
    135136    if pos is None:
    136         print('Warning: Controls not found in gpx file {}'.format(GPXfile))
     137        G2fil.G2Print('Warning: Controls not found in gpx file {}'.format(GPXfile))
    137138        return Controls
    138139    fp = open(GPXfile,'rb')
     
    163164    constDict,fixedList,ignored = ProcessConstraints(constList)
    164165    if ignored:
    165         print ('{} Constraints were rejected. Was a constrained phase, histogram or atom deleted?'.format(ignored))
     166        G2fil.G2Print ('Warning: {} Constraints were rejected. Was a constrained phase, histogram or atom deleted?'.format(ignored))
    166167    return constDict,fixedList
    167168   
     
    285286    if errmsg:
    286287        # print some diagnostic info on the constraints
    287         print('Error in constraints:\n'+errmsg+
     288        G2fil.G2Print('Error in constraints:\n'+errmsg+
    288289              '\nRefinement not possible due to conflict in constraints, see below:\n')
    289         print (G2mv.VarRemapShow(varyList,True))
     290        G2fil.G2Print(G2mv.VarRemapShow(varyList,True),mode='error')
    290291    return errmsg, warnmsg
    291292   
     
    508509                    except KeyError: # would happen if a referenced histogram were
    509510                        # renamed or deleted
    510                         print('For phase "'+phase+
     511                        G2fil.G2Print('Warning: For phase "'+phase+
    511512                              '" unresolved reference to histogram "'+hist+'"')
    512513    # load the fix background info into the histograms
     
    527528                h['_fixedMult'],h['_fixedVary'] = fixedBkg[1:]
    528529            except KeyError: # would happen if a referenced histogram were renamed or deleted
    529                 print('For hist "{}" unresolved background reference to hist "{}"'
     530                G2fil.G2Print('Warning: For hist "{}" unresolved background reference to hist "{}"'
    530531                          .format(hist,fixedBkg[0]))
    531532    G2obj.IndexAllIds(Histograms=Histograms,Phases=Phases)
     
    596597    import distutils.file_util as dfu
    597598    GPXback = GPXBackup(GPXfile,makeBack)
    598     print ('Read from file:'+GPXback)
    599     print ('Save to file  :'+GPXfile)
     599    G2fil.G2Print ('Read from file:'+GPXback)
     600    G2fil.G2Print ('Save to file  :'+GPXfile)
    600601    infile = open(GPXback,'rb')
    601602    outfile = open(GPXfile,'wb')
     
    636637            cPickle.dump(data,outfile,1)
    637638        except AttributeError:
    638             print ('ERROR - bad data in least squares result')
     639            G2fil.G2Print ('ERROR - bad data in least squares result')
    639640            infile.close()
    640641            outfile.close()
    641642            dfu.copy_file(GPXback,GPXfile)
    642             print ('GPX file save failed - old version retained')
     643            G2fil.G2Print ('GPX file save failed - old version retained',mode='error')
    643644            return
    644645           
    645     print ('GPX file save successful')
     646    G2fil.G2Print ('GPX file save successful')
    646647   
    647648def GetSeqResult(GPXfile):
     
    764765    '''
    765766    GPXback = GPXBackup(GPXfile)
    766     print ('Read from file:'+GPXback)
    767     print ('Save to file  :'+GPXfile)
     767    G2fil.G2Print ('Read from file:'+GPXback)
     768    G2fil.G2Print ('Save to file  :'+GPXfile)
    768769    GPXphase = os.path.splitext(GPXfile)[0]+'.seqPhase'
    769770    fp = open(GPXphase,'rb')
     
    813814            hdata = cPickleLoad(hist)
    814815            if data[0][0] != hdata[0][0]:
    815                 print('Error! Updating {} with {}'.format(data[0][0],hdata[0][0]))
     816                G2fil.G2Print('Error! Updating {} with {}'.format(data[0][0],hdata[0][0]))
    816817            data[0] = hdata[0]
    817818            xferItems = ['Background','Instrument Parameters','Sample Parameters','Reflection Lists']
     
    828829        os.remove(GPXphase)
    829830    except:
    830         print('Warning: unable to delete {}'.format(GPXphase))
     831        G2fil.G2Print('Warning: unable to delete {}'.format(GPXphase))
    831832    try:
    832833        os.remove(GPXhist)
    833834    except:
    834         print('Warning: unable to delete {}'.format(GPXhist))
    835     print ('GPX file merge completed')
     835        G2fil.G2Print('Warning: unable to delete {}'.format(GPXhist))
     836    G2fil.G2Print ('GPX file merge completed')
    836837
    837838#==============================================================================
     
    32783279            Inst = Histogram['Instrument Parameters']        #TODO ? ignores tabulated alp,bet & delt for TOF
    32793280            if 'T' in Type and len(Inst[1]):    #patch -  back-to-back exponential contribution to TOF line shape is removed
    3280                 print ('Warning: tabulated profile coefficients are ignored')
     3281                G2fil.G2Print ('Warning: tabulated profile coefficients are ignored')
    32813282            Type,instDict,insVary = GetInstParms(hId,Inst[0])
    32823283            controlDict[pfx+'histType'] = Type
  • trunk/GSASIIstrMain.py

    r4009 r4021  
    3636import GSASIIstrMath as G2stMth
    3737import GSASIIobj as G2obj
     38import GSASIIfiles as G2fil
    3839
    3940sind = lambda x: np.sin(x*np.pi/180.)
     
    129130            IfOK = False
    130131            covMatrix = []
    131             print ('**** Refinement failed - singular matrix ****')
     132            G2fil.G2Print ('Warning: **** Refinement failed - singular matrix ****')
    132133            if 'Hessian' in Controls['deriv type']:
    133134                num = len(varyList)-1
    134135                for i,val in enumerate(np.flipud(result[2]['psing'])):
    135136                    if val:
    136                         print ('Bad parameter: '+varyList[num-i])
     137                        G2fil.G2Print('Bad parameter: '+varyList[num-i],mode='warn')
    137138            else:
    138139                Ipvt = result[2]['ipvt']
    139140                for i,ipvt in enumerate(Ipvt):
    140141                    if not np.sum(result[2]['fjac'],axis=1)[i]:
    141                         print ('Bad parameter: '+varyList[ipvt-1])
     142                        G2fil.G2Print('Bad parameter: '+varyList[ipvt-1],mode='warn')
    142143            break
    143144        IfOK = True
     
    146147            sig = np.sqrt(np.diag(covMatrix))
    147148            if np.any(np.isnan(sig)) or not sig.shape:
    148                 print ('*** Least squares aborted - some invalid esds possible ***')
     149                G2fil.G2Print ('*** Least squares aborted - some invalid esds possible ***',mode='error')
    149150#            table = dict(zip(varyList,zip(values,result[0],(result[0]-values)/sig)))
    150151#            for item in table: print item,table[item]               #useful debug - are things shifting?
     
    155156                covMatrix = []
    156157                break
    157             print ('**** Refinement failed - singular matrix ****')
     158            G2fil.G2Print ('**** Refinement failed - singular matrix ****',mode='error')
    158159            if 'Hessian' in Controls['deriv type']:
    159160                if result[1] is None:
     
    165166                for i,val in enumerate(np.flipud(result[2]['psing'])):
    166167                    if val:
    167                         print ('Removing parameter: '+varyList[num-i])
     168                        G2fil.G2Print ('Removing parameter: '+varyList[num-i])
    168169                        del(varyList[num-i])
    169170            else:
     
    171172                for i,ipvt in enumerate(Ipvt):
    172173                    if not np.sum(result[2]['fjac'],axis=1)[i]:
    173                         print ('Removing parameter: '+varyList[ipvt-1])
     174                        G2fil.G2Print ('Removing parameter: '+varyList[ipvt-1])
    174175                        del(varyList[ipvt-1])
    175176                        break
     
    198199    Histograms,Phases = G2stIO.GetUsedHistogramsAndPhases(GPXfile)
    199200    if not Phases:
    200         print (' *** ERROR - you have no phases to refine! ***')
    201         print (' *** Refine aborted ***')
     201        G2fil.G2Print (' *** ERROR - you have no phases to refine! ***')
     202        G2fil.G2Print (' *** Refine aborted ***')
    202203        return False,'No phases'
    203204    if not Histograms:
    204         print (' *** ERROR - you have no data to refine with! ***')
    205         print (' *** Refine aborted ***')
     205        G2fil.G2Print (' *** ERROR - you have no data to refine with! ***')
     206        G2fil.G2Print (' *** Refine aborted ***')
    206207        return False,'No data'
    207208    rigidbodyDict = G2stIO.GetRigidBodies(GPXfile)
     
    240241        #print 'IndependentVars',G2mv.GetIndependentVars()
    241242    except G2mv.ConstraintException:
    242         print (' *** ERROR - your constraints are internally inconsistent ***')
     243        G2fil.G2Print (' *** ERROR - your constraints are internally inconsistent ***')
    243244        #errmsg, warnmsg = G2mv.CheckConstraints(varyList,constrDict,fixedList)
    244245        #print 'Errors',errmsg
     
    274275            G2stIO.SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,rigidbodyDict,covData,makeBack)
    275276            printFile.close()
    276             print (' Refinement results are in file: '+ospath.splitext(GPXfile)[0]+'.lst')
    277             print (' ***** Refinement successful *****')
     277            G2fil.G2Print (' Refinement results are in file: '+ospath.splitext(GPXfile)[0]+'.lst')
     278            G2fil.G2Print (' ***** Refinement successful *****')
    278279        else:
    279             print ('****ERROR - Refinement failed')
     280            G2fil.G2Print ('****ERROR - Refinement failed')
    280281            raise G2obj.G2Exception('****ERROR - Refinement failed')
    281282#    except G2obj.G2Exception(Msg):
     
    331332
    332333    printFile = open(ospath.splitext(GPXfile)[0]+'.lst','w')
    333     print ('Starting Sequential Refinement')
     334    G2fil.G2Print ('Starting Sequential Refinement')
    334335    G2stIO.ShowBanner(printFile)
    335336    Controls = G2stIO.GetControls(GPXfile)
     
    338339    Histograms,Phases = G2stIO.GetUsedHistogramsAndPhases(GPXfile)
    339340    if not Phases:
    340         print (' *** ERROR - you have no phases to refine! ***')
    341         print (' *** Refine aborted ***')
     341        G2fil.G2Print (' *** ERROR - you have no phases to refine! ***')
     342        G2fil.G2Print (' *** Refine aborted ***')
    342343        return False,'No phases'
    343344    if not Histograms:
    344         print (' *** ERROR - you have no data to refine with! ***')
    345         print (' *** Refine aborted ***')
     345        G2fil.G2Print (' *** ERROR - you have no data to refine with! ***')
     346        G2fil.G2Print (' *** Refine aborted ***')
    346347        return False,'No data'
    347348    rigidbodyDict = G2stIO.GetRigidBodies(GPXfile)
     
    352353    for item in phaseVary:
    353354        if '::A0' in item:
    354             print ('**** WARNING - lattice parameters should not be refined in a sequential refinement ****')
    355             print ('****           instead use the Dij parameters for each powder histogram            ****')
     355            G2fil.G2Print ('**** WARNING - lattice parameters should not be refined in a sequential refinement ****')
     356            G2fil.G2Print ('****           instead use the Dij parameters for each powder histogram            ****')
    356357            return False,'Lattice parameter refinement error - see console message'
    357358        if '::C(' in item:
    358             print ('**** WARNING - phase texture parameters should not be refined in a sequential refinement ****')
    359             print ('****           instead use the C(L,N) parameters for each powder histogram               ****')
     359            G2fil.G2Print ('**** WARNING - phase texture parameters should not be refined in a sequential refinement ****')
     360            G2fil.G2Print ('****           instead use the C(L,N) parameters for each powder histogram               ****')
    360361            return False,'Phase texture refinement error - see console message'
    361362    if 'Seq Data' in Controls:
     
    373374    for ihst,histogram in enumerate(histNames):
    374375        if GSASIIpath.GetConfigValue('Show_timing'): t1 = time.time()
    375         print('\nRefining with '+str(histogram))
     376        G2fil.G2Print('\nRefining with '+str(histogram))
    376377        ifPrint = False
    377378        if dlg:
     
    385386        calcControls['maxSSwave'] = maxSSwave
    386387        if histogram not in Histograms:
    387             print("Error: not found!")
     388            G2fil.G2Print("Error: not found!")
    388389            continue
    389390    #TODO - implement "Fix FXU" for seq refinement here - done?
     
    434435            constraintInfo = (groups,parmlist,constrDict,fixedList,ihst)
    435436        except G2mv.ConstraintException:
    436             print (' *** ERROR - your constraints are internally inconsistent ***')
     437            G2fil.G2Print (' *** ERROR - your constraints are internally inconsistent ***')
    437438            #errmsg, warnmsg = G2mv.CheckConstraints(varyList,constrDict,fixedList)
    438439            #print 'Errors',errmsg
     
    466467            c = [var for var in combined if var not in newVaryList]
    467468            p = [var for var in combined if var not in firstVaryList]
    468             print('*** Variables change ***')
     469            G2fil.G2Print('*** Variables change ***')
    469470            for typ,vars in [('Removed',c),('Added',p)]:
    470471                line = '  '+typ+': '
     
    472473                    for var in vars:
    473474                        if len(line) > 70:
    474                             print(line)
     475                            G2fil.G2Print(line)
    475476                            line = '    '
    476477                        line += var + ', '
    477478                else:
    478479                        line += 'none, '
    479                 print(line[:-2])
     480                G2fil.G2Print(line[:-2])
    480481            firstVaryList = newVaryList
    481482
     
    488489                rigidbodyDict,parmDict,varyList,calcControls,pawleyLookup,ifSeq,printFile,dlg,
    489490                refPlotUpdate=refPlotUpdate)
    490             print ('  wR = %7.2f%%, chi**2 = %12.6g, reduced chi**2 = %6.2f, last delta chi = %.4f'%(
     491            G2fil.G2Print ('  wR = %7.2f%%, chi**2 = %12.6g, reduced chi**2 = %6.2f, last delta chi = %.4f'%(
    491492                Rvals['Rwp'],Rvals['chisq'],Rvals['GOF']**2,Rvals['DelChi2']))
    492493            # add the uncertainties into the esd dictionary (sigDict)
    493494            if not IfOK:
    494                 print('***** Sequential refinement failed at histogram '+histogram)
     495                G2fil.G2Print('***** Sequential refinement failed at histogram '+histogram,mode='warn')
    495496                break
    496497            sigDict = dict(zip(varyList,sig))
     
    531532#        except G2obj.G2Exception(Msg):
    532533#            printFile.close()
    533 #            print (' ***** Refinement aborted *****')
     534#            G2fil.G2Print (' ***** Refinement aborted *****')
    534535#            return False,Msg.msg
    535536        if GSASIIpath.GetConfigValue('Show_timing'):
    536537            t2 = time.time()
    537             print("Fit step time {:.2f} sec.".format(t2-t1))
     538            G2fil.G2Print("Fit step time {:.2f} sec.".format(t2-t1))
    538539            t1 = t2
    539540    SeqResult['histNames'] = [itm for itm in G2stIO.GetHistogramNames(GPXfile,['PWDR',]) if itm in SeqResult.keys()]
    540541    G2stIO.SetSeqResult(GPXfile,Histograms,SeqResult)
    541542    printFile.close()
    542     print (' Sequential refinement results are in file: '+ospath.splitext(GPXfile)[0]+'.lst')
    543     print (' ***** Sequential refinement successful *****')
     543    G2fil.G2Print (' Sequential refinement results are in file: '+ospath.splitext(GPXfile)[0]+'.lst')
     544    G2fil.G2Print (' ***** Sequential refinement successful *****')
    544545    return True,'Success'
    545546
     
    782783    if DATData['Natoms'] == 4:  #torsion
    783784        Tors,sig = G2mth.GetDATSig(Oatoms,Datoms,Amat,SGData,covData)
    784         print (' Torsion angle for %s atom sequence: %s = %s'%(DATData['Name'],str(atmSeq).replace("'","")[1:-1],G2mth.ValEsd(Tors,sig)))
    785         print (' NB: Atom sequence determined by selection order')
     785        G2fil.G2Print (' Torsion angle for %s atom sequence: %s = %s'%(DATData['Name'],str(atmSeq).replace("'","")[1:-1],G2mth.ValEsd(Tors,sig)))
     786        G2fil.G2Print (' NB: Atom sequence determined by selection order')
    786787        return      # done with torsion
    787788    elif DATData['Natoms'] == 3:  #angle
    788789        Ang,sig = G2mth.GetDATSig(Oatoms,Datoms,Amat,SGData,covData)
    789         print (' Angle in %s for atom sequence: %s = %s'%(DATData['Name'],str(atmSeq).replace("'","")[1:-1],G2mth.ValEsd(Ang,sig)))
    790         print (' NB: Atom sequence determined by selection order')
     790        G2fil.G2Print (' Angle in %s for atom sequence: %s = %s'%(DATData['Name'],str(atmSeq).replace("'","")[1:-1],G2mth.ValEsd(Ang,sig)))
     791        G2fil.G2Print (' NB: Atom sequence determined by selection order')
    791792    else:   #2 atoms - distance
    792793        Dist,sig = G2mth.GetDATSig(Oatoms,Datoms,Amat,SGData,covData)
    793         print (' Distance in %s for atom sequence: %s = %s'%(DATData['Name'],str(atmSeq).replace("'","")[1:-1],G2mth.ValEsd(Dist,sig)))
     794        G2fil.G2Print (' Distance in %s for atom sequence: %s = %s'%(DATData['Name'],str(atmSeq).replace("'","")[1:-1],G2mth.ValEsd(Dist,sig)))
    794795
    795796def BestPlane(PlaneData):
     
    797798
    798799    def ShowBanner(name):
    799         print (80*'*')
    800         print ('   Best plane result for phase '+name)
    801         print (80*'*','\n')
     800        G2fil.G2Print (80*'*')
     801        G2fil.G2Print ('   Best plane result for phase '+name)
     802        G2fil.G2Print (80*'*','\n')
    802803
    803804    ShowBanner(PlaneData['Name'])
     
    819820    for i,xyz in enumerate(XYZ):
    820821        Zmat += np.outer(xyz.T,xyz)
    821     print (' Selected atoms centered at %10.5f %10.5f %10.5f'%(sumXYZ[0],sumXYZ[1],sumXYZ[2]))
     822    G2fil.G2Print (' Selected atoms centered at %10.5f %10.5f %10.5f'%(sumXYZ[0],sumXYZ[1],sumXYZ[2]))
    822823    Evec,Emat = nl.eig(Zmat)
    823824    Evec = np.sqrt(Evec)/(Natoms-3)
     
    825826    XYZ = np.inner(XYZ,Emat.T).T
    826827    XYZ = np.array([XYZ[Order[2]],XYZ[Order[1]],XYZ[Order[0]]]).T
    827     print (' Atoms in Cartesian best plane coordinates:')
    828     print (' Name         X         Y         Z')
     828    G2fil.G2Print (' Atoms in Cartesian best plane coordinates:')
     829    G2fil.G2Print (' Name         X         Y         Z')
    829830    for i,xyz in enumerate(XYZ):
    830         print (' %6s%10.3f%10.3f%10.3f'%(Atoms[i][1].ljust(6),xyz[0],xyz[1],xyz[2]))
    831     print ('\n Best plane RMS X =%8.3f, Y =%8.3f, Z =%8.3f'%(Evec[Order[2]],Evec[Order[1]],Evec[Order[0]]))
     831        G2fil.G2Print (' %6s%10.3f%10.3f%10.3f'%(Atoms[i][1].ljust(6),xyz[0],xyz[1],xyz[2]))
     832    G2fil.G2Print ('\n Best plane RMS X =%8.3f, Y =%8.3f, Z =%8.3f'%(Evec[Order[2]],Evec[Order[1]],Evec[Order[0]]))
    832833
    833834def main():
     
    838839        GPXfile = arg[1]
    839840        if not ospath.exists(GPXfile):
    840             print ('ERROR - '+GPXfile+" doesn't exist!")
     841            G2fil.G2Print ('ERROR - '+GPXfile+" doesn't exist!")
    841842            exit()
    842843    else:
    843         print ('ERROR - missing filename')
     844        G2fil.G2Print ('ERROR - missing filename')
    844845        exit()
    845846    # TODO: figure out if this is a sequential refinement and call SeqRefine(GPXfile,None)
    846847    Refine(GPXfile,None)
    847     print("Done. Execution time {:.2f} sec.".format(time.time()-starttime))
     848    G2fil.G2Print("Done. Execution time {:.2f} sec.".format(time.time()-starttime))
    848849
    849850if __name__ == '__main__':
  • trunk/imports/G2img_1TIF.py

    r3767 r4021  
    2323import GSASIIobj as G2obj
    2424import GSASIIpath
     25import GSASIIfiles as G2fil
    2526import numpy as np
    2627import time
     
    6768        self.Comments,self.Data,self.Npix,self.Image = GetTifData(filename)
    6869        if self.Npix == 0:
    69             print("GetTifData failed to read "+str(filename)+" Trying SciPy")
     70            G2fil.G2Print("GetTifData failed to read "+str(filename)+" Trying SciPy")
    7071            import scipy.misc
    7172            self.Image = scipy.misc.imread(filename,flatten=True)
     
    120121                    samplechangerpos = float(line.split('=')[1])
    121122            except:
    122                 print('error reading metadata: '+line)
     123                G2fil.G2Print('error reading metadata: '+line)
    123124        Meta.close()
    124125    except IOError:
    125         print ('no metadata file found - will try to read file anyway')
     126        G2fil.G2Print ('no metadata file found - will try to read file anyway')
    126127        head = ['no metadata file found',]
    127128       
     
    136137        IFD = int(st.unpack(byteOrd+'i',File.read(4))[0])       
    137138    else:
    138         print (tag)
     139#        print (tag)
    139140        lines = ['not a detector tiff file',]
    140141        return lines,0,0,0
     
    171172    time0 = time.time()
    172173    if 34710 in IFD:
    173         print ('Read MAR CCD tiff file: '+filename)
     174        G2fil.G2Print ('Read MAR CCD tiff file: '+filename)
    174175        marFrame = rmf.marFrame(File,byteOrd,IFD)
    175176        image = np.flipud(np.array(np.asarray(marFrame.image),dtype=np.int32))
     
    196197                from PIL import Image as Im
    197198            except ImportError:
    198                 print ("PIL/pillow Image module not present. This TIF cannot be read without this")
     199                G2fil.G2Print ("PIL/pillow Image module not present. This TIF cannot be read without this")
    199200                #raise Exception("PIL/pillow Image module not found")
    200201                lines = ['not a detector tiff file',]
     
    215216            pixy = [172.,172.]
    216217            File.seek(4096)
    217             print ('Read Pilatus tiff file: '+filename)
     218            G2fil.G2Print ('Read Pilatus tiff file: '+filename)
    218219            image = np.array(np.frombuffer(File.read(4*Npix),dtype=np.int32),dtype=np.int32)
    219220        else:
     
    222223                    tifType = 'Dexela'
    223224                    pixy = [74.8,74.8]
    224                     print ('Read Dexela detector tiff file: '+filename)
     225                    G2fil.G2Print ('Read Dexela detector tiff file: '+filename)
    225226                else:
    226227                    tifType = 'GE'
    227228                    pixy = [200.,200.]
    228                     print ('Read GE-detector tiff file: '+filename)
     229                    G2fil.G2Print ('Read GE-detector tiff file: '+filename)
    229230                File.seek(8)
    230231                image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.uint16),dtype=np.int32)
     
    234235                pixy = [200.,200.]
    235236                File.seek(8)
    236                 print ('Read as 32-bit unsigned (CHESS) tiff file: '+filename)
     237                G2fil.G2Print ('Read as 32-bit unsigned (CHESS) tiff file: '+filename)
    237238                image = np.array(ar.array('I',File.read(4*Npix)),dtype=np.uint32)
    238239    elif 270 in IFD:
     
    244245            pixy = [200.,200.]*IFD[277][2][0]
    245246            File.seek(IFD[273][2][0])
    246             print ('Read ImageJ tiff file: '+filename)
     247            G2fil.G2Print ('Read ImageJ tiff file: '+filename)
    247248            if IFD[258][2][0] == 32:
    248249                image = File.read(4*Npix)
     
    262263        pixy = [158.,158.]
    263264        File.seek(512)
    264         print ('Read DND SAX/WAX-detector tiff file: '+filename)
     265        G2fil.G2Print ('Read DND SAX/WAX-detector tiff file: '+filename)
    265266        image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.uint16),dtype=np.int32)
    266267    elif sizexy == [1536,1536]:
     
    268269        pixy = [150.,150.]
    269270        File.seek(64)
    270         print ('Read Gold tiff file:'+filename)
     271        G2fil.G2Print ('Read Gold tiff file:'+filename)
    271272        image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.uint16),dtype=np.int32)
    272273    elif sizexy == [2048,2048] or sizexy == [1024,1024] or sizexy == [3072,3072]:
     
    276277                pixy = [200.,200.]
    277278                File.seek(8)
    278                 print ('Read APS PE-detector tiff file: '+filename)
     279                G2fil.G2Print ('Read APS PE-detector tiff file: '+filename)
    279280                if dataType == 5:
    280281                    image = np.array(np.frombuffer(File.read(4*Npix),dtype=np.float32),dtype=np.int32)  #fastest
     
    285286                pixy = [46.9,46.9]
    286287                File.seek(8)
    287                 print ('Read MedOptics D1 tiff file: '+filename)
     288                G2fil.G2Print ('Read MedOptics D1 tiff file: '+filename)
    288289                image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.uint16),dtype=np.int32)
    289290                 
     
    296297                tifType = 'MAR325'           
    297298            File.seek(4096)
    298             print ('Read MAR CCD tiff file: '+filename)
     299            G2fil.G2Print ('Read MAR CCD tiff file: '+filename)
    299300            image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.uint16),dtype=np.int32)
    300301        elif IFD[273][2][0] == 512:
     
    302303            pixy = [200.,200.]
    303304            File.seek(512)
    304             print ('Read 11-ID-C tiff file: '+filename)
     305            G2fil.G2Print ('Read 11-ID-C tiff file: '+filename)
    305306            image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.uint16),dtype=np.int32)
    306307                   
     
    311312                pixy = [9.,9.]
    312313                File.seek(8)
    313                 print ('Read APS scanCCD tiff file: '+filename)
     314                G2fil.G2Print ('Read APS scanCCD tiff file: '+filename)
    314315                image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
    315316            elif IFD[258][2][0] == 32:
     
    317318                pixy = [100.,100.]
    318319                File.seek(8)
    319                 print ('Read PE 4Kx4K tiff file: '+filename)
     320                G2fil.G2Print ('Read PE 4Kx4K tiff file: '+filename)
    320321                image = np.array(np.frombuffer(File.read(4*Npix),dtype=np.float32)/2.**4,dtype=np.int32)
    321322        elif IFD[273][2][0] == 4096:
     
    323324            pixy = [73.242,73.242]
    324325            File.seek(4096)
    325             print ('Read Rayonix MX300HE tiff file: '+filename)
     326            G2fil.G2Print ('Read Rayonix MX300HE tiff file: '+filename)
    326327            image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.uint16),dtype=np.int32)
    327328    elif sizexy == [391,380]:
     
    362363        lines = ['not a known detector tiff file',]
    363364        return lines,0,0,0
    364     print ('image read time: %.3f'%(time.time()-time0))
     365    G2fil.G2Print ('image read time: %.3f'%(time.time()-time0))
    365366    image = np.reshape(image,(sizexy[1],sizexy[0]))
    366367    center = (not center[0]) and [pixy[0]*sizexy[0]/2000,pixy[1]*sizexy[1]/2000] or center
Note: See TracChangeset for help on using the changeset viewer.