Dear all,

attached a patch (applies to svn version 4020) that introduces the
configuration variable 'suppress_info'. Setting it to 'True' will
suppress all output of informational nature as e.g. emitted by
readers/writers (file loaded/saved) or by many of the functions in G2sc
(histograms loaded, HAP parameters copied, ...). I found this quite
useful in scriptable to prevent my output from becoming hidden in lots
of (uninteresting) information. Default is 'False', i.e. the default
behavior of GSASII does not change with this patch. 'suppress_info' can
either be set in the GUI (Preferences) or from a script as e.g.


# initialize 'suppress_info': Default 'False' but set it to 'True'
GSASIIpath.SetConfigValue({'suppress_info' : [False, True]})

# do some things

if foo:
    # temporarily enable output of info
    GSASIIpath.SetConfigValue({'suppress_info' : [False, False]})

    # do stuff

    # disable output of info again
    GSASIIpath.SetConfigValue({'suppress_info' : [False, True]})

# continue, output of info is disabled again


I am not sure whether I caught all the places that emit info but I would
check the full sources, if the patch gets applied.

BTW: GetConfigValue(key,default=None) only reports locally changed
values (stored in config.py). For keys not present it returns 'False'
(unless 'default' is specified). Thus, for keys kept at their non-False
default (specified in config_example.py) the function returns the wrong
value unless the individual default value is specified in the call. This
looks fragile to me. If a default value is changed in future, both,
config_examples.py (used for Preferences in the GUI) and in addition all
calling sites have to reflect this change consistently. Would it make
sense at start-up to first parse config_examples.py (maybe change its
name to something more descriptive) and then update locally changed keys
from config.py?

gruss
-- 
Dr. Ivo Alxneit
Catalysis for Energy Group
Bioenergy and Catalysis Laboratory        phone: +41 56 310 4092
Paul Scherrer Institute                     fax: +41 56 310 2688
CH-5232 Villigen                      gnupg key: 0x515E30C7
Switzerland
https://www.psi.ch/ceg/
diff --git a/GSASIImpsubs.py b/GSASIImpsubs.py
index 059d76f..2e6b5ef 100644
--- a/GSASIImpsubs.py
+++ b/GSASIImpsubs.py
@@ -62,7 +62,7 @@ def InitMP(allowMP=True):
     if ncores < 0: ncores = mp.cpu_count()//2
     if ncores > 1:
         useMP = True
-    if useMP:
+    if useMP and not GSASIIpath.GetConfigValue('suppress_info'):
         print('Multiprocessing with {} cores enabled'.format(ncores))
     return useMP,ncores
 
diff --git a/GSASIIscriptable.py b/GSASIIscriptable.py
index fbbed81..27699a1 100644
--- a/GSASIIscriptable.py
+++ b/GSASIIscriptable.py
@@ -892,7 +892,8 @@ def SaveDictToProjFile(Project,nameList,ProjFile):
             cPickle.dump(data,file,1)
     finally:
         file.close()
-    print('gpx file saved as %s'%ProjFile)
+    if not GSASIIpath.GetConfigValue('suppress_info'):
+        print('gpx file saved as %s'%ProjFile)
 
 # def ImportPowder(reader,filename):
 #     '''Use a reader to import a powder diffraction data file
@@ -1216,11 +1217,13 @@ def import_generic(filename, readerlist, fmthint=None, bank=None):
                     print("Read warning by", rd.formatName, "reader:",
                           rd.warnings, file=sys.stderr)
                 elif bank is None:
-                    print("{} read by Reader {}"
-                              .format(filename,rd.formatName))
+                    if not GSASIIpath.GetConfigValue('suppress_info'):
+                        print("{} read by Reader {}"
+                                  .format(filename,rd.formatName))
                 else:
-                    print("{} block # {} read by Reader {}"
-                              .format(filename,bank,rd.formatName))
+                    if not GSASIIpath.GetConfigValue('suppress_info'):
+                        print("{} block # {} read by Reader {}"
+                                  .format(filename,bank,rd.formatName))
                 return rd_list
     raise G2ImportException("No reader could read file: " + filename)
 
@@ -1290,7 +1293,8 @@ def load_pwd_from_reader(reader, instprm, existingnames=[],bank=None):
         Iparm1, Iparm2 = instprm
     except ValueError:
         Iparm1, Iparm2 = load_iprms(instprm, reader, bank=bank)
