Changeset 4021
- Timestamp:
- Jun 11, 2019 10:05:07 PM (4 years ago)
- Location:
- trunk
- Files:
-
- 11 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/GSASIIctrlGUI.py
r3977 r4021 1154 1154 self.onChoice = None 1155 1155 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]) 1159 1159 self.strLoc[self.strKey] = self.GetStringSelection() 1160 1160 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: 1162 1164 try: 1163 1165 self.SetSelection(choiceList.index(self.strLoc[self.strKey])) -
trunk/GSASIIdataGUI.py
r4015 r4021 4162 4162 dirname,filename = os.path.split(filename) 4163 4163 filename = os.path.splitext(filename)[0] 4164 Inst = None 4165 Limits = None 4164 4166 for export in exports: 4165 4167 if len(exports) > 1: -
trunk/GSASIIfiles.py
r4018 r4021 42 42 pass 43 43 return 0.0 44 45 G2printLevel = 'all' 46 '''This defines the level of output from calls to :func:`G2Print`, 47 which should be used in place of print() within this module. 48 Settings for this are 'all', 'warn', 'error' or 'none'. Also see: 49 :func:`G2Print` and :func:`G2SetPrintLevel`. 50 ''' 51 52 def 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 71 def 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) 44 93 45 94 def get_python_versions(packagelist): … … 360 409 readerlist.append(reader) 361 410 except AttributeError: 362 print ('Import_' + errprefix + ': Attribute Error ' + filename)411 G2Print ('Import_' + errprefix + ': Attribute Error ' + filename) 363 412 if traceback: 364 413 traceback.print_exc(file=sys.stdout) 365 414 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)) 368 417 if traceback: 369 418 traceback.print_exc(file=sys.stdout) … … 409 458 pass 410 459 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)) 413 462 if traceback: 414 463 traceback.print_exc(file=sys.stdout) … … 416 465 exporterlist.append(exporter) 417 466 except AttributeError: 418 print ('Export Attribute Error ' + filename)467 G2Print ('Export Attribute Error ' + filename) 419 468 if traceback: 420 469 traceback.print_exc(file=sys.stdout) 421 470 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)) 424 473 if traceback: 425 474 traceback.print_exc(file=sys.stdout) … … 564 613 parfiles = glob.glob(os.path.join(GSASIIpath.GetConfigValue('Column_Metadata_directory'),'*.par')) 565 614 if len(parfiles) == 0: 566 print('Sorry, No Column metadata (.par) file found in '+615 G2Print('Sorry, No Column metadata (.par) file found in '+ 567 616 GSASIIpath.GetConfigValue('Column_Metadata_directory')) 568 617 return {} … … 574 623 break 575 624 else: 576 print('Warning: No labels definitions found for '+parFil)625 G2Print('Warning: No labels definitions found for '+parFil) 577 626 continue 578 627 labels,lbldict,keyCols,keyExp,errors = readColMetadataLabels(lblFil) … … 582 631 continue 583 632 else: 584 print('Read '+lblFil)633 G2Print('Read '+lblFil) 585 634 # scan through each line in this .par file, looking for the matching image rootname 586 635 fp = open(parFil,'Ur') … … 600 649 metadata['par file'] = parFil 601 650 metadata['lbls file'] = lblFil 602 print("Metadata read from {} line {}".format(parFil,iline+1))651 G2Print("Metadata read from {} line {}".format(parFil,iline+1)) 603 652 fp.close() 604 653 return metadata 605 654 else: 606 print("Image {} not found in {}".format(imageName,parFil))655 G2Print("Image {} not found in {}".format(imageName,parFil)) 607 656 fp.close() 608 657 continue 609 658 fp.close() 610 659 else: 611 print("Warning: No .par metadata for image {}".format(imageName))660 G2Print("Warning: No .par metadata for image {}".format(imageName)) 612 661 return {} 613 662 … … 700 749 reader.Data['wavelength'] = parParms['wavelength'] 701 750 else: 702 print('Error: wavelength not defined in {}'.format(parParms['lbls file']))751 G2Print('Error: wavelength not defined in {}'.format(parParms['lbls file'])) 703 752 if "distance" in parParms: 704 753 reader.Data['distance'] = parParms['distance'] 705 754 reader.Data['setdist'] = parParms['distance'] 706 755 else: 707 print('Error: distance not defined in {}'.format(parParms['lbls file']))756 G2Print('Error: distance not defined in {}'.format(parParms['lbls file'])) 708 757 709 758 def LoadControls(Slines,data): … … 778 827 primaryReaders.append(rd) 779 828 if len(secondaryReaders) + len(primaryReaders) == 0: 780 print('Error: No matching format for file '+imagefile)829 G2Print('Error: No matching format for file '+imagefile) 781 830 raise Exception('No image read') 782 831 errorReport = '' … … 796 845 raise Exception('No image read. Strange!') 797 846 if GSASIIpath.GetConfigValue('Transpose'): 798 print ('Transposing Image!')847 G2Print ('Warning: Transposing Image!') 799 848 rd.Image = rd.Image.T 800 849 #rd.readfilename = imagefile 801 850 return rd.Image 802 851 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) 805 854 raise Exception('No image read') 806 855 … … 870 919 iqfile.write("%15.6g %15.6g\n" % (q,iq)) 871 920 iqfile.close() 872 print (' I(Q) saved to: '+iqfilename)921 G2Print (' I(Q) saved to: '+iqfilename) 873 922 874 923 if PDFsaves[1]: #S(Q) … … 884 933 sqfile.write("%15.6g %15.6g\n" % (q,sq)) 885 934 sqfile.close() 886 print (' S(Q) saved to: '+sqfilename)935 G2Print (' S(Q) saved to: '+sqfilename) 887 936 888 937 if PDFsaves[2]: #F(Q) … … 898 947 fqfile.write("%15.6g %15.6g\n" % (q,fq)) 899 948 fqfile.close() 900 print (' F(Q) saved to: '+fqfilename)949 G2Print (' F(Q) saved to: '+fqfilename) 901 950 902 951 if PDFsaves[3]: #G(R) … … 912 961 grfile.write("%15.6g %15.6g\n" % (r,gr)) 913 962 grfile.close() 914 print (' G(R) saved to: '+grfilename)963 G2Print (' G(R) saved to: '+grfilename) 915 964 916 965 if PDFsaves[4]: #pdfGUI file for G(R) … … 970 1019 grfile.write("%15.2F %15.6F\n" % (r,gr)) 971 1020 grfile.close() 972 print (' G(R) saved to: '+grfilename)1021 G2Print (' G(R) saved to: '+grfilename) -
trunk/GSASIIimage.py
r4009 r4021 34 34 import GSASIIspc as G2spc 35 35 import GSASIImath as G2mth 36 import GSASIIfiles as G2fil 36 37 37 38 # trig functions in degrees … … 566 567 ''' 567 568 import ImageCalibrants as calFile 568 print ('Image recalibration:')569 G2fil.G2Print ('Image recalibration:') 569 570 time0 = time.time() 570 571 pixelSize = data['pixelSize'] … … 578 579 data['DetDepth'] /= data['distance'] 579 580 if not data['calibrant']: 580 print ('no calibration material selected')581 G2fil.G2Print ('warning: no calibration material selected') 581 582 return [] 582 583 skip = data['calibskip'] 583 584 dmin = data['calibdmin'] 584 585 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']) 586 587 return [] 587 588 Bravais,SGs,Cells = calFile.Calibrants[data['calibrant']][:3] … … 612 613 tth = 2.0*asind(wave/(2.*dsp)) 613 614 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') 615 616 break 616 617 ellipse = GetEllipse(dsp,data) … … 627 628 continue 628 629 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') 630 631 return [] 631 632 … … 644 645 ellipse = GetEllipse(H[3],data) 645 646 data['ellipses'].append(copy.deepcopy(ellipse+('b',))) 646 print ('calibration time = %.3f'%(time.time()-time0))647 G2fil.G2Print ('calibration time = %.3f'%(time.time()-time0)) 647 648 if G2frame: 648 649 G2plt.PlotImage(G2frame,newImage=True) … … 654 655 ''' 655 656 import ImageCalibrants as calFile 656 print ('Image calibration:')657 G2fil.G2Print ('Image calibration:') 657 658 time0 = time.time() 658 659 ring = data['ring'] … … 664 665 varyDict = data['varyList'] 665 666 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') 667 668 return False 668 669 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') 670 671 return False 671 672 … … 677 678 fmt2 = '%s X: %.3f, Y: %.3f, phi: %.3f, R1: %.3f, R2: %.3f, chi**2: %.3f, Np: %d' 678 679 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])) 680 681 ellipse = outE 681 682 else: … … 690 691 ellipse = FitEllipse(Ring) 691 692 else: 692 print ('1st ring not sufficiently complete to proceed')693 G2fil.G2Print ('1st ring not sufficiently complete to proceed',mode='warn') 693 694 return False 694 695 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], 696 697 ellipse[2][0],ellipse[2][1],0.,len(Ring))) #cent,phi,radii 697 698 data['ellipses'].append(ellipse[:]+('r',)) … … 702 703 data['rings'] = [] 703 704 if not data['calibrant']: 704 print ('no calibration material selected')705 G2fil.G2Print ('Warning: no calibration material selected') 705 706 return True 706 707 … … 715 716 SGData = G2spc.SpcGroup(sg)[1] 716 717 hkl = G2pwd.getHKLpeak(dmin,SGData,A) 717 print(hkl)718 G2fil.G2Print(hkl) 718 719 HKL += list(hkl) 719 720 else: … … 724 725 elcent,phi,radii = ellipse #from fit of 1st ring 725 726 dsp = HKL[0][3] 726 print ('1st ring: try %.4f'%(dsp))727 G2fil.G2Print ('1st ring: try %.4f'%(dsp)) 727 728 if varyDict['dist']: 728 729 wave = data['wavelength'] … … 739 740 tilt = npasind(np.sqrt(max(0.,1.-(radii[0]/radii[1])**2))*ctth) 740 741 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') 743 744 else: 744 745 tilt = data['tilt'] … … 763 764 while fail: 764 765 dsp = HKL[i2][3] 765 print ('2nd ring: try %.4f'%(dsp))766 G2fil.G2Print ('2nd ring: try %.4f'%(dsp)) 766 767 tth = 2.0*asind(wave/(2.*dsp)) 767 768 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])) 769 770 Ringp = makeRing(dsp,ellipsep,3,cutoff,scalex,scaley,G2frame.ImageZ)[0] 770 771 parmDict = {'dist':dist,'det-X':centp[0],'det-Y':centp[1], … … 780 781 chip = 1e6 781 782 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])) 783 784 Ringm = makeRing(dsp,ellipsem,3,cutoff,scalex,scaley,G2frame.ImageZ)[0] 784 785 if len(Ringm) > 10: … … 817 818 tth = 2.0*asind(wave/(2.*dsp)) 818 819 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') 820 821 break 821 822 if debug: print ('HKLD:'+str(H[:4])+'2-theta: %.4f'%(tth)) … … 845 846 fullSize = len(G2frame.ImageZ)/scalex 846 847 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') 848 849 N = len(data['ellipses']) 849 850 if N > 2: … … 858 859 ellipse = GetEllipse(H[3],data) 859 860 data['ellipses'].append(copy.deepcopy(ellipse+('b',))) 860 print ('calibration time = %.3f'%(time.time()-time0))861 G2fil.G2Print ('calibration time = %.3f'%(time.time()-time0)) 861 862 G2plt.PlotImage(G2frame,newImage=True) 862 863 return True … … 971 972 'Integrate an image; called from OnIntegrateAll and OnIntegrate in G2imgGUI' #for q, log(q) bins need data['binType'] 972 973 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))) 974 975 CancelPressed = False 975 976 LUtth = np.array(data['IOtth']) … … 1045 1046 times[3] += time.time()-t0 1046 1047 # 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') 1048 1049 t0 = time.time() 1049 1050 # H2 = np.array([tth for tth in np.linspace(lutth[0],lutth[1],numChans+1)]) … … 1074 1075 H0 /= np.array([G2pwd.Polarization(data['PolaVal'][0],H2[:-1],Azm=azm-90.)[0] for azm in (H1[:-1]+np.diff(H1)/2.)]) 1075 1076 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 \ 1077 1078 \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') 1080 1081 if returnN: #As requested by Steven Weigand 1081 1082 return H0,H1,H2,NST,CancelPressed … … 1132 1133 ring['Ivar'] = np.var(ringint) 1133 1134 ring['covMat'] = covMat 1134 print ('Variance in normalized ring intensity: %.3f'%(ring['Ivar']))1135 G2fil.G2Print ('Variance in normalized ring intensity: %.3f'%(ring['Ivar'])) 1135 1136 CalcStrSta(StrSta,Controls) 1136 1137 … … 1151 1152 ringint = np.array([float(Image[int(x*scalex),int(y*scaley)]) for y,x in np.array(ringxy)[:,:2]]) 1152 1153 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))) 1154 1155 RingsAI.append(np.array(zip(ringazm,ringint)).T) 1155 1156 return RingsAI … … 1298 1299 def AutoSpotMasks(Image,Masks,Controls): 1299 1300 1300 print ('auto spot search')1301 G2fil.G2Print ('auto spot search') 1301 1302 nxy = 15 1302 1303 rollImage = lambda rho,roll: np.roll(np.roll(rho,roll[0],axis=0),roll[1],axis=1) … … 1321 1322 mags = magind[2] 1322 1323 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)) 1324 1325 nx,ny = Image.shape 1325 1326 ImMax = np.max(Image) … … 1332 1333 minM = mult*np.max(mags) 1333 1334 num = ma.count(ma.array(mags,mask=mags<=minM)) 1334 print('try',mult,minM,num)1335 G2fil.G2Print('try',mult,minM,num) 1335 1336 minM = mult*np.max(mags) 1336 print ('Find biggest spots:',mult,num,minM)1337 G2fil.G2Print ('Find biggest spots:',mult,num,minM) 1337 1338 for i,mag in enumerate(mags): 1338 1339 if mag > minM: 1339 1340 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])) 1341 1342 peak = FitImageSpots(Image,ImMax,[indx[1][i],indx[0][i]],pixelSize,nxy) 1342 1343 if peak and not any(np.isnan(np.array(peak))): 1343 1344 peaks.append(peak) 1344 # print (' Spot found: %s'%str(peak))1345 # G2fil.G2Print (' Spot found: %s'%str(peak)) 1345 1346 peaks = G2mth.sortArray(G2mth.sortArray(peaks,1),0) 1346 1347 Peaks = [peaks[0],] … … 1350 1351 if (peak[0]-Peaks[-1][0])**2+(peak[1]-Peaks[-1][1])**2 > peak[2]*Peaks[-1][2] : 1351 1352 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)) 1354 1355 Masks['Points'] = Peaks 1355 1356 return None -
trunk/GSASIImpsubs.py
r3866 r4021 32 32 GSASIIpath.SetVersionNumber("$Revision$") 33 33 import GSASIIpwd as G2pwd 34 import GSASIIfiles as G2fil 34 35 35 36 sind = lambda x: np.sin(x*np.pi/180.) … … 56 57 useMP = False 57 58 if not allowMP: 58 print('Multiprocessing disabled')59 G2fil.G2Print('Multiprocessing disabled') 59 60 ncores = 0 60 61 return useMP,ncores … … 64 65 useMP = True 65 66 if useMP: 66 print('Multiprocessing with {} cores enabled'.format(ncores))67 G2fil.G2Print('Multiprocessing with {} cores enabled'.format(ncores)) 67 68 return useMP,ncores 68 69 -
trunk/GSASIIplot.py
r4010 r4021 3200 3200 CalcLine = None 3201 3201 BackLine = None 3202 DifLine = None3202 DifLine = [None] 3203 3203 if G2frame.Weight: 3204 3204 Plot1.set_yscale("linear") -
trunk/GSASIIpwd.py
r4002 r4021 44 44 import pydiffax as pyx 45 45 except ImportError: 46 print ('pydiffax is not available for this platform - under develpment') 46 print ('pydiffax is not available for this platform') 47 import GSASIIfiles as G2fil 47 48 48 49 … … 440 441 parmDict,varyList = MakeParms(peaks) 441 442 if not len(varyList): 442 print (' Nothing varied')443 G2fil.G2Print (' Nothing varied') 443 444 return newpeaks,None,None,None,None,None 444 445 … … 505 506 if showFit: 506 507 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') 508 509 if data['Sample Bkg.'].get('Refine',False): 509 510 # 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( 511 512 data['Ruland'],data['Sample Bkg.']['Mult'],rms)) 512 513 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( 514 515 data['Flat Bkg'],data['BackRatio'],data['Ruland'],rms)) 515 516 if data['Sample Bkg.'].get('Refine',False): … … 526 527 msg = 'Not Converged' 527 528 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( 529 530 data['Ruland'],data['Sample Bkg.']['Mult'],res['fun'],msg)) 530 531 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( 532 533 data['Flat Bkg'],data['BackRatio'],data['Ruland'],res['fun'],msg)) 533 534 return res … … 925 926 break 926 927 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 ****') 928 929 break 929 930 # fixed background from file … … 931 932 mult = fixedBkg.get('_fixedMult',0.0) 932 933 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( 934 935 len(yb),len(fixedBkg.get('_fixedValues',[])))) 935 936 elif mult: … … 1063 1064 break 1064 1065 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 ****') 1066 1067 break 1067 1068 return dydb,dyddb,dydpk … … 1605 1606 varyList = insVary 1606 1607 if not len(varyList): 1607 print ('**** ERROR - nothing to refine! ****')1608 G2fil.G2Print ('**** ERROR - nothing to refine! ****') 1608 1609 return False 1609 1610 while True: … … 1617 1618 Values2Dict(parmDict, varyList, result[0]) 1618 1619 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)) 1622 1623 try: 1623 1624 sig = np.sqrt(np.diag(result[1])*GOF) 1624 1625 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 ***') 1626 1627 break #refinement succeeded - finish up! 1627 1628 except ValueError: #result[1] is None on singular matrix 1628 print ('**** Refinement failed - singular matrix ****')1629 G2fil.G2Print ('**** Refinement failed - singular matrix ****') 1629 1630 1630 1631 sigDict = dict(zip(varyList,sig)) … … 1943 1944 Rvals['Rwp'] = np.sqrt(chisq/np.sum(w[xBeg:xFin]*(y+fixback)[xBeg:xFin]**2))*100. #to % 1944 1945 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))) 1946 1947 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'])) 1949 1950 sig = [0]*len(varyList) 1950 1951 if len(varyList) == 0: break # if nothing was refined … … 1952 1953 sig = np.sqrt(np.diag(result[1])*Rvals['GOF']) 1953 1954 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 ***') 1955 1956 break #refinement succeeded - finish up! 1956 1957 except ValueError: #result[1] is None on singular matrix 1957 print ('**** Refinement failed - singular matrix ****')1958 G2fil.G2Print ('**** Refinement failed - singular matrix ****') 1958 1959 Ipvt = result[2]['ipvt'] 1959 1960 for i,ipvt in enumerate(Ipvt): 1960 1961 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]) 1962 1963 badVary.append(varyList[ipvt-1]) 1963 1964 del(varyList[ipvt-1]) … … 1985 1986 if len(binsperFWHM): 1986 1987 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 ***') 1988 1989 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') 1990 1991 else: 1991 print (' Manually increase W in Instrument Parameters')1992 G2fil.G2Print (' Manually increase W in Instrument Parameters') 1992 1993 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))) 1995 1996 return sigDict,result,sig,Rvals,varyList,parmDict,fullvaryList,badVary 1996 1997 … … 2055 2056 2056 2057 def 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])) 2058 2059 2059 2060 class RandomDisplacementBounds(object): … … 2114 2115 data['Scale'][0] = parmDict['Scale'] 2115 2116 line += ' esd: %.4g'%(sigDict['Scale']) 2116 print (line)2117 G2fil.G2Print (line) 2117 2118 line = ' Flat background: %15.4g'%(parmDict['FltBack']) 2118 2119 if 'FltBack' in varyList: 2119 2120 data['FltBack'][0] = parmDict['FltBack'] 2120 2121 line += ' esd: %15.3g'%(sigDict['FltBack']) 2121 print (line)2122 G2fil.G2Print (line) 2122 2123 for ilay,layer in enumerate(data['Layers']): 2123 2124 name = layer['Name'] 2124 print (' Parameters for layer: %d %s'%(ilay,name))2125 G2fil.G2Print (' Parameters for layer: %d %s'%(ilay,name)) 2125 2126 cid = str(ilay)+';' 2126 2127 line = ' ' … … 2136 2137 if cid+parm in varyList: 2137 2138 line += ' esd: %.3g'%(sigDict[cid+parm]) 2138 print (line)2139 print (line2)2139 G2fil.G2Print (line) 2140 G2fil.G2Print (line2) 2140 2141 2141 2142 def calcREFD(values,Q,Io,wt,Qsig,parmDict,varyList): … … 2216 2217 take_step = RandomDisplacementBounds(xyrng[0], xyrng[1]) 2217 2218 T0 = estimateT0(take_step) 2218 print (' Estimated temperature: %.3g'%(T0))2219 G2fil.G2Print (' Estimated temperature: %.3g'%(T0)) 2219 2220 result = so.basinhopping(sumREFD,values,take_step=take_step,disp=True,T=T0,stepsize=Bfac, 2220 2221 interval=20,niter=200,minimizer_kwargs={'method':'L-BFGS-B','bounds':bounds, … … 2236 2237 ncalc = result[3] 2237 2238 covM = [] 2238 print (' MC/SA final temperature: %.4g'%(result[2]))2239 G2fil.G2Print (' MC/SA final temperature: %.4g'%(result[2])) 2239 2240 elif data['Minimizer'] == 'L-BFGS-B': 2240 2241 result = so.minimize(sumREFD,values,method='L-BFGS-B',bounds=bounds, #ftol=Ftol, … … 2281 2282 covMatrix = [] 2282 2283 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'])) 2286 2287 SetModelParms() 2287 2288 return True,result,varyList,sig,Rvals,covMatrix,parmDict,'' 2288 2289 except (ValueError,TypeError): #when bad LS refinement; covM missing or with nans 2289 print (Msg)2290 G2fil.G2Print (Msg) 2290 2291 return False,0,0,0,0,0,0,Msg 2291 2292 … … 2470 2471 2471 2472 def makeRefdFFT(Limits,Profile): 2472 print ('make fft')2473 G2fil.G2Print ('make fft') 2473 2474 Q,Io = Profile[:2] 2474 2475 Qmin = Limits[1][0] … … 2535 2536 if 'bin' in name: 2536 2537 DIFFaX = name+'/DIFFaX.exe' 2537 print (' Execute '+DIFFaX)2538 G2fil.G2Print (' Execute '+DIFFaX) 2538 2539 break 2539 2540 # make form factor file that DIFFaX wants - atom types are GSASII style … … 2654 2655 sumPx += p 2655 2656 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) 2657 2658 df.close() 2658 2659 os.remove('data.sfc') … … 2665 2666 subp.call(DIFFaX) 2666 2667 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)) 2669 2670 if os.path.exists('GSASII-DIFFaX.spc'): 2670 2671 Xpat = np.loadtxt('GSASII-DIFFaX.spc').T … … 2831 2832 time0 = time.time() 2832 2833 pyx.pygetspc(controls,Nspec,spec) 2833 print (' GETSPC time = %.2fs'%(time.time()-time0))2834 G2fil.G2Print (' GETSPC time = %.2fs'%(time.time()-time0)) 2834 2835 time0 = time.time() 2835 2836 U = ateln2*inst['U'][1]/10000. … … 2862 2863 profile[2][iBeg:iFin] = np.where(profile[1][iBeg:iFin]>0.,1./profile[1][iBeg:iFin],1.0) 2863 2864 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)) 2865 2866 2866 2867 def CalcStackingSADP(Layers,debug): … … 2897 2898 iB += Nblk 2898 2899 Layers['Sadp']['Img'] = Sapd 2899 print (' GETSAD time = %.2fs'%(time.time()-time0))2900 G2fil.G2Print (' GETSAD time = %.2fs'%(time.time()-time0)) 2900 2901 2901 2902 ############################################################################### … … 3187 3188 for i in range(100): 3188 3189 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) 3190 3191 3191 3192 def test2(name,delt): … … 3225 3226 for name,shft in [['pos',0.0001],['sig',0.01],['gam',0.0001],['shl',0.00005]]: 3226 3227 test3(name,shft) 3227 print ("OK")3228 G2fil.G2Print ("OK") 3228 3229 plotter.StartEventLoop() -
trunk/GSASIIscriptable.py
r4015 r4021 800 800 npsind = lambda x: np.sin(x*np.pi/180.) 801 801 802 def 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 802 820 def 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 ''' 804 825 if len(Readers['Pwdr']) > 0: return 805 826 # initialize imports … … 865 886 # Let IOError be thrown if file does not exist 866 887 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 {}'. 868 889 format(ProjFile)) 869 890 raise IOError('GPX file {} does not exist'.format(ProjFile)) … … 893 914 finally: 894 915 file.close() 895 print('gpx file saved as %s'%ProjFile)916 G2fil.G2Print('gpx file saved as %s'%ProjFile) 896 917 897 918 # def ImportPowder(reader,filename): … … 912 933 # rd = rdclass.GSAS_ReaderClass() 913 934 # 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') 915 936 # return None 916 937 # rdlist = [] … … 929 950 # repeat = True 930 951 # return rdlist 931 # print(rd.errors)952 # G2fil.G2Print(rd.errors) 932 953 # return None 933 954 … … 1189 1210 if not rd.ContentsValidator(filename): 1190 1211 # 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)) 1192 1213 if len(rd.selections) > 1: 1193 1214 raise G2ImportException("File {} has {} banks. Specify which bank to read with databank param." … … 1211 1232 repeat = rd.repeat 1212 1233 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)) 1214 1235 if rd_list: 1215 1236 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) 1218 1239 elif bank is None: 1219 print("{} read by Reader {}"1240 G2fil.G2Print("{} read by Reader {}" 1220 1241 .format(filename,rd.formatName)) 1221 1242 else: 1222 print("{} block # {} read by Reader {}"1243 G2fil.G2Print("{} block # {} read by Reader {}" 1223 1244 .format(filename,bank,rd.formatName)) 1224 1245 return rd_list … … 1291 1312 except ValueError: 1292 1313 Iparm1, Iparm2 = load_iprms(instprm, reader, bank=bank) 1293 print('Instrument parameters read:',reader.instmsg)1314 G2fil.G2Print('Instrument parameters read:',reader.instmsg) 1294 1315 Ymin = np.min(reader.powderdata[1]) 1295 1316 Ymax = np.max(reader.powderdata[1]) … … 1530 1551 if filename is not None and newgpx is not None: 1531 1552 raise G2ScriptException('Do not use filename and newgpx together') 1532 elif newgpx is not None:1553 elif newgpx: 1533 1554 filename = newgpx 1534 if gpxfile is None:1555 if not gpxfile: 1535 1556 filename = os.path.abspath(os.path.expanduser(filename)) 1536 1557 self.filename = filename 1537 1558 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)): 1544 1560 # TODO set author 1545 1561 self.data, self.names = LoadDictFromProjFile(gpxfile) 1546 1562 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)) 1547 1571 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)) 1549 1573 1550 1574 @classmethod … … 1622 1646 [h.name for h in self.histograms()],bank=instbank) 1623 1647 if histname in self.data: 1624 print("Warning - redefining histogram", histname)1648 G2fil.G2Print("Warning - redefining histogram", histname) 1625 1649 elif self.names[-1][0] == 'Phases': 1626 1650 self.names.insert(-1, new_names) … … 1705 1729 [h.name for h in self.histograms()]) 1706 1730 if histname in self.data: 1707 print("Warning - redefining histogram", histname)1731 G2fil.G2Print("Warning - redefining histogram", histname) 1708 1732 elif self.names[-1][0] == 'Phases': 1709 1733 self.names.insert(-1, new_names) … … 1870 1894 errmsg, warnmsg = G2strIO.ReadCheckConstraints(self.filename) 1871 1895 if errmsg: 1872 print('Refinement error',errmsg)1896 G2fil.G2Print('Refinement error',errmsg) 1873 1897 raise Exception('Constraint error') 1874 1898 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'+ 1876 1900 warnmsg+u'\nRefinement not possible') 1877 1901 raise Exception('Constraint error') … … 2074 2098 """ 2075 2099 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) 2076 2125 2077 2126 def add_PDF(self, prmfile, histogram): … … 2120 2169 self.names.append([PDFname]+['PDF Controls', 'PDF Peaks']) 2121 2170 self.data[PDFname] = PDFdict 2122 print('Adding "{}" to project'.format(PDFname))2171 G2fil.G2Print('Adding "{}" to project'.format(PDFname)) 2123 2172 return G2PDF(self.data[PDFname], PDFname, self) 2124 2173 … … 2438 2487 for rd in readers: 2439 2488 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)) 2441 2490 #see this: G2IO.EditImageParms(self,rd.Data,rd.Comments,rd.Image,imagefile) 2442 2491 rd.SciPy = False … … 2564 2613 return self.data['Controls']['data']['Copy2Next'] 2565 2614 else: 2566 print('Defined Controls:',self.data['Controls']['data'].keys())2615 G2fil.G2Print('Defined Controls:',self.data['Controls']['data'].keys()) 2567 2616 raise Exception('{} is an invalid control value'.format(control)) 2568 2617 … … 2708 2757 missing = [i for i in varList if i not in self['Covariance']['data']['varyList']] 2709 2758 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)) 2711 2760 return None 2712 2761 vals = [self['Covariance']['data']['parmDict'][i] for i in varList] … … 3048 3097 import matplotlib.pyplot as plt 3049 3098 except ImportError: 3050 print('Unable to import matplotlib, skipping plot')3099 G2fil.G2Print('Warning: Unable to import matplotlib, skipping plot') 3051 3100 return 3052 3101 data = self.data['data'][1] … … 3196 3245 import GSASIImath as G2mth 3197 3246 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') 3199 3248 return 3200 3249 pos = ttheta … … 3267 3316 File.write(item+':'+str(data[item][1])+'\n') 3268 3317 File.close() 3269 print ('Instrument parameters saved to: '+filename)3318 G2fil.G2Print ('Instrument parameters saved to: '+filename) 3270 3319 3271 3320 def LoadProfile(self,filename,bank=0): … … 3597 3646 """ 3598 3647 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)) 3600 3649 return 3601 3650 … … 3606 3655 if self._decodeHist(h) in self.data['Histograms']] 3607 3656 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)) 3609 3658 return 3610 3659 for key, val in refs.items(): … … 3735 3784 self.data['Histograms'][h]['Scale'][1] = bool(val) 3736 3785 else: 3737 print(u'Unknown HAP key: '+key)3786 G2fil.G2Print(u'Warning: Unknown HAP key: '+key) 3738 3787 3739 3788 def clear_HAP_refinements(self, refs, histograms='all'): … … 3799 3848 self.data['Histograms'][h]['Scale'][1] = False 3800 3849 else: 3801 print(u'Unknown HAP key: '+key)3850 G2fil.G2Print(u'Warning: Unknown HAP key: '+key) 3802 3851 3803 3852 def _decodeHist(self,hist): … … 3866 3915 del copydict[item] 3867 3916 else: 3868 print('items in HAP dict are: {}'.format(3917 G2fil.G2Print('items in HAP dict are: {}'.format( 3869 3918 list(self.data['Histograms'][sourcehist]))) 3870 3919 raise Exception('HAP skip list entry {} invalid'.format(item)) … … 3874 3923 del copydict[item] 3875 3924 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])) 3878 3927 for h in targethistlist: 3879 3928 h = self._decodeHist(h) 3880 3929 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)) 3882 3931 continue 3883 3932 self.data['Histograms'][h].update(copy.deepcopy(copydict)) … … 3924 3973 del copydict[item] 3925 3974 else: 3926 print('items in HAP dict are: {}'.format(3975 G2fil.G2Print('items in HAP dict are: {}'.format( 3927 3976 list(self.data['Histograms'][sourcehist]))) 3928 3977 raise Exception('HAP skip list entry {} invalid'.format(item)) … … 3936 3985 h = self._decodeHist(h) 3937 3986 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)) 3939 3988 continue 3940 3989 if first: … … 3942 3991 if 'HStrain' in self.data['Histograms'][h] and 'HStrain' in copydict: 3943 3992 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 {}: {}'. 3945 3994 format(len(copydict['HStrain'][0]), 3946 3995 self.name,len(self.data['Histograms'][h]['HStrain'][0]))) 3947 3996 raise Exception('HStrain has differing numbers of terms.') 3948 3997 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])) 3951 4000 3952 4001 class G2SeqRefRes(G2ObjectWrapper): … … 4180 4229 seqData,histData = self.RefData(hist) 4181 4230 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)) 4183 4232 return 4184 4233 missing = [i for i in varList if i not in seqData['varyList']] 4185 4234 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)) 4187 4236 return None 4188 4237 vals = [seqData['parmDict'][i] for i in varList] … … 4291 4340 self.data['PDF Controls']['Form Vol'] = max(10.0,sumVol) 4292 4341 4293 def calculate(self ):4342 def calculate(self,xydata=None,limits=None,inst=None): 4294 4343 '''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. 4296 4365 ''' 4297 4366 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] 4306 4379 G2pwd.CalcPDF(data,inst,limits,xydata) 4307 4380 data['I(Q)'] = xydata['IofQ'] … … 4310 4383 data['G(R)'] = xydata['GofR'] 4311 4384 4312 def optimize(self,showFit=True,maxCycles=5): 4385 def optimize(self,showFit=True,maxCycles=5, 4386 xydata=None,limits=None,inst=None): 4313 4387 '''Optimize the low R portion of G(R) to minimize selected 4314 4388 parameters. Note that this updates the parameters in the settings … … 4324 4398 :returns: the result from the optimizer as True or False, depending 4325 4399 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. 4326 4413 ''' 4327 4414 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 4336 4428 res = G2pwd.OptimizePDF(data,xydata,limits,inst,showFit,maxCycles) 4337 4429 return res['success'] … … 4435 4527 if arg in self.ControlList[typ]: break 4436 4528 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('')]) 4438 4530 raise Exception('arg {} not defined in G2Image.setControl' 4439 4531 .format(arg)) … … 4468 4560 if arg in self.data['Image Controls']: 4469 4561 return self.data['Image Controls'][arg] 4470 print(self.findControl(''))4562 G2fil.G2Print(self.findControl('')) 4471 4563 raise Exception('arg {} not defined in G2Image.getControl'.format(arg)) 4472 4564 … … 4505 4597 self.data['Image Controls']['calibrant'] = calib 4506 4598 return 4507 print('Calibrant {} is not valid. Valid calibrants'.format(calib))4599 G2fil.G2Print('Calibrant {} is not valid. Valid calibrants'.format(calib)) 4508 4600 for i in calFile.Calibrants.keys(): 4509 if i: print('\t"{}"'.format(i))4601 if i: G2fil.G2Print('\t"{}"'.format(i)) 4510 4602 4511 4603 def setControlFile(self,typ,imageRef,mult=None): … … 4530 4622 #key = 'Gain map' 4531 4623 if mult is not None: 4532 print('Ignoring multiplier for Gain map')4624 G2fil.G2Print('Warning: Ignoring multiplier for Gain map') 4533 4625 mult = None 4534 4626 else: … … 4554 4646 File.close() 4555 4647 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)) 4557 4649 elif imgDict: 4558 4650 self.data['Image Controls'].update(imgDict) 4559 print('Image controls set')4651 G2fil.G2Print('Image controls set') 4560 4652 else: 4561 4653 raise Exception("loadControls called without imgDict or filename specified") … … 4568 4660 ''' 4569 4661 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 4572 4686 def loadMasks(self,filename,ignoreThreshold=False): 4573 4687 '''load masks from a .immask file … … 4580 4694 ''' 4581 4695 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]] 4583 4726 4584 4727 def getVary(self,*args): … … 4780 4923 for j in self.proj.names: 4781 4924 if j[0] == Aname: 4782 print('Replacing "{}" in project'.format(Aname))4925 G2fil.G2Print('Replacing "{}" in project'.format(Aname)) 4783 4926 break 4784 4927 else: 4785 print('Adding "{}" to project'.format(Aname))4928 G2fil.G2Print('Adding "{}" to project'.format(Aname)) 4786 4929 self.proj.names.append([Aname]+ 4787 4930 [u'Comments',u'Limits',u'Background',u'Instrument Parameters', … … 4834 4977 if args.histograms: 4835 4978 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) 4837 4980 hist_objs.append(proj.add_powder_histogram(h, i)) 4838 4981 4839 4982 if args.phases: 4840 4983 for p in args.phases: 4841 print("Adding phase from",p)4984 G2fil.G2Print("Adding phase from",p) 4842 4985 proj.add_phase(p, histograms=hist_objs) 4843 print('Linking phase(s) to histogram(s):')4986 G2fil.G2Print('Linking phase(s) to histogram(s):') 4844 4987 for h in hist_objs: 4845 print (' '+h.name)4988 G2fil.G2Print (' '+h.name) 4846 4989 4847 4990 proj.save() … … 4889 5032 if args.histograms: 4890 5033 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) 4892 5035 proj.add_powder_histogram(h, i, fmthint=args.histogramformat) 4893 5036 … … 4899 5042 4900 5043 for p in args.phases: 4901 print("Adding phase from",p)5044 G2fil.G2Print("Adding phase from",p) 4902 5045 proj.add_phase(p, histograms=histlist, fmthint=args.phaseformat) 4903 5046 4904 5047 if not args.histlist: 4905 print('Linking phase(s) to all histogram(s)')5048 G2fil.G2Print('Linking phase(s) to all histogram(s)') 4906 5049 else: 4907 print('Linking phase(s) to histogram(s):')5050 G2fil.G2Print('Linking phase(s) to histogram(s):') 4908 5051 for h in histlist: 4909 print (' '+h.name) 4910 5052 G2fil.G2Print(' '+h.name) 4911 5053 proj.save() 4912 5054 -
trunk/GSASIIstrIO.py
r3925 r4021 39 39 import GSASIImapvars as G2mv 40 40 import GSASIImath as G2mth 41 import GSASIIfiles as G2fil 41 42 42 43 sind = lambda x: np.sin(x*np.pi/180.) … … 118 119 pass 119 120 except Exception as msg: 120 print('Read Error:',msg)121 G2fil.G2Print('Read Error:',msg) 121 122 raise Exception("Error reading file "+str(GPXfile)+". This is not a GSAS-II .gpx file") 122 123 finally: … … 134 135 pos = gpxIndex.get('Controls') 135 136 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)) 137 138 return Controls 138 139 fp = open(GPXfile,'rb') … … 163 164 constDict,fixedList,ignored = ProcessConstraints(constList) 164 165 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)) 166 167 return constDict,fixedList 167 168 … … 285 286 if errmsg: 286 287 # print some diagnostic info on the constraints 287 print('Error in constraints:\n'+errmsg+288 G2fil.G2Print('Error in constraints:\n'+errmsg+ 288 289 '\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') 290 291 return errmsg, warnmsg 291 292 … … 508 509 except KeyError: # would happen if a referenced histogram were 509 510 # renamed or deleted 510 print('For phase "'+phase+511 G2fil.G2Print('Warning: For phase "'+phase+ 511 512 '" unresolved reference to histogram "'+hist+'"') 512 513 # load the fix background info into the histograms … … 527 528 h['_fixedMult'],h['_fixedVary'] = fixedBkg[1:] 528 529 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 "{}"' 530 531 .format(hist,fixedBkg[0])) 531 532 G2obj.IndexAllIds(Histograms=Histograms,Phases=Phases) … … 596 597 import distutils.file_util as dfu 597 598 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) 600 601 infile = open(GPXback,'rb') 601 602 outfile = open(GPXfile,'wb') … … 636 637 cPickle.dump(data,outfile,1) 637 638 except AttributeError: 638 print ('ERROR - bad data in least squares result')639 G2fil.G2Print ('ERROR - bad data in least squares result') 639 640 infile.close() 640 641 outfile.close() 641 642 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') 643 644 return 644 645 645 print ('GPX file save successful')646 G2fil.G2Print ('GPX file save successful') 646 647 647 648 def GetSeqResult(GPXfile): … … 764 765 ''' 765 766 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) 768 769 GPXphase = os.path.splitext(GPXfile)[0]+'.seqPhase' 769 770 fp = open(GPXphase,'rb') … … 813 814 hdata = cPickleLoad(hist) 814 815 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])) 816 817 data[0] = hdata[0] 817 818 xferItems = ['Background','Instrument Parameters','Sample Parameters','Reflection Lists'] … … 828 829 os.remove(GPXphase) 829 830 except: 830 print('Warning: unable to delete {}'.format(GPXphase))831 G2fil.G2Print('Warning: unable to delete {}'.format(GPXphase)) 831 832 try: 832 833 os.remove(GPXhist) 833 834 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') 836 837 837 838 #============================================================================== … … 3278 3279 Inst = Histogram['Instrument Parameters'] #TODO ? ignores tabulated alp,bet & delt for TOF 3279 3280 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') 3281 3282 Type,instDict,insVary = GetInstParms(hId,Inst[0]) 3282 3283 controlDict[pfx+'histType'] = Type -
trunk/GSASIIstrMain.py
r4009 r4021 36 36 import GSASIIstrMath as G2stMth 37 37 import GSASIIobj as G2obj 38 import GSASIIfiles as G2fil 38 39 39 40 sind = lambda x: np.sin(x*np.pi/180.) … … 129 130 IfOK = False 130 131 covMatrix = [] 131 print ('**** Refinement failed - singular matrix ****')132 G2fil.G2Print ('Warning: **** Refinement failed - singular matrix ****') 132 133 if 'Hessian' in Controls['deriv type']: 133 134 num = len(varyList)-1 134 135 for i,val in enumerate(np.flipud(result[2]['psing'])): 135 136 if val: 136 print ('Bad parameter: '+varyList[num-i])137 G2fil.G2Print('Bad parameter: '+varyList[num-i],mode='warn') 137 138 else: 138 139 Ipvt = result[2]['ipvt'] 139 140 for i,ipvt in enumerate(Ipvt): 140 141 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') 142 143 break 143 144 IfOK = True … … 146 147 sig = np.sqrt(np.diag(covMatrix)) 147 148 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') 149 150 # table = dict(zip(varyList,zip(values,result[0],(result[0]-values)/sig))) 150 151 # for item in table: print item,table[item] #useful debug - are things shifting? … … 155 156 covMatrix = [] 156 157 break 157 print ('**** Refinement failed - singular matrix ****')158 G2fil.G2Print ('**** Refinement failed - singular matrix ****',mode='error') 158 159 if 'Hessian' in Controls['deriv type']: 159 160 if result[1] is None: … … 165 166 for i,val in enumerate(np.flipud(result[2]['psing'])): 166 167 if val: 167 print ('Removing parameter: '+varyList[num-i])168 G2fil.G2Print ('Removing parameter: '+varyList[num-i]) 168 169 del(varyList[num-i]) 169 170 else: … … 171 172 for i,ipvt in enumerate(Ipvt): 172 173 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]) 174 175 del(varyList[ipvt-1]) 175 176 break … … 198 199 Histograms,Phases = G2stIO.GetUsedHistogramsAndPhases(GPXfile) 199 200 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 ***') 202 203 return False,'No phases' 203 204 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 ***') 206 207 return False,'No data' 207 208 rigidbodyDict = G2stIO.GetRigidBodies(GPXfile) … … 240 241 #print 'IndependentVars',G2mv.GetIndependentVars() 241 242 except G2mv.ConstraintException: 242 print (' *** ERROR - your constraints are internally inconsistent ***')243 G2fil.G2Print (' *** ERROR - your constraints are internally inconsistent ***') 243 244 #errmsg, warnmsg = G2mv.CheckConstraints(varyList,constrDict,fixedList) 244 245 #print 'Errors',errmsg … … 274 275 G2stIO.SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,rigidbodyDict,covData,makeBack) 275 276 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 *****') 278 279 else: 279 print ('****ERROR - Refinement failed')280 G2fil.G2Print ('****ERROR - Refinement failed') 280 281 raise G2obj.G2Exception('****ERROR - Refinement failed') 281 282 # except G2obj.G2Exception(Msg): … … 331 332 332 333 printFile = open(ospath.splitext(GPXfile)[0]+'.lst','w') 333 print ('Starting Sequential Refinement')334 G2fil.G2Print ('Starting Sequential Refinement') 334 335 G2stIO.ShowBanner(printFile) 335 336 Controls = G2stIO.GetControls(GPXfile) … … 338 339 Histograms,Phases = G2stIO.GetUsedHistogramsAndPhases(GPXfile) 339 340 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 ***') 342 343 return False,'No phases' 343 344 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 ***') 346 347 return False,'No data' 347 348 rigidbodyDict = G2stIO.GetRigidBodies(GPXfile) … … 352 353 for item in phaseVary: 353 354 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 ****') 356 357 return False,'Lattice parameter refinement error - see console message' 357 358 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 ****') 360 361 return False,'Phase texture refinement error - see console message' 361 362 if 'Seq Data' in Controls: … … 373 374 for ihst,histogram in enumerate(histNames): 374 375 if GSASIIpath.GetConfigValue('Show_timing'): t1 = time.time() 375 print('\nRefining with '+str(histogram))376 G2fil.G2Print('\nRefining with '+str(histogram)) 376 377 ifPrint = False 377 378 if dlg: … … 385 386 calcControls['maxSSwave'] = maxSSwave 386 387 if histogram not in Histograms: 387 print("Error: not found!")388 G2fil.G2Print("Error: not found!") 388 389 continue 389 390 #TODO - implement "Fix FXU" for seq refinement here - done? … … 434 435 constraintInfo = (groups,parmlist,constrDict,fixedList,ihst) 435 436 except G2mv.ConstraintException: 436 print (' *** ERROR - your constraints are internally inconsistent ***')437 G2fil.G2Print (' *** ERROR - your constraints are internally inconsistent ***') 437 438 #errmsg, warnmsg = G2mv.CheckConstraints(varyList,constrDict,fixedList) 438 439 #print 'Errors',errmsg … … 466 467 c = [var for var in combined if var not in newVaryList] 467 468 p = [var for var in combined if var not in firstVaryList] 468 print('*** Variables change ***')469 G2fil.G2Print('*** Variables change ***') 469 470 for typ,vars in [('Removed',c),('Added',p)]: 470 471 line = ' '+typ+': ' … … 472 473 for var in vars: 473 474 if len(line) > 70: 474 print(line)475 G2fil.G2Print(line) 475 476 line = ' ' 476 477 line += var + ', ' 477 478 else: 478 479 line += 'none, ' 479 print(line[:-2])480 G2fil.G2Print(line[:-2]) 480 481 firstVaryList = newVaryList 481 482 … … 488 489 rigidbodyDict,parmDict,varyList,calcControls,pawleyLookup,ifSeq,printFile,dlg, 489 490 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'%( 491 492 Rvals['Rwp'],Rvals['chisq'],Rvals['GOF']**2,Rvals['DelChi2'])) 492 493 # add the uncertainties into the esd dictionary (sigDict) 493 494 if not IfOK: 494 print('***** Sequential refinement failed at histogram '+histogram)495 G2fil.G2Print('***** Sequential refinement failed at histogram '+histogram,mode='warn') 495 496 break 496 497 sigDict = dict(zip(varyList,sig)) … … 531 532 # except G2obj.G2Exception(Msg): 532 533 # printFile.close() 533 # print (' ***** Refinement aborted *****')534 # G2fil.G2Print (' ***** Refinement aborted *****') 534 535 # return False,Msg.msg 535 536 if GSASIIpath.GetConfigValue('Show_timing'): 536 537 t2 = time.time() 537 print("Fit step time {:.2f} sec.".format(t2-t1))538 G2fil.G2Print("Fit step time {:.2f} sec.".format(t2-t1)) 538 539 t1 = t2 539 540 SeqResult['histNames'] = [itm for itm in G2stIO.GetHistogramNames(GPXfile,['PWDR',]) if itm in SeqResult.keys()] 540 541 G2stIO.SetSeqResult(GPXfile,Histograms,SeqResult) 541 542 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 *****') 544 545 return True,'Success' 545 546 … … 782 783 if DATData['Natoms'] == 4: #torsion 783 784 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') 786 787 return # done with torsion 787 788 elif DATData['Natoms'] == 3: #angle 788 789 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') 791 792 else: #2 atoms - distance 792 793 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))) 794 795 795 796 def BestPlane(PlaneData): … … 797 798 798 799 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') 802 803 803 804 ShowBanner(PlaneData['Name']) … … 819 820 for i,xyz in enumerate(XYZ): 820 821 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])) 822 823 Evec,Emat = nl.eig(Zmat) 823 824 Evec = np.sqrt(Evec)/(Natoms-3) … … 825 826 XYZ = np.inner(XYZ,Emat.T).T 826 827 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') 829 830 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]])) 832 833 833 834 def main(): … … 838 839 GPXfile = arg[1] 839 840 if not ospath.exists(GPXfile): 840 print ('ERROR - '+GPXfile+" doesn't exist!")841 G2fil.G2Print ('ERROR - '+GPXfile+" doesn't exist!") 841 842 exit() 842 843 else: 843 print ('ERROR - missing filename')844 G2fil.G2Print ('ERROR - missing filename') 844 845 exit() 845 846 # TODO: figure out if this is a sequential refinement and call SeqRefine(GPXfile,None) 846 847 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)) 848 849 849 850 if __name__ == '__main__': -
trunk/imports/G2img_1TIF.py
r3767 r4021 23 23 import GSASIIobj as G2obj 24 24 import GSASIIpath 25 import GSASIIfiles as G2fil 25 26 import numpy as np 26 27 import time … … 67 68 self.Comments,self.Data,self.Npix,self.Image = GetTifData(filename) 68 69 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") 70 71 import scipy.misc 71 72 self.Image = scipy.misc.imread(filename,flatten=True) … … 120 121 samplechangerpos = float(line.split('=')[1]) 121 122 except: 122 print('error reading metadata: '+line)123 G2fil.G2Print('error reading metadata: '+line) 123 124 Meta.close() 124 125 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') 126 127 head = ['no metadata file found',] 127 128 … … 136 137 IFD = int(st.unpack(byteOrd+'i',File.read(4))[0]) 137 138 else: 138 print (tag)139 # print (tag) 139 140 lines = ['not a detector tiff file',] 140 141 return lines,0,0,0 … … 171 172 time0 = time.time() 172 173 if 34710 in IFD: 173 print ('Read MAR CCD tiff file: '+filename)174 G2fil.G2Print ('Read MAR CCD tiff file: '+filename) 174 175 marFrame = rmf.marFrame(File,byteOrd,IFD) 175 176 image = np.flipud(np.array(np.asarray(marFrame.image),dtype=np.int32)) … … 196 197 from PIL import Image as Im 197 198 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") 199 200 #raise Exception("PIL/pillow Image module not found") 200 201 lines = ['not a detector tiff file',] … … 215 216 pixy = [172.,172.] 216 217 File.seek(4096) 217 print ('Read Pilatus tiff file: '+filename)218 G2fil.G2Print ('Read Pilatus tiff file: '+filename) 218 219 image = np.array(np.frombuffer(File.read(4*Npix),dtype=np.int32),dtype=np.int32) 219 220 else: … … 222 223 tifType = 'Dexela' 223 224 pixy = [74.8,74.8] 224 print ('Read Dexela detector tiff file: '+filename)225 G2fil.G2Print ('Read Dexela detector tiff file: '+filename) 225 226 else: 226 227 tifType = 'GE' 227 228 pixy = [200.,200.] 228 print ('Read GE-detector tiff file: '+filename)229 G2fil.G2Print ('Read GE-detector tiff file: '+filename) 229 230 File.seek(8) 230 231 image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.uint16),dtype=np.int32) … … 234 235 pixy = [200.,200.] 235 236 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) 237 238 image = np.array(ar.array('I',File.read(4*Npix)),dtype=np.uint32) 238 239 elif 270 in IFD: … … 244 245 pixy = [200.,200.]*IFD[277][2][0] 245 246 File.seek(IFD[273][2][0]) 246 print ('Read ImageJ tiff file: '+filename)247 G2fil.G2Print ('Read ImageJ tiff file: '+filename) 247 248 if IFD[258][2][0] == 32: 248 249 image = File.read(4*Npix) … … 262 263 pixy = [158.,158.] 263 264 File.seek(512) 264 print ('Read DND SAX/WAX-detector tiff file: '+filename)265 G2fil.G2Print ('Read DND SAX/WAX-detector tiff file: '+filename) 265 266 image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.uint16),dtype=np.int32) 266 267 elif sizexy == [1536,1536]: … … 268 269 pixy = [150.,150.] 269 270 File.seek(64) 270 print ('Read Gold tiff file:'+filename)271 G2fil.G2Print ('Read Gold tiff file:'+filename) 271 272 image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.uint16),dtype=np.int32) 272 273 elif sizexy == [2048,2048] or sizexy == [1024,1024] or sizexy == [3072,3072]: … … 276 277 pixy = [200.,200.] 277 278 File.seek(8) 278 print ('Read APS PE-detector tiff file: '+filename)279 G2fil.G2Print ('Read APS PE-detector tiff file: '+filename) 279 280 if dataType == 5: 280 281 image = np.array(np.frombuffer(File.read(4*Npix),dtype=np.float32),dtype=np.int32) #fastest … … 285 286 pixy = [46.9,46.9] 286 287 File.seek(8) 287 print ('Read MedOptics D1 tiff file: '+filename)288 G2fil.G2Print ('Read MedOptics D1 tiff file: '+filename) 288 289 image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.uint16),dtype=np.int32) 289 290 … … 296 297 tifType = 'MAR325' 297 298 File.seek(4096) 298 print ('Read MAR CCD tiff file: '+filename)299 G2fil.G2Print ('Read MAR CCD tiff file: '+filename) 299 300 image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.uint16),dtype=np.int32) 300 301 elif IFD[273][2][0] == 512: … … 302 303 pixy = [200.,200.] 303 304 File.seek(512) 304 print ('Read 11-ID-C tiff file: '+filename)305 G2fil.G2Print ('Read 11-ID-C tiff file: '+filename) 305 306 image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.uint16),dtype=np.int32) 306 307 … … 311 312 pixy = [9.,9.] 312 313 File.seek(8) 313 print ('Read APS scanCCD tiff file: '+filename)314 G2fil.G2Print ('Read APS scanCCD tiff file: '+filename) 314 315 image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32) 315 316 elif IFD[258][2][0] == 32: … … 317 318 pixy = [100.,100.] 318 319 File.seek(8) 319 print ('Read PE 4Kx4K tiff file: '+filename)320 G2fil.G2Print ('Read PE 4Kx4K tiff file: '+filename) 320 321 image = np.array(np.frombuffer(File.read(4*Npix),dtype=np.float32)/2.**4,dtype=np.int32) 321 322 elif IFD[273][2][0] == 4096: … … 323 324 pixy = [73.242,73.242] 324 325 File.seek(4096) 325 print ('Read Rayonix MX300HE tiff file: '+filename)326 G2fil.G2Print ('Read Rayonix MX300HE tiff file: '+filename) 326 327 image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.uint16),dtype=np.int32) 327 328 elif sizexy == [391,380]: … … 362 363 lines = ['not a known detector tiff file',] 363 364 return lines,0,0,0 364 print ('image read time: %.3f'%(time.time()-time0))365 G2fil.G2Print ('image read time: %.3f'%(time.time()-time0)) 365 366 image = np.reshape(image,(sizexy[1],sizexy[0])) 366 367 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.