-        print('Instrument parameters read:',reader.instmsg)
+        if not GSASIIpath.GetConfigValue('suppress_info'):
+            print('Instrument parameters read:',reader.instmsg)
     Ymin = np.min(reader.powderdata[1])
     Ymax = np.max(reader.powderdata[1])
     valuesdict = {'wtFactor': 1.0,
@@ -2119,7 +2123,8 @@ class G2Project(G2ObjectWrapper):
         PDFdict = {'data':None,'PDF Controls':Controls, 'PDF Peaks':peaks}
         self.names.append([PDFname]+['PDF Controls', 'PDF Peaks'])
         self.data[PDFname] = PDFdict
-        print('Adding "{}" to project'.format(PDFname))
+        if not GSASIIpath.GetConfigValue('suppress_info'):
+            print('Adding "{}" to project'.format(PDFname))
         return G2PDF(self.data[PDFname], PDFname, self)
 
     def seqref(self):
@@ -3872,9 +3877,9 @@ class G2Phase(G2ObjectWrapper):
             for item in list(copydict.keys()):
                 if item not in use:
                     del copydict[item]
-
-        print('Copying item(s) {} from histogram {}'.format(list(copydict.keys()),sourcehist))
-        print(' to histogram(s) {}'.format([self._decodeHist(h) for h in targethistlist]))
+        if not GSASIIpath.GetConfigValue('suppress_info'):
+            print('Copying item(s) {} from histogram {}'.format(list(copydict.keys()),sourcehist))
+            print(' to histogram(s) {}'.format([self._decodeHist(h) for h in targethistlist]))
         for h in targethistlist:
             h = self._decodeHist(h)
             if h not in self.data['Histograms']:
@@ -3946,8 +3951,9 @@ class G2Phase(G2ObjectWrapper):
                                         self.name,len(self.data['Histograms'][h]['HStrain'][0])))
                         raise Exception('HStrain has differing numbers of terms.')
             self.data['Histograms'][h].update(copy.deepcopy(copydict))            
-        print('Copied item(s) {} from dict'.format(list(copydict.keys())))
-        print(' to histogram(s) {}'.format([self._decodeHist(h) for h in targethistlist]))
+        if not GSASIIpath.GetConfigValue('suppress_info'):
+            print('Copied item(s) {} from dict'.format(list(copydict.keys())))
+            print(' to histogram(s) {}'.format([self._decodeHist(h) for h in targethistlist]))
 
 class G2SeqRefRes(G2ObjectWrapper):
     '''Wrapper for a Sequential Refinement Results tree entry, containing the 
@@ -4529,7 +4535,8 @@ class G2Image(G2ObjectWrapper):
         elif 'gain' in typ.lower():
             #key = 'Gain map'
             if mult is not None:
-                print('Ignoring multiplier for Gain map')
+                if not GSASIIpath.GetConfigValue('suppress_info'):
+                    print('Ignoring multiplier for Gain map')
             mult = None
         else:
             raise Exception("Invalid typ {} for setControlFile".format(typ))
@@ -4553,10 +4560,12 @@ class G2Image(G2ObjectWrapper):
             Slines = File.readlines()
             File.close()
             G2fil.LoadControls(Slines,self.data['Image Controls'])
-            print('file {} read into {}'.format(filename,self.name))
+            if not GSASIIpath.GetConfigValue('suppress_info'):
+                print('file {} read into {}'.format(filename,self.name))
         elif imgDict:
             self.data['Image Controls'].update(imgDict)
-            print('Image controls set')
+            if not GSASIIpath.GetConfigValue('suppress_info'):
+                print('Image controls set')
         else:
             raise Exception("loadControls called without imgDict or filename specified")
 
@@ -4567,7 +4576,8 @@ class G2Image(G2ObjectWrapper):
           with .imctrl
         '''
         G2fil.WriteControls(filename,self.data['Image Controls'])
-        print('file {} written from {}'.format(filename,self.name))
+        if not GSASIIpath.GetConfigValue('suppress_info'):
+            print('file {} written from {}'.format(filename,self.name))
 
     def loadMasks(self,filename,ignoreThreshold=False):
         '''load masks from a .immask file
@@ -4579,7 +4589,8 @@ class G2Image(G2ObjectWrapper):
           in the file are ignored.
         '''
         G2fil.readMasks(filename,self.data['Masks'],ignoreThreshold)
-        print('file {} read into {}'.format(filename,self.name))
+        if not GSASIIpath.GetConfigValue('suppress_info'):
+            print('file {} read into {}'.format(filename,self.name))
         
     def getVary(self,*args):
         '''Return the refinement flag(s) for Image Controls parameter(s)
@@ -4778,11 +4789,13 @@ class G2Image(G2ObjectWrapper):
                 'refOffset':-0.1*Ymax,'refDelt':0.1*Ymax,'Yminmax':[Ymin,Ymax]}
             # if Aname is already in the project replace it
             for j in self.proj.names:
-                if j[0] == Aname: 
-                    print('Replacing "{}" in project'.format(Aname))
+                if j[0] == Aname:
+                    if not GSASIIpath.GetConfigValue('suppress_info'):
+                        print('Replacing "{}" in project'.format(Aname))
                     break
             else:
-                print('Adding "{}" to project'.format(Aname))
+                if not GSASIIpath.GetConfigValue('suppress_info'):
+                    print('Adding "{}" to project'.format(Aname))
                 self.proj.names.append([Aname]+
                         [u'Comments',u'Limits',u'Background',u'Instrument Parameters',
                          u'Sample Parameters', u'Peak List', u'Index Peak List',
diff --git a/GSASIIstrIO.py b/GSASIIstrIO.py
index 93ac36a..f9f0d67 100644
--- a/GSASIIstrIO.py
+++ b/GSASIIstrIO.py
@@ -595,8 +595,9 @@ def SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,RigidBodies,CovData,mak
                         
     import distutils.file_util as dfu
     GPXback = GPXBackup(GPXfile,makeBack)
-    print ('Read from file:'+GPXback)
-    print ('Save to file  :'+GPXfile)
+    if not GSASIIpath.GetConfigValue('suppress_info'):
+        print ('Read from file:'+GPXback)
+        print ('Save to file  :'+GPXfile)
     infile = open(GPXback,'rb')
     outfile = open(GPXfile,'wb')
     while True:
@@ -642,7 +643,8 @@ def SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,RigidBodies,CovData,mak
             print ('GPX file save failed - old version retained')
             return
             
-    print ('GPX file save successful')
+    if not GSASIIpath.GetConfigValue('suppress_info'):
+        print ('GPX file save successful')
     
 def GetSeqResult(GPXfile):
     '''
diff --git a/GSASIIstrMain.py b/GSASIIstrMain.py
index b56c26a..b410cec 100644
--- a/GSASIIstrMain.py
+++ b/GSASIIstrMain.py
@@ -55,7 +55,7 @@ def RefineCore(Controls,Histograms,Phases,restraintDict,rigidbodyDict,parmDict,v
 #    print 'current',varyList
 #    for item in parmDict: print item,parmDict[item] ######### show dict just before refinement
     G2mv.Map2Dict(parmDict,varyList)
-    ifPrint = True
+    ifPrint = not GSASIIpath.GetConfigValue('suppress_info')
     if ifSeq:
         ifPrint = False
     Rvals = {}
@@ -273,8 +273,9 @@ def Refine(GPXfile,dlg=None,makeBack=True,refPlotUpdate=None):
             G2stIO.SetHistogramData(parmDict,sigDict,Histograms,calcControls['FFtables'],pFile=printFile)
             G2stIO.SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,rigidbodyDict,covData,makeBack)
             printFile.close()
-            print (' Refinement results are in file: '+ospath.splitext(GPXfile)[0]+'.lst')
-            print (' ***** Refinement successful *****')
+            if not GSASIIpath.GetConfigValue('suppress_info'):
+                print (' Refinement results are in file: '+ospath.splitext(GPXfile)[0]+'.lst')
+                print (' ***** Refinement successful *****')
         else:
             print ('****ERROR - Refinement failed')
             raise G2obj.G2Exception('****ERROR - Refinement failed')
@@ -330,7 +331,8 @@ def SeqRefine(GPXfile,dlg,refPlotUpdate=None):
     ptx.pyqlmninit()            #initialize fortran arrays for spherical harmonics
 
     printFile = open(ospath.splitext(GPXfile)[0]+'.lst','w')
-    print ('Starting Sequential Refinement')
+    if not GSASIIpath.GetConfigValue('suppress_info'):
+        print ('Starting Sequential Refinement')
     G2stIO.ShowBanner(printFile)
     Controls = G2stIO.GetControls(GPXfile)
     G2stIO.ShowControls(Controls,printFile,SeqRef=True)
@@ -539,8 +541,9 @@ def SeqRefine(GPXfile,dlg,refPlotUpdate=None):
     SeqResult['histNames'] = [itm for itm in G2stIO.GetHistogramNames(GPXfile,['PWDR',]) if itm in SeqResult.keys()]
     G2stIO.SetSeqResult(GPXfile,Histograms,SeqResult)
     printFile.close()
-    print (' Sequential refinement results are in file: '+ospath.splitext(GPXfile)[0]+'.lst')
-    print (' ***** Sequential refinement successful *****')
+    if not GSASIIpath.GetConfigValue('suppress_info'):
+        print (' Sequential refinement results are in file: '+ospath.splitext(GPXfile)[0]+'.lst')
+        print (' ***** Sequential refinement successful *****')
     return True,'Success'
 
 def RetDistAngle(DisAglCtls,DisAglData):
diff --git a/config_example.py b/config_example.py
index a251235..92fb00c 100644
--- a/config_example.py
+++ b/config_example.py
@@ -199,3 +199,9 @@ line colors in order of obs., calc., back., diff., color5 & color6 separated by
 PDF_Rmax = 100.
 '''Maximum radius for G(r) calculations: range is from 10-200A; default is 100A
 '''
+
+suppress_info = False
+""" Set to 'True' to suppress all output of purely informational nature (but still report warnings or errors)
+that is provided by e.g. readers / writers, that documents progress of the refinement, or that is provided
+by different functions of GSASII.scriptable. Default is to output info.
+"""

Attachment: signature.asc
Description: OpenPGP digital signature

_______________________________________________
GSAS-II mailing list
[email protected]
https://mailman.aps.anl.gov/mailman/listinfo/gsas-ii

Reply via email to