Changeset 4833


Ignore:
Timestamp:
Mar 1, 2021 8:32:50 AM (8 months ago)
Author:
toby
Message:

popup menu for GSGrids; split off sequential display; rename File menu in background, reload atoms to update; select atoms from listbox; copy selected to drawatoms; right-click draw & atoms popups; fix atom highlighting in Atoms tab; help button on plots & help updates; spyder cleanup & reformat

Location:
trunk
Files:
1 added
6 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIctrlGUI.py

    r4822 r4833  
    45474547            if rowLblCallback: wx.EVT_MOTION(self.GetGridRowLabelWindow(), OnMouseMotion)
    45484548
     4549    def setupPopup(self,lblList,callList):
     4550        '''define a callback that creates a popup menu. The rows associated
     4551        with the items selected items are selected in the table and if
     4552        an item is called from the menu, the corresponding function
     4553        is called to perform an action on the
     4554
     4555        :param list lblList: list of str items that will be placed in the
     4556          popup menu
     4557        :param list callList: list of functions to be called when a
     4558        :returns: a callback that can be used to create the menu
     4559
     4560        Sample usage::
     4561
     4562            lblList = ('Delete','Set atom style','Set atom label',
     4563                           'Set atom color','Set view point','Generate copy',
     4564                           'Generate surrounding sphere','Transform atoms',
     4565                           'Generate bonded')
     4566            callList = (DrawAtomsDelete,DrawAtomStyle, DrawAtomLabel,
     4567                            DrawAtomColor,SetViewPoint,AddSymEquiv,
     4568                            AddSphere,TransformSymEquiv,
     4569                            FillCoordSphere)
     4570            onRightClick = drawAtoms.setupPopup(lblList,callList)
     4571            drawAtoms.Bind(wg.EVT_GRID_CELL_RIGHT_CLICK, onRightClick)
     4572            drawAtoms.Bind(wg.EVT_GRID_LABEL_RIGHT_CLICK, onRightClick)
     4573
     4574        '''
     4575        def createPopup(event):
     4576            def OnPopup(event):
     4577                callback = callList[menuIndx.index(event.GetId())]
     4578                self.ClearSelection()
     4579                for r in indx:
     4580                    self.SelectRow(r,True)
     4581                callback(event)
     4582            # get selections
     4583            indx = self.GetSelectedRows()
     4584            indx += [row for row,col in self.GetSelectedCells()]
     4585            for top,bottom in zip([r for r,c in self.GetSelectionBlockTopLeft()],
     4586                          [r for r,c in self.GetSelectionBlockBottomRight()]):
     4587                indx += list(range(top,bottom+1))
     4588            indx = list(set(indx))
     4589            if len(indx) == 0: # nothing selected, get current row
     4590                r,_ =  event.GetRow(),event.GetCol()
     4591                if r < 0:
     4592                    return
     4593                indx = [r]
     4594            # make a pop-up menu
     4595            menu = wx.Menu()
     4596            menuIndx = []
     4597            for l in lblList:
     4598                menuIndx.append(wx.NewIdRef())
     4599                menu.Append(menuIndx[-1], l)
     4600                self.Bind(wx.EVT_MENU, OnPopup, id=menuIndx[-1])
     4601            self.PopupMenu(menu)
     4602            menu.Destroy()
     4603        return createPopup
     4604       
    45494605    def completeEdits(self):
    45504606        'complete any outstanding edits'
  • trunk/GSASIIdataGUI.py

    r4829 r4833  
    11# -*- coding: utf-8 -*-
    22#GSASIIdataGUI - Main GUI routines
    3 ########### SVN repository information ###################
     3#========== SVN repository information ###################
    44# $Date$
    55# $Author$
     
    77# $URL$
    88# $Id$
    9 ########### SVN repository information ###################
     9#=========- SVN repository information ###################
    1010'''
    1111*GSASIIdataGUI: Main GSAS-II GUI*
     
    5353    pass
    5454import scipy as sp
    55 import scipy.optimize as so
     55#import scipy.optimize as so
    5656try:
    5757    import wx
    58     import wx.grid as wg
     58#    import wx.grid as wg
    5959    #import wx.wizard as wz
    6060    #import wx.aui
     
    7878import GSASIIrestrGUI as G2restG
    7979import GSASIIobj as G2obj
    80 import GSASIIexprGUI as G2exG
     80#import GSASIIexprGUI as G2exG
    8181import GSASIIlog as log
    8282import GSASIIctrlGUI as G2G
     
    8686import defaultIparms as dI
    8787import GSASIIfpaGUI as G2fpa
     88import GSASIIseqGUI as G2seq
    8889
    8990try:
     
    17671768            else:
    17681769                self.ErrorDialog('Open Error',u'Error opening instrument parameter file '
    1769                     +u'{} requested by file '.format(instfile,filename))
     1770                    +u'{} requested by file {}'.format(instfile,filename))
    17701771        #Finally - ask user for Instrument parametrs file - seems it can't be in a zip file
    17711772        while True: # loop until we get a file that works or we get a cancel
     
    52275228            else:
    52285229                msg = ''
    5229             result = wx.ID_NO
    52305230            try:
    52315231                dlg = wx.MessageDialog(self, msg,'Note singularities',
     
    52335233                dlg.CenterOnParent()
    52345234                dlg.SetSize((700,300)) # does not resize on Mac
    5235                 result = dlg.ShowModal()
     5235                dlg.ShowModal()
    52365236            finally:
    52375237                dlg.Destroy()
     
    58745874        self.PrefillDataMenu(self.BackMenu)
    58755875        self.BackEdit = wx.Menu(title='')
    5876         self.BackMenu.Append(menu=self.BackEdit, title='File')
     5876        self.BackMenu.Append(menu=self.BackEdit, title='Background')
    58775877        self.BackEdit.Append(G2G.wxID_BACKCOPY,'Copy','Copy background parameters to other histograms')
    58785878        self.BackEdit.Append(G2G.wxID_BACKFLAGCOPY,'Copy flags',
     
    62366236            'wxID_ATOMSPDISAGL', 'wxID_ISODISP', 'wxID_ADDHATOM', 'wxID_UPDATEHATOM',
    62376237            'wxID_ATOMSROTATE', 'wxID_ATOMSDENSITY','wxID_ATOMSBNDANGLHIST',
    6238             'wxID_ATOMSSETALL', 'wxID_ATOMSSETSEL','wxID_ATOMFRACSPLIT','wxID_COLLECTATOMS')
     6238            'wxID_ATOMSSETALL', 'wxID_ATOMSSETSEL','wxID_ATOMFRACSPLIT','wxID_COLLECTATOMS',
     6239            'wxID_ATOMSSETVP', 'wxID_ATOMSSETLST')
    62396240        self.AtomsMenu = wx.MenuBar()
    62406241        self.PrefillDataMenu(self.AtomsMenu)
     
    62526253        submenu.Append(G2G.wxID_ATOMSEDITDELETE,'Delete atom','Delete selected atoms')
    62536254        submenu.Append(G2G.wxID_ATOMSTRANSFORM,'Transform atoms','Symmetry transform selected atoms')
    6254         submenu.Append(G2G.wxID_ATOMSSETALL,'Select All','Set refinement flags for all atoms')
    6255        
     6255        submenu.Append(G2G.wxID_ATOMSSETALL,'Select All','Select all atoms')
     6256        submenu.Append(G2G.wxID_ATOMSSETLST,'Select from list','Select atoms from a filtered listbox')
     6257
    62566258        self.AtomEdit.Append(G2G.wxID_ATOMSEDITADD,'Append atom','Appended as an H atom')
    62576259        self.AtomEdit.Append(G2G.wxID_ATOMSVIEWADD,'Append view point','Appended as an H atom')
     
    62596261        self.AtomEdit.Append(G2G.wxID_UPDATEHATOM,'Update H atoms','Update H atoms in standard positions')
    62606262        self.AtomEdit.Append(G2G.wxID_ATOMMOVE,'Move selected atom to view point','Select a single atom to be moved to view point in plot')
     6263        self.AtomEdit.Append(G2G.wxID_ATOMSSETVP,'Set view point','Set the view point from positions of selected atom(s)')
     6264
    62616265        self.AtomEdit.Append(G2G.wxID_MAKEMOLECULE,'Assemble molecule','Select a single atom to assemble as a molecule from scattered atom positions')
    62626266        self.AtomEdit.Append(G2G.wxID_COLLECTATOMS,'Collect atoms','Collect selected atoms to specified unit cell location')
    6263         self.AtomEdit.Append(G2G.wxID_RELOADDRAWATOMS,'Reload draw atoms','Reload atom drawing list')
     6267        self.AtomEdit.Append(G2G.wxID_RELOADDRAWATOMS,'Update draw atoms','Update atom drawing list')
    62646268        submenu = wx.Menu()
    62656269        self.AtomEdit.AppendSubMenu(submenu,'Reimport atoms','Reimport atoms from file; sequence must match')
     
    63406344            'wxID_DRAWVIEWPOINT', 'wxID_DRAWTRANSFORM', 'wxID_DRAWDELETE', 'wxID_DRAWFILLCELL',
    63416345            'wxID_DRAWADDEQUIV', 'wxID_DRAWFILLCOORD', 'wxID_DRAWDISAGLTOR', 'wxID_DRAWPLANE',
    6342             'wxID_DRAWDISTVP', 'wxID_DRAWADDSPHERE', 'wxID_DRWAEDITRADII',)
     6346            'wxID_DRAWDISTVP', 'wxID_DRAWADDSPHERE', 'wxID_DRWAEDITRADII',
     6347            'wxID_DRAWSETSEL', 'wxID_DRAWLOADSEL',           
     6348            )
    63436349        G2G.Define_wxId('wxID_DRAWRESTRBOND', 'wxID_DRAWRESTRANGLE', 'wxID_DRAWRESTRPLANE', 'wxID_DRAWRESTRCHIRAL',)       
    63446350        self.DrawAtomsMenu = wx.MenuBar()
     
    63596365        self.DrawAtomEdit.Append(G2G.wxID_DRWAEDITRADII,'Edit atom radii','Edit drawing atom radii') # TODO: removed until it can be made to do something
    63606366        self.DrawAtomEdit.Append(G2G.wxID_DRAWVIEWPOINT,'View point','View point is 1st atom selected')
     6367        self.DrawAtomEdit.Append(G2G.wxID_DRAWSETSEL,'Select from list','Select atoms from a filtered listbox')
    63616368        self.DrawAtomEdit.Append(G2G.wxID_DRAWADDEQUIV,'Add atoms','Add symmetry & cell equivalents to drawing set from selected atoms')
    63626369        self.DrawAtomEdit.Append(G2G.wxID_DRAWADDSPHERE,'Add sphere of atoms','Add atoms within sphere of enclosure')
     
    63686375        G2G.Define_wxId('wxID_DRAWVOIDMAP')
    63696376        self.DrawAtomEdit.Append(G2G.wxID_DRAWVOIDMAP,'Create void map','Create a map of locations outside of any VDW radius')
    6370         self.DrawAtomEdit.Append(G2G.wxID_DRAWDELETE,'Delete atoms','Delete atoms from drawing set')
     6377        self.DrawAtomEdit.Append(G2G.wxID_DRAWDELETE,'Delete atoms','Delete selected atoms from drawing set')
    63716378        G2G.Define_wxId('wxID_RELOADATOMS')
    6372         self.DrawAtomEdit.Append(G2G.wxID_RELOADATOMS,'Reload draw atoms','Reload atom drawing list')
    6373        
     6379        self.DrawAtomEdit.Append(G2G.wxID_RELOADATOMS,'Update draw atoms','Update atom drawing list')
     6380        self.DrawAtomEdit.Append(G2G.wxID_DRAWLOADSEL,'Load selected atoms','Copy selected atoms into draw atoms')
     6381
    63746382        self.DrawAtomCompute.Append(G2G.wxID_DRAWDISTVP,'View pt. dist.','Compute distance of selected atoms from view point')   
    63756383        self.DrawAtomCompute.Append(G2G.wxID_DRAWDISAGLTOR,'Dist. Ang. Tors.',
     
    65656573            choices = [i for i in choices if i in usedHistograms]
    65666574            if len(choices) == 0:
    6567                 G2G.G2MessageBox(self,
     6575                G2G.G2MessageBox(G2frame,
    65686576                                'No histograms in use found for a sequential fit.',
    65696577                                'No Histograms')
     
    68146822    G2frame.SendSizeEvent()
    68156823   
    6816 
    6817 #####  Display of Sequential Results ##########################################
    6818 def UpdateSeqResults(G2frame,data,prevSize=None):
    6819     """
    6820     Called when the Sequential Results data tree entry is selected
    6821     to show results from a sequential refinement.
    6822    
    6823     :param wx.Frame G2frame: main GSAS-II data tree windows
    6824 
    6825     :param dict data: a dictionary containing the following items: 
    6826 
    6827             * 'histNames' - list of histogram names in order as processed by Sequential Refinement
    6828             * 'varyList' - list of variables - identical over all refinements in sequence
    6829               note that this is the original list of variables, prior to processing
    6830               constraints.
    6831             * 'variableLabels' -- a dict of labels to be applied to each parameter
    6832               (this is created as an empty dict if not present in data).
    6833             * keyed by histName - dictionaries for all data sets processed, which contains:
    6834 
    6835               * 'variables'- result[0] from leastsq call
    6836               * 'varyList' - list of variables passed to leastsq call (not same as above)
    6837               * 'sig' - esds for variables
    6838               * 'covMatrix' - covariance matrix from individual refinement
    6839               * 'title' - histogram name; same as dict item name
    6840               * 'newAtomDict' - new atom parameters after shifts applied
    6841               * 'newCellDict' - refined cell parameters after shifts to A0-A5 from Dij terms applied'
    6842     """
    6843     def GetSampleParms():
    6844         '''Make a dictionary of the sample parameters that are not the same over the
    6845         refinement series. Controls here is local
    6846         '''
    6847         if 'IMG' in histNames[0]:
    6848             sampleParmDict = {'Sample load':[],}
    6849         else:
    6850             sampleParmDict = {'Temperature':[],'Pressure':[],'Time':[],
    6851                 'FreePrm1':[],'FreePrm2':[],'FreePrm3':[],'Omega':[],
    6852                 'Chi':[],'Phi':[],'Azimuth':[],}
    6853         Controls = G2frame.GPXtree.GetItemPyData(
    6854             GetGPXtreeItemId(G2frame,G2frame.root, 'Controls'))
    6855         sampleParm = {}
    6856         for name in histNames:
    6857             if 'IMG' in name:
    6858                 if name not in data:
    6859                     continue
    6860                 for item in sampleParmDict:
    6861                     sampleParmDict[item].append(data[name]['parmDict'].get(item,0))
    6862             else:
    6863                 if 'PDF' in name:
    6864                     name = 'PWDR' + name[4:]
    6865                 Id = GetGPXtreeItemId(G2frame,G2frame.root,name)
    6866                 if Id:
    6867                     sampleData = G2frame.GPXtree.GetItemPyData(GetGPXtreeItemId(G2frame,Id,'Sample Parameters'))
    6868                     for item in sampleParmDict:
    6869                         sampleParmDict[item].append(sampleData.get(item,0))
    6870         for item in sampleParmDict:
    6871             if sampleParmDict[item]:
    6872                 frstValue = sampleParmDict[item][0]
    6873                 if np.any(np.array(sampleParmDict[item])-frstValue):
    6874                     if item.startswith('FreePrm'):
    6875                         sampleParm[Controls[item]] = sampleParmDict[item]
    6876                     else:
    6877                         sampleParm[item] = sampleParmDict[item]
    6878         return sampleParm
    6879 
    6880     def GetColumnInfo(col):
    6881         '''returns column label, lists of values and errors (or None) for each column in the table
    6882         for plotting. The column label is reformatted from Unicode to MatPlotLib encoding
    6883         '''
    6884         colName = G2frame.SeqTable.GetColLabelValue(col)
    6885         plotName = variableLabels.get(colName,colName)
    6886         plotName = plotSpCharFix(plotName)
    6887         return plotName,G2frame.colList[col],G2frame.colSigs[col]
    6888            
    6889     def PlotSelectedColRow(calltyp=''):
    6890         '''Called to plot a selected column or row by clicking or
    6891         double-clicking on a row or column label. N.B. This is called
    6892         after the event is processed so that the column or row has been
    6893         selected.
    6894 
    6895         :param str calltyp: ='single'/'double', specifies if this was
    6896           a single- or double-click, where a single click on row
    6897           plots histogram; Double click on row plots V-C matrix;
    6898           Single or double click on column: plots values in column
    6899         '''
    6900         cols = G2frame.dataDisplay.GetSelectedCols()
    6901         rows = G2frame.dataDisplay.GetSelectedRows()
    6902         if cols:
    6903             G2plt.PlotSelectedSequence(G2frame,cols,GetColumnInfo,SelectXaxis)
    6904         elif rows and calltyp == 'single':
    6905             name = histNames[rows[0]]       #only does 1st one selected
    6906             if not name.startswith('PWDR'): return
    6907             pickId = G2frame.PickId
    6908             G2frame.PickId = G2frame.PatternId = GetGPXtreeItemId(G2frame, G2frame.root, name)
    6909             G2plt.PlotPatterns(G2frame,newPlot=False,plotType='PWDR')
    6910             G2frame.PickId = pickId
    6911         elif rows:
    6912             name = histNames[rows[0]]       #only does 1st one selected
    6913             G2plt.PlotCovariance(G2frame,data[name])
    6914         else:
    6915             G2frame.ErrorDialog(
    6916                 'Select row or columns',
    6917                 'Nothing selected in table. Click on column or row label(s) to plot. N.B. Grid selection can be a bit funky.'
    6918                 )
    6919        
    6920     def PlotSSelect(event):
    6921         'Called by a single click on a row or column label. '
    6922         event.Skip()
    6923         wx.CallAfter(PlotSelectedColRow,'single')
    6924        
    6925     def PlotSelect(event):
    6926         'Called by a double-click on a row or column label'
    6927         event.Skip()
    6928         wx.CallAfter(PlotSelectedColRow,'double')
    6929        
    6930     def OnKeyUp(event):
    6931         event.Skip()
    6932         wx.CallAfter(PlotSelectedColRow,'single')
    6933            
    6934     def OnPlotSelSeq(event):
    6935         'plot the selected columns or row from menu command'
    6936         cols = sorted(G2frame.dataDisplay.GetSelectedCols()) # ignore selection order
    6937         rows = G2frame.dataDisplay.GetSelectedRows()
    6938         if cols:
    6939             G2plt.PlotSelectedSequence(G2frame,cols,GetColumnInfo,SelectXaxis)
    6940         elif rows:
    6941             name = histNames[rows[0]]       #only does 1st one selected
    6942             G2plt.PlotCovariance(G2frame,data[name])
    6943         else:
    6944             G2frame.ErrorDialog('Select columns',
    6945                 'No columns or rows selected in table. Click on row or column labels to select fields for plotting.')
    6946                
    6947     def OnAveSelSeq(event):
    6948         'average the selected columns from menu command'
    6949         cols = sorted(G2frame.dataDisplay.GetSelectedCols()) # ignore selection order
    6950         useCol =  ~np.array(G2frame.SeqTable.GetColValues(1),dtype=bool)
    6951         if cols:
    6952             for col in cols:
    6953                 items = GetColumnInfo(col)[1]
    6954                 noneMask = np.array([item is None for item in items])
    6955                 info = ma.array(items,mask=useCol+noneMask)
    6956                 ave = ma.mean(ma.compressed(info))
    6957                 sig = ma.std(ma.compressed(info))
    6958                 print (u' Average for '+G2frame.SeqTable.GetColLabelValue(col)+u': '+'%.6g'%(ave)+u' +/- '+u'%.6g'%(sig))
    6959         else:
    6960             G2frame.ErrorDialog('Select columns',
    6961                 'No columns selected in table. Click on column labels to select fields for averaging.')
    6962            
    6963     def OnSelectUse(event):
    6964         dlg = G2G.G2MultiChoiceDialog(G2frame, 'Select rows to use','Select rows',histNames)
    6965         sellist = [i for i,item in enumerate(G2frame.colList[1]) if item]
    6966         dlg.SetSelections(sellist)
    6967         if dlg.ShowModal() == wx.ID_OK:
    6968             sellist = dlg.GetSelections()
    6969             for row in range(G2frame.SeqTable.GetNumberRows()):
    6970                 G2frame.SeqTable.SetValue(row,1,False)
    6971                 G2frame.colList[1][row] = False
    6972             for row in sellist:
    6973                 G2frame.SeqTable.SetValue(row,1,True)
    6974                 G2frame.colList[1][row] = True
    6975             G2frame.dataDisplay.ForceRefresh()
    6976         dlg.Destroy()
    6977                
    6978     def OnRenameSelSeq(event):
    6979         cols = sorted(G2frame.dataDisplay.GetSelectedCols()) # ignore selection order
    6980         colNames = [G2frame.SeqTable.GetColLabelValue(c) for c in cols]
    6981         newNames = colNames[:]
    6982         for i,name in enumerate(colNames):
    6983             if name in variableLabels:
    6984                 newNames[i] = variableLabels[name]
    6985         if not cols:
    6986             G2frame.ErrorDialog('Select columns',
    6987                 'No columns selected in table. Click on column labels to select fields for rename.')
    6988             return
    6989         dlg = G2G.MultiStringDialog(G2frame.dataDisplay,'Set column names',colNames,newNames)
    6990         if dlg.Show():
    6991             newNames = dlg.GetValues()           
    6992             variableLabels.update(dict(zip(colNames,newNames)))
    6993         data['variableLabels'] = variableLabels
    6994         dlg.Destroy()
    6995         UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
    6996         G2plt.PlotSelectedSequence(G2frame,cols,GetColumnInfo,SelectXaxis)
    6997            
    6998     def OnSaveSelSeqCSV(event):
    6999         'export the selected columns to a .csv file from menu command'
    7000         OnSaveSelSeq(event,csv=True)
    7001        
    7002     def OnSaveSeqCSV(event):
    7003         'export all columns to a .csv file from menu command'
    7004         OnSaveSelSeq(event,csv=True,allcols=True)
    7005        
    7006     def OnSaveSelSeq(event,csv=False,allcols=False):
    7007         'export the selected columns to a .txt or .csv file from menu command'
    7008         def WriteLine(line):
    7009             if '2' in platform.python_version_tuple()[0]:
    7010                 SeqFile.write(G2obj.StripUnicode(line))
    7011             else:
    7012                 SeqFile.write(line)
    7013                
    7014         def WriteCSV():
    7015             def WriteList(headerItems):
    7016                 line = ''
    7017                 for lbl in headerItems:
    7018                     if line: line += ','
    7019                     line += '"'+lbl+'"'
    7020                 return line
    7021             head = ['name']
    7022             for col in cols:
    7023                 # Excel does not like unicode
    7024                 item = G2obj.StripUnicode(G2frame.SeqTable.GetColLabelValue(col))
    7025                 if col in havesig:
    7026                     head += [item,'esd-'+item]
    7027                 else:
    7028                     head += [item]
    7029             WriteLine(WriteList(head)+'\n')
    7030             for row,name in enumerate(saveNames):
    7031                 line = '"'+saveNames[row]+'"'
    7032                 for col in cols:
    7033                     if saveData[col][row] is None:
    7034                         if col in havesig:
    7035 #                            line += ',0.0,0.0'
    7036                             line += ',,'
    7037                         else:
    7038 #                            line += ',0.0'
    7039                             line += ','
    7040                     else:
    7041                         if col in havesig:
    7042                             line += ','+str(saveData[col][row])+','+str(saveSigs[col][row])
    7043                         else:   
    7044                             line += ','+str(saveData[col][row])
    7045                 WriteLine(line+'\n')
    7046         def WriteSeq():
    7047             lenName = len(saveNames[0])
    7048             line = '  %s  '%('name'.center(lenName))
    7049             for col in cols:
    7050                 item = G2frame.SeqTable.GetColLabelValue(col)
    7051                 if col in havesig:
    7052                     line += ' %12s %12s '%(item.center(12),'esd'.center(12))
    7053                 else:
    7054                     line += ' %12s '%(item.center(12))
    7055             WriteLine(line+'\n')
    7056             for row,name in enumerate(saveNames):
    7057                 line = " '%s' "%(saveNames[row])
    7058                 for col in cols:
    7059                     if col in havesig:
    7060                         try:
    7061                             line += ' %12.6f %12.6f '%(saveData[col][row],saveSigs[col][row])
    7062                         except TypeError:
    7063                             line += '                           '
    7064                     else:
    7065                         try:
    7066                             line += ' %12.6f '%saveData[col][row]
    7067                         except TypeError:
    7068                             line += '              '
    7069                 WriteLine(line+'\n')
    7070 
    7071         # start of OnSaveSelSeq code
    7072         if allcols:
    7073             cols = range(G2frame.SeqTable.GetNumberCols())
    7074         else:
    7075             cols = sorted(G2frame.dataDisplay.GetSelectedCols()) # ignore selection order
    7076         nrows = G2frame.SeqTable.GetNumberRows()
    7077         if not cols:
    7078             choices = [G2frame.SeqTable.GetColLabelValue(r) for r in range(G2frame.SeqTable.GetNumberCols())]
    7079             dlg = G2G.G2MultiChoiceDialog(G2frame, 'Select columns to write',
    7080                 'select columns',choices)
    7081             #dlg.SetSelections()
    7082             if dlg.ShowModal() == wx.ID_OK:
    7083                 cols = dlg.GetSelections()
    7084                 dlg.Destroy()
    7085             else:
    7086                 dlg.Destroy()
    7087                 return
    7088             #G2frame.ErrorDialog('Select columns',
    7089             #                 'No columns selected in table. Click on column labels to select fields for output.')
    7090             #return
    7091         saveNames = [G2frame.SeqTable.GetRowLabelValue(r) for r in range(nrows)]
    7092         saveData = {}
    7093         saveSigs = {}
    7094         havesig = []
    7095         for col in cols:
    7096             name,vals,sigs = GetColumnInfo(col)
    7097             saveData[col] = vals
    7098             if sigs:
    7099                 havesig.append(col)
    7100                 saveSigs[col] = sigs
    7101         if csv:
    7102             wild = 'CSV output file (*.csv)|*.csv'
    7103         else:
    7104             wild = 'Text output file (*.txt)|*.txt'
    7105         pth = G2G.GetExportPath(G2frame)
    7106         dlg = wx.FileDialog(
    7107             G2frame,
    7108             'Choose text output file for your selection', pth, '',
    7109             wild,wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
    7110         try:
    7111             if dlg.ShowModal() == wx.ID_OK:
    7112                 SeqTextFile = dlg.GetPath()
    7113                 SeqTextFile = G2IO.FileDlgFixExt(dlg,SeqTextFile)
    7114                 SeqFile = open(SeqTextFile,'w')
    7115                 if csv:
    7116                     WriteCSV()
    7117                 else:
    7118                     WriteSeq()
    7119                 SeqFile.close()
    7120         finally:
    7121             dlg.Destroy()
    7122                
    7123     def striphist(var,insChar=''):
    7124         'strip a histogram number from a var name'
    7125         sv = var.split(':')
    7126         if len(sv) <= 1: return var
    7127         if sv[1]:
    7128             sv[1] = insChar
    7129         return ':'.join(sv)
    7130        
    7131     def plotSpCharFix(lbl):
    7132         'Change selected unicode characters to their matplotlib equivalent'
    7133         for u,p in [
    7134             (u'\u03B1',r'$\alpha$'),
    7135             (u'\u03B2',r'$\beta$'),
    7136             (u'\u03B3',r'$\gamma$'),
    7137             (u'\u0394\u03C7',r'$\Delta\chi$'),
    7138             ]:
    7139             lbl = lbl.replace(u,p)
    7140         return lbl
    7141    
    7142     def SelectXaxis():
    7143         'returns a selected column number (or None) as the X-axis selection'
    7144         ncols = G2frame.SeqTable.GetNumberCols()
    7145         colNames = [G2frame.SeqTable.GetColLabelValue(r) for r in range(ncols)]
    7146         dlg = G2G.G2SingleChoiceDialog(
    7147             G2frame.dataDisplay,
    7148             'Select x-axis parameter for plot or Cancel for sequence number',
    7149             'Select X-axis',
    7150             colNames)
    7151         try:
    7152             if dlg.ShowModal() == wx.ID_OK:
    7153                 col = dlg.GetSelection()
    7154             else:
    7155                 col = None
    7156         finally:
    7157             dlg.Destroy()
    7158         return col
    7159    
    7160     def EnablePseudoVarMenus():
    7161         'Enables or disables the PseudoVar menu items that require existing defs'
    7162         if data['SeqPseudoVars']:
    7163             val = True
    7164         else:
    7165             val = False
    7166         G2frame.dataWindow.SequentialPvars.Enable(G2G.wxID_DELSEQVAR,val)
    7167         G2frame.dataWindow.SequentialPvars.Enable(G2G.wxID_EDITSEQVAR,val)
    7168 
    7169     def DelPseudoVar(event):
    7170         'Ask the user to select a pseudo var expression to delete'
    7171         choices = list(data['SeqPseudoVars'].keys())
    7172         selected = G2G.ItemSelector(
    7173             choices,G2frame,
    7174             multiple=True,
    7175             title='Select expressions to remove',
    7176             header='Delete expression')
    7177         if selected is None: return
    7178         for item in selected:
    7179             del data['SeqPseudoVars'][choices[item]]
    7180         if selected:
    7181             UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
    7182 
    7183     def EditPseudoVar(event):
    7184         'Edit an existing pseudo var expression'
    7185         choices = list(data['SeqPseudoVars'].keys())
    7186         if len(choices) == 1:
    7187             selected = 0
    7188         else:
    7189             selected = G2G.ItemSelector(
    7190                 choices,G2frame,
    7191                 multiple=False,
    7192                 title='Select an expression to edit',
    7193                 header='Edit expression')
    7194         if selected is not None:
    7195             dlg = G2exG.ExpressionDialog(
    7196                 G2frame.dataDisplay,PSvarDict,
    7197                 data['SeqPseudoVars'][choices[selected]],
    7198                 header="Edit the PseudoVar expression",
    7199                 VarLabel="PseudoVar #"+str(selected+1),
    7200                 fit=False)
    7201             newobj = dlg.Show(True)
    7202             if newobj:
    7203                 calcobj = G2obj.ExpressionCalcObj(newobj)
    7204                 del data['SeqPseudoVars'][choices[selected]]
    7205                 data['SeqPseudoVars'][calcobj.eObj.expression] = newobj
    7206                 UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
    7207        
    7208     def AddNewPseudoVar(event):
    7209         'Create a new pseudo var expression'
    7210         dlg = G2exG.ExpressionDialog(G2frame.dataDisplay,PSvarDict,
    7211             header='Enter an expression for a PseudoVar here',
    7212             VarLabel = "New PseudoVar",fit=False)
    7213         obj = dlg.Show(True)
    7214         dlg.Destroy()
    7215         if obj:
    7216             calcobj = G2obj.ExpressionCalcObj(obj)
    7217             data['SeqPseudoVars'][calcobj.eObj.expression] = obj
    7218             UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
    7219            
    7220     def AddNewDistPseudoVar(event):
    7221         obj = None
    7222         dlg = G2exG.BondDialog(
    7223             G2frame.dataDisplay,Phases,PSvarDict,
    7224             header='Select a Bond here',
    7225             VarLabel = "New Bond")
    7226         if dlg.ShowModal() == wx.ID_OK:
    7227             pName,Oatom,Tatom = dlg.GetSelection()
    7228             if Tatom:
    7229                 Phase = Phases[pName]
    7230                 General = Phase['General']
    7231                 cx,ct = General['AtomPtrs'][:2]
    7232                 pId = Phase['pId']
    7233                 SGData = General['SGData']
    7234                 sB = Tatom.find('(')+1
    7235                 symNo = 0
    7236                 if sB:
    7237                     sF = Tatom.find(')')
    7238                     symNo = int(Tatom[sB:sF])
    7239                 cellNo = [0,0,0]
    7240                 cB = Tatom.find('[')
    7241                 if cB>0:
    7242                     cF = Tatom.find(']')+1
    7243                     cellNo = eval(Tatom[cB:cF])
    7244                 Atoms = Phase['Atoms']
    7245                 aNames = [atom[ct-1] for atom in Atoms]
    7246                 oId = aNames.index(Oatom)
    7247                 tId = aNames.index(Tatom.split(' +')[0])
    7248                 # create an expression object
    7249                 obj = G2obj.ExpressionObj()
    7250                 obj.expression = 'Dist(%s,\n%s)'%(Oatom,Tatom.split(' d=')[0].replace(' ',''))
    7251                 obj.distance_dict = {'pId':pId,'SGData':SGData,'symNo':symNo,'cellNo':cellNo}
    7252                 obj.distance_atoms = [oId,tId]
    7253         else:
    7254             dlg.Destroy()
    7255             return
    7256         dlg.Destroy()
    7257         if obj:
    7258             data['SeqPseudoVars'][obj.expression] = obj
    7259             UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
    7260 
    7261     def AddNewAnglePseudoVar(event):
    7262         obj = None
    7263         dlg = G2exG.AngleDialog(
    7264             G2frame.dataDisplay,Phases,PSvarDict,
    7265             header='Enter an Angle here',
    7266             VarLabel = "New Angle")
    7267         if dlg.ShowModal() == wx.ID_OK:
    7268             pName,Oatom,Tatoms = dlg.GetSelection()
    7269             if Tatoms:
    7270                 Phase = Phases[pName]
    7271                 General = Phase['General']
    7272                 cx,ct = General['AtomPtrs'][:2]
    7273                 pId = Phase['pId']
    7274                 SGData = General['SGData']
    7275                 Atoms = Phase['Atoms']
    7276                 aNames = [atom[ct-1] for atom in Atoms]
    7277                 tIds = []
    7278                 symNos = []
    7279                 cellNos = []
    7280                 oId = aNames.index(Oatom)
    7281                 Tatoms = Tatoms.split(';')
    7282                 for Tatom in Tatoms:
    7283                     sB = Tatom.find('(')+1
    7284                     symNo = 0
    7285                     if sB:
    7286                         sF = Tatom.find(')')
    7287                         symNo = int(Tatom[sB:sF])
    7288                     symNos.append(symNo)
    7289                     cellNo = [0,0,0]
    7290                     cB = Tatom.find('[')
    7291                     if cB>0:
    7292                         cF = Tatom.find(']')+1
    7293                         cellNo = eval(Tatom[cB:cF])
    7294                     cellNos.append(cellNo)
    7295                     tIds.append(aNames.index(Tatom.split('+')[0]))
    7296                 # create an expression object
    7297                 obj = G2obj.ExpressionObj()
    7298                 obj.expression = 'Angle(%s,%s,\n%s)'%(Tatoms[0],Oatom,Tatoms[1])
    7299                 obj.angle_dict = {'pId':pId,'SGData':SGData,'symNo':symNos,'cellNo':cellNos}
    7300                 obj.angle_atoms = [oId,tIds]
    7301         else:
    7302             dlg.Destroy()
    7303             return
    7304         dlg.Destroy()
    7305         if obj:
    7306             data['SeqPseudoVars'][obj.expression] = obj
    7307             UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
    7308            
    7309     def UpdateParmDict(parmDict):
    7310         '''generate the atom positions and the direct & reciprocal cell values,
    7311         because they might be needed to evaluate the pseudovar
    7312         '''
    7313         Ddict = dict(zip(['D11','D22','D33','D12','D13','D23'],
    7314                          ['A'+str(i) for i in range(6)])
    7315                      )
    7316         delList = []
    7317         phaselist = []
    7318         for item in parmDict:
    7319             if ':' not in item: continue
    7320             key = item.split(':')
    7321             if len(key) < 3: continue
    7322             # remove the dA[xyz] terms, they would only bring confusion
    7323             if key[0] and key[0] not in phaselist: phaselist.append(key[0])
    7324             if key[2].startswith('dA'):
    7325                 delList.append(item)
    7326             # compute and update the corrected reciprocal cell terms using the Dij values
    7327             elif key[2] in Ddict:
    7328                 akey = key[0]+'::'+Ddict[key[2]]
    7329                 parmDict[akey] += parmDict[item]
    7330                 delList.append(item)
    7331         for item in delList:
    7332             del parmDict[item]               
    7333         for i in phaselist:
    7334             pId = int(i)
    7335             # apply cell symmetry
    7336             A,zeros = G2stIO.cellFill(str(pId)+'::',SGdata[pId],parmDict,zeroDict[pId])
    7337             # convert to direct cell & add the unique terms to the dictionary
    7338             for i,val in enumerate(G2lat.A2cell(A)):
    7339                 if i in uniqCellIndx[pId]:
    7340                     lbl = str(pId)+'::'+cellUlbl[i]
    7341                     parmDict[lbl] = val
    7342             lbl = str(pId)+'::'+'Vol'
    7343             parmDict[lbl] = G2lat.calc_V(A)
    7344         return parmDict
    7345 
    7346     def EvalPSvarDeriv(calcobj,parmDict,sampleDict,var,ESD):
    7347         '''Evaluate an expression derivative with respect to a
    7348         GSAS-II variable name.
    7349 
    7350         Note this likely could be faster if the loop over calcobjs were done
    7351         inside after the Dict was created.
    7352         '''
    7353         if not ESD:
    7354             return 0.
    7355         step = ESD/10
    7356         Ddict = dict(zip(['D11','D22','D33','D12','D13','D23'],
    7357                          ['A'+str(i) for i in range(6)])
    7358                      )
    7359         results = []
    7360         phaselist = []
    7361         VparmDict = sampleDict.copy()
    7362         for incr in step,-step:
    7363             VparmDict.update(parmDict.copy())           
    7364             # as saved, the parmDict has updated 'A[xyz]' values, but 'dA[xyz]'
    7365             # values are not zeroed: fix that!
    7366             VparmDict.update({item:0.0 for item in parmDict if 'dA' in item})
    7367             VparmDict[var] += incr
    7368             G2mv.Dict2Map(VparmDict,[]) # apply constraints
    7369             # generate the atom positions and the direct & reciprocal cell values now, because they might
    7370             # needed to evaluate the pseudovar
    7371             for item in VparmDict:
    7372                 if item in sampleDict:
    7373                     continue
    7374                 if ':' not in item: continue
    7375                 key = item.split(':')
    7376                 if len(key) < 3: continue
    7377                 # apply any new shifts to atom positions
    7378                 if key[2].startswith('dA'):
    7379                     VparmDict[''.join(item.split('d'))] += VparmDict[item]
    7380                     VparmDict[item] = 0.0
    7381                 # compute and update the corrected reciprocal cell terms using the Dij values
    7382                 if key[2] in Ddict:
    7383                     if key[0] not in phaselist: phaselist.append(key[0])
    7384                     akey = key[0]+'::'+Ddict[key[2]]
    7385                     VparmDict[akey] += VparmDict[item]
    7386             for i in phaselist:
    7387                 pId = int(i)
    7388                 # apply cell symmetry
    7389                 A,zeros = G2stIO.cellFill(str(pId)+'::',SGdata[pId],VparmDict,zeroDict[pId])
    7390                 # convert to direct cell & add the unique terms to the dictionary
    7391                 for i,val in enumerate(G2lat.A2cell(A)):
    7392                     if i in uniqCellIndx[pId]:
    7393                         lbl = str(pId)+'::'+cellUlbl[i]
    7394                         VparmDict[lbl] = val
    7395                 lbl = str(pId)+'::'+'Vol'
    7396                 VparmDict[lbl] = G2lat.calc_V(A)
    7397             # dict should be fully updated, use it & calculate
    7398             calcobj.SetupCalc(VparmDict)
    7399             results.append(calcobj.EvalExpression())
    7400         if None in results:
    7401             return None
    7402         return (results[0] - results[1]) / (2.*step)
    7403        
    7404     def EnableParFitEqMenus():
    7405         'Enables or disables the Parametric Fit menu items that require existing defs'
    7406         if data['SeqParFitEqList']:
    7407             val = True
    7408         else:
    7409             val = False
    7410         G2frame.dataWindow.SequentialPfit.Enable(G2G.wxID_DELPARFIT,val)
    7411         G2frame.dataWindow.SequentialPfit.Enable(G2G.wxID_EDITPARFIT,val)
    7412         G2frame.dataWindow.SequentialPfit.Enable(G2G.wxID_DOPARFIT,val)
    7413 
    7414     def ParEqEval(Values,calcObjList,varyList):
    7415         '''Evaluate the parametric expression(s)
    7416         :param list Values: a list of values for each variable parameter
    7417         :param list calcObjList: a list of :class:`GSASIIobj.ExpressionCalcObj`
    7418           expression objects to evaluate
    7419         :param list varyList: a list of variable names for each value in Values
    7420         '''
    7421         result = []
    7422         for calcobj in calcObjList:
    7423             calcobj.UpdateVars(varyList,Values)
    7424             if calcobj.depSig:
    7425                 result.append((calcobj.depVal-calcobj.EvalExpression())/calcobj.depSig)
    7426             else:
    7427                 result.append(calcobj.depVal-calcobj.EvalExpression())
    7428         return result
    7429 
    7430     def DoParEqFit(event,eqObj=None):
    7431         'Parametric fit minimizer'
    7432         varyValueDict = {} # dict of variables and their initial values
    7433         calcObjList = [] # expression objects, ready to go for each data point
    7434         if eqObj is not None:
    7435             eqObjList = [eqObj,]
    7436         else:
    7437             eqObjList = data['SeqParFitEqList']
    7438         UseFlags = G2frame.SeqTable.GetColValues(1)
    7439         for obj in eqObjList:
    7440             # assemble refined vars for this equation
    7441             varyValueDict.update({var:val for var,val in obj.GetVariedVarVal()})
    7442             # lookup dependent var position
    7443             depVar = obj.GetDepVar()
    7444             if depVar in colLabels:
    7445                 indx = colLabels.index(depVar)
    7446             else:
    7447                 raise Exception('Dependent variable '+depVar+' not found')
    7448             # assemble a list of the independent variables
    7449             indepVars = obj.GetIndependentVars()
    7450             # loop over each datapoint
    7451             for j,row in enumerate(zip(*G2frame.colList)):
    7452                 if not UseFlags[j]: continue
    7453                 # assemble equations to fit
    7454                 calcobj = G2obj.ExpressionCalcObj(obj)
    7455                 # prepare a dict of needed independent vars for this expression
    7456                 indepVarDict = {var:row[i] for i,var in enumerate(colLabels) if var in indepVars}
    7457                 calcobj.SetupCalc(indepVarDict)               
    7458                 # values and sigs for current value of dependent var
    7459                 if row[indx] is None: continue
    7460                 calcobj.depVal = row[indx]
    7461                 calcobj.depSig = G2frame.colSigs[indx][j]
    7462                 calcObjList.append(calcobj)
    7463         # varied parameters
    7464         varyList = varyValueDict.keys()
    7465         values = varyValues = [varyValueDict[key] for key in varyList]
    7466         if not varyList:
    7467             print ('no variables to refine!')
    7468             return
    7469         try:
    7470             result = so.leastsq(ParEqEval,varyValues,full_output=True,   #ftol=Ftol,
    7471                 args=(calcObjList,varyList))
    7472             values = result[0]
    7473             covar = result[1]
    7474             if covar is None:
    7475                 raise Exception
    7476             chisq = np.sum(result[2]['fvec']**2)
    7477             GOF = np.sqrt(chisq/(len(calcObjList)-len(varyList)))
    7478             esdDict = {}
    7479             for i,avar in enumerate(varyList):
    7480                 esdDict[avar] = np.sqrt(covar[i,i])
    7481         except:
    7482             print('====> Fit failed')
    7483             return
    7484         print('==== Fit Results ====')
    7485         print ('  chisq =  %.2f, GOF = %.2f'%(chisq,GOF))
    7486         for obj in eqObjList:
    7487             obj.UpdateVariedVars(varyList,values)
    7488             ind = '      '
    7489             print(u'  '+obj.GetDepVar()+u' = '+obj.expression)
    7490             for var in obj.assgnVars:
    7491                 print(ind+var+u' = '+obj.assgnVars[var])
    7492             for var in obj.freeVars:
    7493                 avar = "::"+obj.freeVars[var][0]
    7494                 val = obj.freeVars[var][1]
    7495                 if obj.freeVars[var][2]:
    7496                     print(ind+var+u' = '+avar + " = " + G2mth.ValEsd(val,esdDict[avar]))
    7497                 else:
    7498                     print(ind+var+u' = '+avar + u" =" + G2mth.ValEsd(val,0))
    7499         # create a plot for each parametric variable
    7500         for fitnum,obj in enumerate(eqObjList):
    7501             calcobj = G2obj.ExpressionCalcObj(obj)
    7502             # lookup dependent var position
    7503             indx = colLabels.index(obj.GetDepVar())
    7504             # assemble a list of the independent variables
    7505             indepVars = obj.GetIndependentVars()           
    7506             # loop over each datapoint
    7507             fitvals = []
    7508             for j,row in enumerate(zip(*G2frame.colList)):
    7509                 calcobj.SetupCalc({var:row[i] for i,var in enumerate(colLabels) if var in indepVars})
    7510                 fitvals.append(calcobj.EvalExpression())
    7511             G2plt.PlotSelectedSequence(G2frame,[indx],GetColumnInfo,SelectXaxis,fitnum,fitvals)
    7512 
    7513     def SingleParEqFit(eqObj):
    7514         DoParEqFit(None,eqObj)
    7515 
    7516     def DelParFitEq(event):
    7517         'Ask the user to select function to delete'
    7518         txtlst = [obj.GetDepVar()+' = '+obj.expression for obj in data['SeqParFitEqList']]
    7519         selected = G2G.ItemSelector(
    7520             txtlst,G2frame,
    7521             multiple=True,
    7522             title='Select a parametric equation(s) to remove',
    7523             header='Delete equation')
    7524         if selected is None: return
    7525         data['SeqParFitEqList'] = [obj for i,obj in enumerate(data['SeqParFitEqList']) if i not in selected]
    7526         EnableParFitEqMenus()
    7527         if data['SeqParFitEqList']: DoParEqFit(event)
    7528        
    7529     def EditParFitEq(event):
    7530         'Edit an existing parametric equation'
    7531         txtlst = [obj.GetDepVar()+' = '+obj.expression for obj in data['SeqParFitEqList']]
    7532         if len(txtlst) == 1:
    7533             selected = 0
    7534         else:
    7535             selected = G2G.ItemSelector(
    7536                 txtlst,G2frame,
    7537                 multiple=False,
    7538                 title='Select a parametric equation to edit',
    7539                 header='Edit equation')
    7540         if selected is not None:
    7541             dlg = G2exG.ExpressionDialog(G2frame.dataDisplay,VarDict,
    7542                 data['SeqParFitEqList'][selected],depVarDict=VarDict,
    7543                 header="Edit the formula for this minimization function",
    7544                 ExtraButton=['Fit',SingleParEqFit],wildCard=False)
    7545             newobj = dlg.Show(True)
    7546             if newobj:
    7547                 data['SeqParFitEqList'][selected] = newobj
    7548                 EnableParFitEqMenus()
    7549             if data['SeqParFitEqList']: DoParEqFit(event)
    7550 
    7551     def AddNewParFitEq(event):
    7552         'Create a new parametric equation to be fit to sequential results'
    7553 
    7554         # compile the variable names used in previous freevars to avoid accidental name collisions
    7555         usedvarlist = []
    7556         for obj in data['SeqParFitEqList']:
    7557             for var in obj.freeVars:
    7558                 if obj.freeVars[var][0] not in usedvarlist: usedvarlist.append(obj.freeVars[var][0])
    7559 
    7560         dlg = G2exG.ExpressionDialog(G2frame.dataDisplay,VarDict,depVarDict=VarDict,
    7561             header='Define an equation to minimize in the parametric fit',
    7562             ExtraButton=['Fit',SingleParEqFit],usedVars=usedvarlist,wildCard=False)
    7563         obj = dlg.Show(True)
    7564         dlg.Destroy()
    7565         if obj:
    7566             data['SeqParFitEqList'].append(obj)
    7567             EnableParFitEqMenus()
    7568             if data['SeqParFitEqList']: DoParEqFit(event)
    7569                
    7570     def CopyParFitEq(event):
    7571         'Copy an existing parametric equation to be fit to sequential results'
    7572         # compile the variable names used in previous freevars to avoid accidental name collisions
    7573         usedvarlist = []
    7574         for obj in data['SeqParFitEqList']:
    7575             for var in obj.freeVars:
    7576                 if obj.freeVars[var][0] not in usedvarlist: usedvarlist.append(obj.freeVars[var][0])
    7577         txtlst = [obj.GetDepVar()+' = '+obj.expression for obj in data['SeqParFitEqList']]
    7578         if len(txtlst) == 1:
    7579             selected = 0
    7580         else:
    7581             selected = G2G.ItemSelector(
    7582                 txtlst,G2frame,
    7583                 multiple=False,
    7584                 title='Select a parametric equation to copy',
    7585                 header='Copy equation')
    7586         if selected is not None:
    7587             newEqn = copy.deepcopy(data['SeqParFitEqList'][selected])
    7588             for var in newEqn.freeVars:
    7589                 newEqn.freeVars[var][0] = G2obj.MakeUniqueLabel(newEqn.freeVars[var][0],usedvarlist)
    7590             dlg = G2exG.ExpressionDialog(
    7591                 G2frame.dataDisplay,VarDict,newEqn,depVarDict=VarDict,
    7592                 header="Edit the formula for this minimization function",
    7593                 ExtraButton=['Fit',SingleParEqFit],wildCard=False)
    7594             newobj = dlg.Show(True)
    7595             if newobj:
    7596                 data['SeqParFitEqList'].append(newobj)
    7597                 EnableParFitEqMenus()
    7598             if data['SeqParFitEqList']: DoParEqFit(event)
    7599                                            
    7600     def GridSetToolTip(row,col):
    7601         '''Routine to show standard uncertainties for each element in table
    7602         as a tooltip
    7603         '''
    7604         if G2frame.colSigs[col]:
    7605             if G2frame.colSigs[col][row] == -0.1: return 'frozen'
    7606             return u'\u03c3 = '+str(G2frame.colSigs[col][row])
    7607         return ''
    7608        
    7609     def GridColLblToolTip(col):
    7610         '''Define a tooltip for a column. This will be the user-entered value
    7611         (from data['variableLabels']) or the default name
    7612         '''
    7613         if col < 0 or col > len(colLabels):
    7614             print ('Illegal column #%d'%col)
    7615             return
    7616         var = colLabels[col]
    7617         return variableLabels.get(var,G2obj.fmtVarDescr(var))
    7618        
    7619     def SetLabelString(event):
    7620         '''Define or edit the label for a column in the table, to be used
    7621         as a tooltip and for plotting
    7622         '''
    7623         col = event.GetCol()
    7624         if col < 0 or col > len(colLabels):
    7625             return
    7626         var = colLabels[col]
    7627         lbl = variableLabels.get(var,G2obj.fmtVarDescr(var))
    7628         head = u'Set a new name for variable {} (column {})'.format(var,col)
    7629         dlg = G2G.SingleStringDialog(G2frame,'Set variable label',
    7630                                  head,lbl,size=(400,-1))
    7631         if dlg.Show():
    7632             variableLabels[var] = dlg.GetValue()
    7633             dlg.Destroy()
    7634             wx.CallAfter(UpdateSeqResults,G2frame,data) # redisplay variables
    7635         else:
    7636             dlg.Destroy()
    7637 
    7638     def DoSequentialExport(event):
    7639         '''Event handler for all Sequential Export menu items
    7640         '''
    7641         vals = G2frame.dataWindow.SeqExportLookup.get(event.GetId())
    7642         if vals is None:
    7643             print('Error: Id not found. This should not happen!')
    7644             return
    7645         G2IO.ExportSequential(G2frame,data,*vals)
    7646 
    7647     def onSelectSeqVars(event):
    7648         '''Select which variables will be shown in table'''
    7649         hides = [saveColLabels[1:].index(item) for item in G2frame.SeqTblHideList if
    7650                      item in saveColLabels[1:]]
    7651         dlg = G2G.G2MultiChoiceDialog(G2frame, 'Select columns to hide',
    7652                 'Hide columns',saveColLabels[1:])
    7653         dlg.SetSelections(hides)
    7654         if dlg.ShowModal() == wx.ID_OK:
    7655             G2frame.SeqTblHideList = [saveColLabels[1:][sel] for sel in dlg.GetSelections()]
    7656             dlg.Destroy()
    7657             UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
    7658         else:
    7659             dlg.Destroy()
    7660            
    7661     def OnCellChange(event):
    7662         r = event.GetRow()
    7663         val = G2frame.SeqTable.GetValue(r,0)
    7664 #        print (r,val)
    7665         G2frame.SeqTable.SetValue(r,0, val)
    7666        
    7667     def OnSelectUpdate(event):
    7668         '''Update all phase parameters from a selected column in the Sequential Table.
    7669         If no histogram is selected (or more than one), ask the user to make a selection.
    7670 
    7671         Loosely based on :func:`GSASIIstrIO.SetPhaseData`
    7672         '''
    7673         rows = G2frame.dataDisplay.GetSelectedRows()
    7674         if len(rows) == 1:
    7675             sel = rows[0]
    7676         else:
    7677             dlg = G2G.G2SingleChoiceDialog(G2frame, 'Select histogram to use for update',
    7678                                            'Select row',histNames)
    7679             if dlg.ShowModal() == wx.ID_OK:
    7680                 sel = dlg.GetSelection()
    7681                 dlg.Destroy()
    7682             else:
    7683                 dlg.Destroy()
    7684                 return
    7685         parmDict = data[histNames[sel]]['parmDict']
    7686         Histograms,Phases = G2frame.GetUsedHistogramsAndPhasesfromTree()
    7687         for phase in Phases:
    7688             print('Updating {} from Seq. Ref. row {}'.format(phase,histNames[sel]))
    7689             Phase = Phases[phase]
    7690             General = Phase['General']
    7691             SGData = General['SGData']
    7692             Atoms = Phase['Atoms']
    7693             cell = General['Cell']
    7694             pId = Phase['pId']
    7695             pfx = str(pId)+'::'
    7696             # there should not be any changes to the cell because those terms are not refined
    7697             A,sigA = G2stIO.cellFill(pfx,SGData,parmDict,{})
    7698             cell[1:7] = G2lat.A2cell(A)
    7699             cell[7] = G2lat.calc_V(A)
    7700             textureData = General['SH Texture']   
    7701             if textureData['Order']:
    7702 #                SHtextureSig = {}
    7703                 for name in ['omega','chi','phi']:
    7704                     aname = pfx+'SH '+name
    7705                     textureData['Sample '+name][1] = parmDict[aname]
    7706                 for name in textureData['SH Coeff'][1]:
    7707                     aname = pfx+name
    7708                     textureData['SH Coeff'][1][name] = parmDict[aname]
    7709             ik = 6  #for Pawley stuff below
    7710             if General.get('Modulated',False):
    7711                 ik = 7
    7712             # how are these updated?
    7713             #General['SuperVec']
    7714             #RBModels = Phase['RBModels']
    7715             if Phase['General'].get('doPawley'):
    7716                 pawleyRef = Phase['Pawley ref']
    7717                 for i,refl in enumerate(pawleyRef):
    7718                     key = pfx+'PWLref:'+str(i)
    7719                     refl[ik] = parmDict[key]
    7720 #                    if key in sigDict:  #TODO: error here sigDict not defined. What was intended
    7721 #                        refl[ik+1] = sigDict[key]
    7722 #                    else:
    7723 #                        refl[ik+1] = 0
    7724                 continue
    7725             General['Mass'] = 0.
    7726             cx,ct,cs,cia = General['AtomPtrs']
    7727             for i,at in enumerate(Atoms):
    7728                 names = {cx:pfx+'Ax:'+str(i),cx+1:pfx+'Ay:'+str(i),cx+2:pfx+'Az:'+str(i),cx+3:pfx+'Afrac:'+str(i),
    7729                     cia+1:pfx+'AUiso:'+str(i),cia+2:pfx+'AU11:'+str(i),cia+3:pfx+'AU22:'+str(i),cia+4:pfx+'AU33:'+str(i),
    7730                     cia+5:pfx+'AU12:'+str(i),cia+6:pfx+'AU13:'+str(i),cia+7:pfx+'AU23:'+str(i),
    7731                     cx+4:pfx+'AMx:'+str(i),cx+5:pfx+'AMy:'+str(i),cx+6:pfx+'AMz:'+str(i)}
    7732                 for ind in range(cx,cx+4):
    7733                     at[ind] = parmDict[names[ind]]
    7734                 if at[cia] == 'I':
    7735                     at[cia+1] = parmDict[names[cia+1]]
    7736                 else:
    7737                     for ind in range(cia+2,cia+8):
    7738                         at[ind] = parmDict[names[ind]]
    7739                 if General['Type'] == 'magnetic':
    7740                     for ind in range(cx+4,cx+7):
    7741                         at[ind] = parmDict[names[ind]]
    7742                 ind = General['AtomTypes'].index(at[ct])
    7743                 General['Mass'] += General['AtomMass'][ind]*at[cx+3]*at[cx+5]
    7744                 if General.get('Modulated',False):
    7745                     AtomSS = at[-1]['SS1']
    7746                     waveType = AtomSS['waveType']
    7747                     for Stype in ['Sfrac','Spos','Sadp','Smag']:
    7748                         Waves = AtomSS[Stype]
    7749                         for iw,wave in enumerate(Waves):
    7750                             stiw = str(i)+':'+str(iw)
    7751                             if Stype == 'Spos':
    7752                                 if waveType in ['ZigZag','Block',] and not iw:
    7753                                     names = ['Tmin:'+stiw,'Tmax:'+stiw,'Xmax:'+stiw,'Ymax:'+stiw,'Zmax:'+stiw]
    7754                                 else:
    7755                                     names = ['Xsin:'+stiw,'Ysin:'+stiw,'Zsin:'+stiw,
    7756                                         'Xcos:'+stiw,'Ycos:'+stiw,'Zcos:'+stiw]
    7757                             elif Stype == 'Sadp':
    7758                                 names = ['U11sin:'+stiw,'U22sin:'+stiw,'U33sin:'+stiw,
    7759                                     'U12sin:'+stiw,'U13sin:'+stiw,'U23sin:'+stiw,
    7760                                     'U11cos:'+stiw,'U22cos:'+stiw,'U33cos:'+stiw,
    7761                                     'U12cos:'+stiw,'U13cos:'+stiw,'U23cos:'+stiw]
    7762                             elif Stype == 'Sfrac':
    7763                                 if 'Crenel' in waveType and not iw:
    7764                                     names = ['Fzero:'+stiw,'Fwid:'+stiw]
    7765                                 else:
    7766                                     names = ['Fsin:'+stiw,'Fcos:'+stiw]
    7767                             elif Stype == 'Smag':
    7768                                 names = ['MXsin:'+stiw,'MYsin:'+stiw,'MZsin:'+stiw,
    7769                                     'MXcos:'+stiw,'MYcos:'+stiw,'MZcos:'+stiw]
    7770                             for iname,name in enumerate(names):
    7771                                 AtomSS[Stype][iw][0][iname] = parmDict[pfx+name]
    7772                                
    7773     def OnEditSelectPhaseVars(event):
    7774         '''Select phase parameters in a selected histogram in a sequential
    7775         fit. This allows the user to set their value(s)
    7776         '''
    7777         rows = G2frame.dataDisplay.GetSelectedRows()
    7778         if len(rows) == 1:
    7779             sel = rows[0]
    7780         else:
    7781             dlg = G2G.G2SingleChoiceDialog(G2frame, 'Select histogram to use for update',
    7782                                            'Select row',histNames)
    7783             if dlg.ShowModal() == wx.ID_OK:
    7784                 sel = dlg.GetSelection()
    7785                 dlg.Destroy()
    7786             else:
    7787                 dlg.Destroy()
    7788                 return
    7789         parmDict = data[histNames[sel]]['parmDict']
    7790         # narrow down to items w/o a histogram & having float values
    7791         phaseKeys = [i for i in parmDict if ':' in i and i.split(':')[1] == '']
    7792         phaseKeys = [i for i in phaseKeys if type(parmDict[i]) not in (int,str,bool) ]
    7793         dlg = G2G.G2MultiChoiceDialog(G2frame, 'Choose phase parmDict items to set',
    7794                                       'Choose items to edit', phaseKeys)
    7795         if dlg.ShowModal() == wx.ID_OK:
    7796             select = dlg.GetSelections()
    7797             dlg.Destroy()
    7798         else:
    7799             dlg.Destroy()
    7800             return
    7801         if len(select) == 0: return
    7802         l = [phaseKeys[i] for i in select]
    7803         d = {i:parmDict[i] for i in l}
    7804         val = G2G.CallScrolledMultiEditor(G2frame,len(l)*[d],l,l,CopyButton=True)
    7805         if val:
    7806             for key in d: # update values shown in table
    7807                 if parmDict[key] == d[key]: continue
    7808                 if key in data[histNames[sel]]['varyList']:
    7809                     i = data[histNames[sel]]['varyList'].index(key)
    7810                     data[histNames[sel]]['variables'][i] = d[key]
    7811                     data[histNames[sel]]['sig'][i] = 0
    7812                 if key in data[histNames[sel]].get('depParmDict',{}):
    7813                     data[histNames[sel]]['depParmDict'][key] = (d[key],0)
    7814             parmDict.update(d) # update values used in next fit
    7815         wx.CallAfter(UpdateSeqResults,G2frame,data) # redisplay variables
    7816         return
    7817            
    7818 ##### UpdateSeqResults: start processing sequential results here ##########
    7819     # lookup table for unique cell parameters by symmetry
    7820     cellGUIlist = [
    7821         [['m3','m3m'],(0,)],
    7822         [['3R','3mR'],(0,3)],
    7823         [['3','3m1','31m','6/m','6/mmm','4/m','4/mmm'],(0,2)],
    7824         [['mmm'],(0,1,2)],
    7825         [['2/m'+'a'],(0,1,2,3)],
    7826         [['2/m'+'b'],(0,1,2,4)],
    7827         [['2/m'+'c'],(0,1,2,5)],
    7828         [['-1'],(0,1,2,3,4,5)],
    7829         ]
    7830     # cell labels
    7831     cellUlbl = ('a','b','c',u'\u03B1',u'\u03B2',u'\u03B3') # unicode a,b,c,alpha,beta,gamma
    7832 
    7833     if not data:
    7834         print ('No sequential refinement results')
    7835         return
    7836     variableLabels = data.get('variableLabels',{})
    7837     data['variableLabels'] = variableLabels
    7838     Histograms,Phases = G2frame.GetUsedHistogramsAndPhasesfromTree()
    7839     Controls = G2frame.GPXtree.GetItemPyData(GetGPXtreeItemId(G2frame,G2frame.root,'Controls'))
    7840     # create a place to store Pseudo Vars & Parametric Fit functions, if not present
    7841     if 'SeqPseudoVars' not in data: data['SeqPseudoVars'] = {}
    7842     if 'SeqParFitEqList' not in data: data['SeqParFitEqList'] = []
    7843     histNames = data['histNames']
    7844     foundNames = [name for name in histNames if name in data]
    7845     histNames = foundNames
    7846     if G2frame.dataDisplay:
    7847         G2frame.dataDisplay.Destroy()
    7848     G2frame.GetStatusBar().SetStatusText("Select column to export; Double click on column to plot data; on row for Covariance",1)
    7849     sampleParms = GetSampleParms()
    7850 
    7851     # make dict of varied atom coords keyed by absolute position
    7852     newAtomDict = data[histNames[0]].get('newAtomDict',{}) # dict with atom positions; relative & absolute
    7853     # Possible error: the next might need to be data[histNames[0]]['varyList']
    7854     # error will arise if there constraints on coordinates?
    7855     atomLookup = {newAtomDict[item][0]:item for item in newAtomDict if item in data['varyList']}
    7856    
    7857     # make dict of varied cell parameters equivalents
    7858     ESDlookup = {} # provides the Dij term for each Ak term (where terms are refined)
    7859     Dlookup = {} # provides the Ak term for each Dij term (where terms are refined)
    7860     # N.B. These Dij vars are missing a histogram #
    7861     newCellDict = {}
    7862     for name in histNames:
    7863         if name in data and 'newCellDict' in data[name]:
    7864             newCellDict.update(data[name]['newCellDict'])
    7865     cellAlist = []
    7866     for item in newCellDict:
    7867         cellAlist.append(newCellDict[item][0])
    7868         if item in data.get('varyList',[]):
    7869             ESDlookup[newCellDict[item][0]] = item
    7870             Dlookup[item] = newCellDict[item][0]
    7871     # add coordinate equivalents to lookup table
    7872     for parm in atomLookup:
    7873         Dlookup[atomLookup[parm]] = parm
    7874         ESDlookup[parm] = atomLookup[parm]
    7875 
    7876     # get unit cell & symmetry for all phases & initial stuff for later use
    7877     RecpCellTerms = {}
    7878     SGdata = {}
    7879     uniqCellIndx = {}
    7880     initialCell = {}
    7881     RcellLbls = {}
    7882     zeroDict = {}
    7883     for phase in Phases:
    7884         phasedict = Phases[phase]
    7885         pId = phasedict['pId']
    7886         pfx = str(pId)+'::' # prefix for A values from phase
    7887         RcellLbls[pId] = [pfx+'A'+str(i) for i in range(6)]
    7888         RecpCellTerms[pId] = G2lat.cell2A(phasedict['General']['Cell'][1:7])
    7889         zeroDict[pId] = dict(zip(RcellLbls[pId],6*[0.,]))
    7890         SGdata[pId] = phasedict['General']['SGData']
    7891         laue = SGdata[pId]['SGLaue']
    7892         if laue == '2/m':
    7893             laue += SGdata[pId]['SGUniq']
    7894         for symlist,celllist in cellGUIlist:
    7895             if laue in symlist:
    7896                 uniqCellIndx[pId] = celllist
    7897                 break
    7898         else: # should not happen
    7899             uniqCellIndx[pId] = list(range(6))
    7900         for i in uniqCellIndx[pId]:
    7901             initialCell[str(pId)+'::A'+str(i)] =  RecpCellTerms[pId][i]
    7902 
    7903     SetDataMenuBar(G2frame,G2frame.dataWindow.SequentialMenu)
    7904     G2frame.Bind(wx.EVT_MENU, OnSelectUse, id=G2G.wxID_SELECTUSE)
    7905     G2frame.Bind(wx.EVT_MENU, OnRenameSelSeq, id=G2G.wxID_RENAMESEQSEL)
    7906     G2frame.Bind(wx.EVT_MENU, OnSaveSelSeq, id=G2G.wxID_SAVESEQSEL)
    7907     G2frame.Bind(wx.EVT_MENU, OnSaveSelSeqCSV, id=G2G.wxID_SAVESEQSELCSV)
    7908     G2frame.Bind(wx.EVT_MENU, OnSaveSeqCSV, id=G2G.wxID_SAVESEQCSV)
    7909     G2frame.Bind(wx.EVT_MENU, OnPlotSelSeq, id=G2G.wxID_PLOTSEQSEL)
    7910     G2frame.Bind(wx.EVT_MENU, OnAveSelSeq, id=G2G.wxID_AVESEQSEL)
    7911     #G2frame.Bind(wx.EVT_MENU, OnReOrgSelSeq, id=G2G.wxID_ORGSEQSEL)
    7912     G2frame.Bind(wx.EVT_MENU, OnSelectUpdate, id=G2G.wxID_UPDATESEQSEL)
    7913     G2frame.Bind(wx.EVT_MENU, OnEditSelectPhaseVars, id=G2G.wxID_EDITSEQSELPHASE)
    7914     G2frame.Bind(wx.EVT_MENU, onSelectSeqVars, id=G2G.wxID_ORGSEQINC)
    7915     G2frame.Bind(wx.EVT_MENU, AddNewPseudoVar, id=G2G.wxID_ADDSEQVAR)
    7916     G2frame.Bind(wx.EVT_MENU, AddNewDistPseudoVar, id=G2G.wxID_ADDSEQDIST)
    7917     G2frame.Bind(wx.EVT_MENU, AddNewAnglePseudoVar, id=G2G.wxID_ADDSEQANGLE)
    7918     G2frame.Bind(wx.EVT_MENU, DelPseudoVar, id=G2G.wxID_DELSEQVAR)
    7919     G2frame.Bind(wx.EVT_MENU, EditPseudoVar, id=G2G.wxID_EDITSEQVAR)
    7920     G2frame.Bind(wx.EVT_MENU, AddNewParFitEq, id=G2G.wxID_ADDPARFIT)
    7921     G2frame.Bind(wx.EVT_MENU, CopyParFitEq, id=G2G.wxID_COPYPARFIT)
    7922     G2frame.Bind(wx.EVT_MENU, DelParFitEq, id=G2G.wxID_DELPARFIT)
    7923     G2frame.Bind(wx.EVT_MENU, EditParFitEq, id=G2G.wxID_EDITPARFIT)
    7924     G2frame.Bind(wx.EVT_MENU, DoParEqFit, id=G2G.wxID_DOPARFIT)
    7925 
    7926     for id in G2frame.dataWindow.SeqExportLookup:       
    7927         G2frame.Bind(wx.EVT_MENU, DoSequentialExport, id=id)
    7928 
    7929     EnablePseudoVarMenus()
    7930     EnableParFitEqMenus()
    7931 
    7932     # scan for locations where the variables change
    7933     VaryListChanges = [] # histograms where there is a change
    7934     combinedVaryList = []
    7935     firstValueDict = {}
    7936     vallookup = {}
    7937     posdict = {}
    7938     prevVaryList = []
    7939     foundNames = []
    7940     missing = 0
    7941     for i,name in enumerate(histNames):
    7942         if name not in data:
    7943             if missing < 5:
    7944                 print(" Warning: "+name+" not found")
    7945             elif missing == 5:
    7946                 print (' Warning: more are missing')
    7947             missing += 1
    7948             continue
    7949         foundNames.append(name)
    7950         maxPWL = 5
    7951         for var,val,sig in zip(data[name]['varyList'],data[name]['variables'],data[name]['sig']):
    7952             svar = striphist(var,'*') # wild-carded
    7953             if 'PWL' in svar:
    7954                 if int(svar.split(':')[-1]) > maxPWL:
    7955                     continue
    7956             if svar not in combinedVaryList:
    7957                 # add variables to list as they appear
    7958                 combinedVaryList.append(svar)
    7959                 firstValueDict[svar] = (val,sig)
    7960         if prevVaryList != data[name]['varyList']: # this refinement has a different refinement list from previous
    7961             prevVaryList = data[name]['varyList']
    7962             vallookup[name] = dict(zip(data[name]['varyList'],data[name]['variables']))
    7963             posdict[name] = {}
    7964             for var in data[name]['varyList']:
    7965                 svar = striphist(var,'*')
    7966                 if 'PWL' in svar:
    7967                     if int(svar.split(':')[-1]) > maxPWL:
    7968                         continue
    7969                 posdict[name][combinedVaryList.index(svar)] = svar
    7970             VaryListChanges.append(name)
    7971     if missing:
    7972         print (' Warning: Total of %d data sets missing from sequential results'%(missing))
    7973     #if len(VaryListChanges) > 1:
    7974     #    G2frame.dataWindow.SequentialFile.Enable(G2G.wxID_ORGSEQSEL,True)
    7975     #else:
    7976     #    G2frame.dataWindow.SequentialFile.Enable(G2G.wxID_ORGSEQSEL,False)
    7977     ######  build up the data table by columns -----------------------------------------------
    7978     histNames = foundNames
    7979     nRows = len(histNames)
    7980     G2frame.colList = [list(range(nRows)),nRows*[True]]
    7981     G2frame.colSigs = [None,None,]
    7982     colLabels = ['No.','Use',]
    7983     Types = [wg.GRID_VALUE_LONG,wg.GRID_VALUE_BOOL,]
    7984     # start with Rwp values
    7985     if 'IMG ' not in histNames[0][:4]:
    7986         G2frame.colList += [[data[name]['Rvals']['Rwp'] for name in histNames]]
    7987         G2frame.colSigs += [None]
    7988         colLabels += ['Rwp']
    7989         Types += [wg.GRID_VALUE_FLOAT+':10,3',]
    7990     # add % change in Chi^2 in last cycle
    7991     if histNames[0][:4] not in ['SASD','IMG ','REFD'] and Controls.get('ShowCell'):
    7992         G2frame.colList += [[100.*data[name]['Rvals'].get('DelChi2',-1) for name in histNames]]
    7993         G2frame.colSigs += [None]
    7994         colLabels += [u'\u0394\u03C7\u00B2 (%)']
    7995         Types += [wg.GRID_VALUE_FLOAT+':10,5',]
    7996     deltaChiCol = len(colLabels)-1
    7997     # frozen variables?
    7998     if 'parmFrozen' in Controls:
    7999         f = [len(Controls['parmFrozen'].get(h,[])) for h in histNames]
    8000         if any(f):
    8001             G2frame.colList += [f]
    8002             G2frame.colSigs += [None]
    8003             colLabels += ['frozen']
    8004             Types += [wg.GRID_VALUE_LONG]
    8005     # add changing sample parameters to table
    8006     for key in sampleParms:
    8007         G2frame.colList += [sampleParms[key]]
    8008         G2frame.colSigs += [None]
    8009         colLabels += [key]
    8010         Types += [wg.GRID_VALUE_FLOAT,]
    8011     sampleDict = {}
    8012     for i,name in enumerate(histNames):
    8013         sampleDict[name] = dict(zip(sampleParms.keys(),[sampleParms[key][i] for key in sampleParms.keys()]))
    8014     # add unique cell parameters 
    8015     if Controls.get('ShowCell',False) and len(newCellDict):
    8016         phaseLookup = {Phases[phase]['pId']:phase for phase in Phases}
    8017         for pId in sorted(RecpCellTerms):
    8018             pfx = str(pId)+'::' # prefix for A values from phase
    8019             cells = []
    8020             cellESDs = []
    8021             colLabels += [pfx+cellUlbl[i] for i in uniqCellIndx[pId]]
    8022             colLabels += [pfx+'Vol']
    8023             Types += (len(uniqCellIndx[pId]))*[wg.GRID_VALUE_FLOAT+':10,5',]
    8024             Types += [wg.GRID_VALUE_FLOAT+':10,3',]
    8025             Albls = [pfx+'A'+str(i) for i in range(6)]
    8026             for name in histNames:
    8027                 if name not in Histograms: continue
    8028                 hId = Histograms[name]['hId']
    8029                 phfx = '%d:%d:'%(pId,hId)
    8030                 esdLookUp = {}
    8031                 dLookup = {}
    8032                 for item in data[name]['newCellDict']:
    8033                     if phfx+item.split('::')[1] in data[name]['varyList']:
    8034                         esdLookUp[newCellDict[item][0]] = item
    8035                         dLookup[item] = newCellDict[item][0]
    8036                 covData = {'varyList': [dLookup.get(striphist(v),v) for v in data[name]['varyList']],
    8037                     'covMatrix': data[name]['covMatrix']}
    8038                 A = RecpCellTerms[pId][:] # make copy of starting A values
    8039                 # update with refined values
    8040                 for i,j in enumerate(('D11','D22','D33','D12','D13','D23')):
    8041                     var = str(pId)+'::A'+str(i)
    8042                     Dvar = str(pId)+':'+str(hId)+':'+j
    8043                     # apply Dij value if non-zero
    8044                     if Dvar in data[name]['parmDict']:
    8045                         parmDict = data[name]['parmDict']
    8046                         if parmDict[Dvar] != 0.0:
    8047                             A[i] += parmDict[Dvar]
    8048                     # override with fit result if is Dij varied
    8049                     if var in cellAlist:
    8050                         try:
    8051                             A[i] = data[name]['newCellDict'][esdLookUp[var]][1] # get refined value
    8052                         except KeyError:
    8053                             pass
    8054                 # apply symmetry
    8055                 cellDict = dict(zip(Albls,A))
    8056                 try:    # convert to direct cell
    8057                     A,zeros = G2stIO.cellFill(pfx,SGdata[pId],cellDict,zeroDict[pId])
    8058                     c = G2lat.A2cell(A)
    8059                     vol = G2lat.calc_V(A)
    8060                     cE = G2stIO.getCellEsd(pfx,SGdata[pId],A,covData)
    8061                 except:
    8062                     c = 6*[None]
    8063                     cE = 6*[None]
    8064                     vol = None
    8065                 # add only unique values to table
    8066                 if name in Phases[phaseLookup[pId]]['Histograms']:
    8067                     cells += [[c[i] for i in uniqCellIndx[pId]]+[vol]]
    8068                     cellESDs += [[cE[i] for i in uniqCellIndx[pId]]+[cE[-1]]]
    8069                 else:
    8070                     cells += [[None for i in uniqCellIndx[pId]]+[None]]
    8071                     cellESDs += [[None for i in uniqCellIndx[pId]]+[None]]
    8072             G2frame.colList += zip(*cells)
    8073             G2frame.colSigs += zip(*cellESDs)
    8074     # sort out the variables in their selected order
    8075     varcols = 0
    8076     for d in posdict.values():
    8077         varcols = max(varcols,max(d.keys())+1)
    8078     # get labels for each column
    8079     for i in range(varcols):
    8080         lbl = ''
    8081         for h in VaryListChanges:
    8082             if posdict[h].get(i):
    8083                 if posdict[h].get(i) in lbl: continue
    8084                 if lbl != "": lbl += '/'
    8085                 lbl += posdict[h].get(i)
    8086         colLabels.append(lbl)
    8087     Types += varcols*[wg.GRID_VALUE_FLOAT,]
    8088     vals = []
    8089     esds = []
    8090     varsellist = None        # will be a list of variable names in the order they are selected to appear
    8091     # tabulate values for each hist, leaving None for blank columns
    8092     for name in histNames:
    8093         if name in posdict:
    8094             varsellist = [posdict[name].get(i) for i in range(varcols)]
    8095             # translate variable names to how they will be used in the headings
    8096             vs = [striphist(v,'*') for v in data[name]['varyList']]
    8097             # determine the index for each column (or None) in the data[]['variables'] and ['sig'] lists
    8098             sellist = [vs.index(v) if v is not None else None for v in varsellist]
    8099             #sellist = [i if striphist(v,'*') in varsellist else None for i,v in enumerate(data[name]['varyList'])]
    8100         if not varsellist: raise Exception()
    8101         vals.append([data[name]['variables'][s] if s is not None else None for s in sellist])
    8102         esds.append([data[name]['sig'][s] if s is not None else None for s in sellist])
    8103     G2frame.colList += zip(*vals)
    8104     G2frame.colSigs += zip(*esds)
    8105     # tabulate constrained variables, removing histogram numbers if needed
    8106     # from parameter label
    8107     depValDict = {}
    8108     depSigDict = {}
    8109     for name in histNames:
    8110         for var in data[name].get('depParmDict',{}):
    8111             val,sig = data[name]['depParmDict'][var]
    8112             svar = striphist(var,'*')
    8113             if svar not in depValDict:
    8114                depValDict[svar] = [val]
    8115                depSigDict[svar] = [sig]
    8116             else:
    8117                depValDict[svar].append(val)
    8118                depSigDict[svar].append(sig)
    8119    
    8120     # add the dependent constrained variables to the table
    8121     for var in sorted(depValDict):
    8122         if len(depValDict[var]) != len(histNames): continue
    8123         colLabels.append(var)
    8124         Types += [wg.GRID_VALUE_FLOAT+':10,5',]
    8125         G2frame.colSigs += [depSigDict[var]]
    8126         G2frame.colList += [depValDict[var]]
    8127 
    8128     # add refined atom parameters to table
    8129     colLabels += sorted(atomLookup.keys())
    8130     for parm in sorted(atomLookup):
    8131         G2frame.colList += [[data[name]['newAtomDict'][atomLookup[parm]][1] for name in histNames]]
    8132         Types += [wg.GRID_VALUE_FLOAT+':10,5',]
    8133         if atomLookup[parm] in data[histNames[0]]['varyList']:
    8134             col = data[histNames[0]]['varyList'].index(atomLookup[parm])
    8135             G2frame.colSigs += [[data[name]['sig'][col] for name in histNames]]
    8136         else:
    8137             G2frame.colSigs += [None]
    8138            
    8139     # compute and add weight fractions to table if varied
    8140     for phase in Phases:
    8141         var = str(Phases[phase]['pId'])+':*:Scale'
    8142         if var not in combinedVaryList+list(depValDict.keys()): continue
    8143         wtFrList = []
    8144         sigwtFrList = []
    8145         for i,name in enumerate(histNames):
    8146             if name not in Phases[phase]['Histograms']:
    8147                 wtFrList.append(None)
    8148                 sigwtFrList.append(0.0)
    8149                 continue
    8150             elif not Phases[phase]['Histograms'][name]['Use']:
    8151                 wtFrList.append(None)
    8152                 sigwtFrList.append(0.0)
    8153                 continue
    8154             wtFrSum = 0.
    8155             for phase1 in Phases:
    8156                 if name not in Phases[phase1]['Histograms']: continue
    8157                 if not Phases[phase1]['Histograms'][name]['Use']: continue
    8158                 wtFrSum += Phases[phase1]['Histograms'][name]['Scale'][0]*Phases[phase1]['General']['Mass']
    8159             var = str(Phases[phase]['pId'])+':'+str(i)+':Scale'
    8160             wtFr = Phases[phase]['Histograms'][name]['Scale'][0]*Phases[phase]['General']['Mass']/wtFrSum
    8161             wtFrList.append(wtFr)
    8162             if var in data[name]['varyList']:
    8163                 sig = data[name]['sig'][data[name]['varyList'].index(var)]*wtFr/Phases[phase]['Histograms'][name]['Scale'][0]
    8164             else:
    8165                 sig = 0.0
    8166             sigwtFrList.append(sig)
    8167         colLabels.append(str(Phases[phase]['pId'])+':*:WgtFrac')
    8168         Types += [wg.GRID_VALUE_FLOAT+':10,5',]
    8169         G2frame.colList += [wtFrList]
    8170         G2frame.colSigs += [sigwtFrList]
    8171                
    8172     # evaluate Pseudovars, their ESDs and add them to grid
    8173     for expr in data['SeqPseudoVars']:
    8174         obj = data['SeqPseudoVars'][expr]
    8175         calcobj = G2obj.ExpressionCalcObj(obj)
    8176         valList = []
    8177         esdList = []
    8178         for seqnum,name in enumerate(histNames):
    8179             sigs = data[name]['sig']
    8180             G2mv.InitVars()
    8181             parmDict = data[name].get('parmDict')
    8182             constraintInfo = data[name].get('constraintInfo',[[],[],{},[],seqnum])
    8183             groups,parmlist,constrDict,fixedList,ihst = constraintInfo
    8184             varyList = data[name]['varyList']
    8185             parmDict = data[name]['parmDict']
    8186             msg = G2mv.EvaluateMultipliers(constrDict,parmDict)
    8187             if msg:
    8188                 print('Unable to interpret multiplier(s) for',name,':',msg)
    8189                 continue
    8190             G2mv.GenerateConstraints(varyList,constrDict,fixedList,parmDict,SeqHist=ihst)
    8191             if 'Dist' in expr:
    8192                 derivs = G2mth.CalcDistDeriv(obj.distance_dict,obj.distance_atoms, parmDict)
    8193                 pId = obj.distance_dict['pId']
    8194                 aId,bId = obj.distance_atoms
    8195                 varyNames = ['%d::dA%s:%d'%(pId,ip,aId) for ip in ['x','y','z']]
    8196                 varyNames += ['%d::dA%s:%d'%(pId,ip,bId) for ip in ['x','y','z']]
    8197                 VCoV = G2mth.getVCov(varyNames,varyList,data[name]['covMatrix'])
    8198                 esdList.append(np.sqrt(np.inner(derivs,np.inner(VCoV,derivs.T)) ))
    8199 #                GSASIIpath.IPyBreak()
    8200             elif 'Angle' in expr:
    8201                 derivs = G2mth.CalcAngleDeriv(obj.angle_dict,obj.angle_atoms, parmDict)
    8202                 pId = obj.angle_dict['pId']
    8203                 aId,bId = obj.angle_atoms
    8204                 varyNames = ['%d::dA%s:%d'%(pId,ip,aId) for ip in ['x','y','z']]
    8205                 varyNames += ['%d::dA%s:%d'%(pId,ip,bId[0]) for ip in ['x','y','z']]
    8206                 varyNames += ['%d::dA%s:%d'%(pId,ip,bId[1]) for ip in ['x','y','z']]
    8207                 VCoV = G2mth.getVCov(varyNames,varyList,data[name]['covMatrix'])
    8208                 esdList.append(np.sqrt(np.inner(derivs,np.inner(VCoV,derivs.T)) ))
    8209             else:
    8210                 derivs = np.array(
    8211                     [EvalPSvarDeriv(calcobj,parmDict.copy(),sampleDict[name],var,ESD)
    8212                      for var,ESD in zip(varyList,sigs)])
    8213                 if None in list(derivs):
    8214                     esdList.append(None)
    8215                 else:
    8216                     esdList.append(np.sqrt(
    8217                         np.inner(derivs,np.inner(data[name]['covMatrix'],derivs.T)) ))
    8218             PSvarDict = parmDict.copy()
    8219             PSvarDict.update(sampleDict[name])
    8220             UpdateParmDict(PSvarDict)
    8221             calcobj.UpdateDict(PSvarDict)
    8222             valList.append(calcobj.EvalExpression())
    8223 #            if calcobj.su is not None: esdList[-1] = calcobj.su
    8224         if not esdList:
    8225             esdList = None
    8226         G2frame.colList += [valList]
    8227         G2frame.colSigs += [esdList]
    8228         colLabels += [expr]
    8229         Types += [wg.GRID_VALUE_FLOAT+':10,5']
    8230     #---- table build done -------------------------------------------------------------
    8231 
    8232     # Make dict needed for creating & editing pseudovars (PSvarDict).
    8233    
    8234     name = histNames[0]
    8235     parmDict = data[name].get('parmDict',{})
    8236     PSvarDict = parmDict.copy()
    8237     PSvarDict.update(sampleParms)
    8238     UpdateParmDict(PSvarDict)
    8239     # Also dicts of variables
    8240     # for Parametric fitting from the data table
    8241     parmDict = dict(zip(colLabels,list(zip(*G2frame.colList))[0])) # scratch dict w/all values in table
    8242     parmDict.update({var:val for var,val in newCellDict.values()}) #  add varied reciprocal cell terms
    8243     del parmDict['Use']
    8244     name = histNames[0]
    8245 
    8246     # remove selected items from table
    8247     saveColLabels = colLabels[:]
    8248     if G2frame.SeqTblHideList is None:      #set default hides
    8249         G2frame.SeqTblHideList = [item for item in saveColLabels if 'Back' in item]
    8250         G2frame.SeqTblHideList += [item for item in saveColLabels if 'dA' in item]
    8251         G2frame.SeqTblHideList += [item for item in saveColLabels if ':*:D' in item]
    8252     #******************************************************************************
    8253     # create a set of values for example evaluation of pseudovars and
    8254     # this does not work for refinements that have differing numbers of variables.
    8255     VarDict = {}
    8256     for i,var in enumerate(colLabels):
    8257         if var in ['Use','Rwp',u'\u0394\u03C7\u00B2 (%)']: continue
    8258         if G2frame.colList[i][0] is None:
    8259             val,sig = firstValueDict.get(var,[None,None])
    8260         elif G2frame.colSigs[i]:
    8261             val,sig = G2frame.colList[i][0],G2frame.colSigs[i][0]
    8262         else:
    8263             val,sig = G2frame.colList[i][0],None
    8264         if striphist(var) not in Dlookup:
    8265             VarDict[var] = val
    8266     # add recip cell coeff. values
    8267     VarDict.update({var:val for var,val in newCellDict.values()})
    8268 
    8269     # remove items to be hidden from table
    8270     for l in reversed(range(len(colLabels))):
    8271         if colLabels[l] in G2frame.SeqTblHideList:
    8272             del colLabels[l]
    8273             del G2frame.colList[l]
    8274             del G2frame.colSigs[l]
    8275 
    8276     # make a copy of the column labels substituting alternate labels when defined
    8277     displayLabels = colLabels[:]
    8278     for i,l in enumerate(colLabels):
    8279         if l in variableLabels:
    8280             displayLabels[i] = variableLabels[l]
    8281            
    8282     G2frame.dataWindow.ClearData()
    8283     G2frame.dataWindow.currentGrids = []
    8284     G2frame.dataDisplay = G2G.GSGrid(parent=G2frame.dataWindow)
    8285     G2frame.dataDisplay.SetScrollRate(10,10)
    8286     G2frame.dataWindow.GetSizer().Add(G2frame.dataDisplay,1,wx.ALL|wx.EXPAND)
    8287     if histNames[0].startswith('PWDR'):
    8288         #rowLabels = [str(i)+': '+l[5:30] for i,l in enumerate(histNames)]
    8289         rowLabels = [l[5:] for i,l in enumerate(histNames)]
    8290     else:
    8291         rowLabels = histNames
    8292     G2frame.SeqTable = G2G.Table([list(cl) for cl in zip(*G2frame.colList)],     # convert from columns to rows
    8293         colLabels=displayLabels,rowLabels=rowLabels,types=Types)
    8294     G2frame.dataDisplay.SetTable(G2frame.SeqTable, True)
    8295     # make all Use editable all others ReadOnly
    8296     for c in range(len(colLabels)):
    8297         for r in range(nRows):
    8298             if c == 1:
    8299                 G2frame.dataDisplay.SetReadOnly(r,c,isReadOnly=False)
    8300             else:
    8301                 G2frame.dataDisplay.SetReadOnly(r,c,isReadOnly=True)
    8302     if 'phoenix' in wx.version():
    8303         G2frame.dataDisplay.Bind(wg.EVT_GRID_CELL_CHANGED, OnCellChange)
    8304     else:
    8305         G2frame.dataDisplay.Bind(wg.EVT_GRID_CELL_CHANGE, OnCellChange)
    8306 #    G2frame.dataDisplay.Bind(wx.EVT_KEY_UP,OnKeyUp)
    8307     G2frame.dataDisplay.Bind(wg.EVT_GRID_LABEL_LEFT_CLICK, PlotSSelect)
    8308     G2frame.dataDisplay.Bind(wg.EVT_GRID_LABEL_LEFT_DCLICK, PlotSelect)
    8309 #    G2frame.dataDisplay.Bind(wg.EVT_GRID_SELECT_CELL,PlotSSelect)
    8310     G2frame.dataDisplay.Bind(wg.EVT_GRID_LABEL_RIGHT_CLICK, SetLabelString)
    8311     G2frame.dataDisplay.SetRowLabelSize(8*len(histNames[0]))       #pretty arbitrary 8
    8312     G2frame.dataDisplay.SetMargins(0,0)
    8313     G2frame.dataDisplay.AutoSizeColumns(False)
    8314     # highlight unconverged shifts
    8315     if histNames[0][:4] not in ['SASD','IMG ','REFD',]:
    8316         for row,name in enumerate(histNames):
    8317             deltaChi = G2frame.SeqTable.GetValue(row,deltaChiCol)
    8318             try:
    8319                 if deltaChi > 10.:
    8320                     G2frame.dataDisplay.SetCellStyle(row,deltaChiCol,color=wx.Colour(255,0,0))
    8321                 elif deltaChi > 1.0:
    8322                     G2frame.dataDisplay.SetCellStyle(row,deltaChiCol,color=wx.Colour(255,255,0))
    8323             except:
    8324                 pass
    8325     G2frame.dataDisplay.InstallGridToolTip(GridSetToolTip,GridColLblToolTip)
    8326     #G2frame.dataDisplay.SendSizeEvent() # resize needed on mac
    8327     #G2frame.dataDisplay.Refresh() # shows colored text on mac
    8328     G2frame.dataWindow.SetDataSize()
    8329 
    83306824#####  Main PWDR panel ########################################################   
    83316825def UpdatePWHKPlot(G2frame,kind,item):
     
    88947388            G2frame.dataWindow.helpKey = 'Sequential'  # for now all sequential refinements are documented in one place
    88957389            data = G2frame.GPXtree.GetItemPyData(item)
    8896             UpdateSeqResults(G2frame,data)
     7390            G2seq.UpdateSeqResults(G2frame,data)
    88977391        elif G2frame.GPXtree.GetItemText(item) == 'Covariance':
    88987392            data = G2frame.GPXtree.GetItemPyData(item)
  • trunk/GSASIIphsGUI.py

    r4829 r4833  
    11# -*- coding: utf-8 -*-
    22#GSASII - phase data display routines
    3 ########### SVN repository information ###################
     3#========== SVN repository information ###################
    44# $Date$
    55# $Author$
     
    77# $URL$
    88# $Id$
    9 ########### SVN repository information ###################
     9#========== SVN repository information ###################
    1010'''
    1111*GSASIIphsGUI: Phase GUI*
     
    198198        parent.Raise()
    199199        self.EndModal(wx.ID_CANCEL)
    200 ################################################################################
     200#==============================================================================
    201201class SphereEnclosure(wx.Dialog):
    202202    ''' Add atoms within sphere of enclosure to drawing
     
    300300        self.EndModal(wx.ID_CANCEL)
    301301       
    302 ################################################################################
     302#==============================================================================
    303303class TransformDialog(wx.Dialog):
    304304    ''' Phase transformation X' = M*(X-U)+V
     
    613613        self.EndModal(wx.ID_CANCEL)
    614614       
    615 ################################################################################
     615#==============================================================================
    616616class UseMagAtomDialog(wx.Dialog):
    617617    '''Get user selected magnetic atoms after cell transformation
     
    731731           
    732732               
    733 ################################################################################
     733#==============================================================================
    734734class RotationDialog(wx.Dialog):
    735735    ''' Get Rotate & translate matrix & vector - currently not used
     
    846846        self.EndModal(wx.ID_CANCEL)   
    847847       
    848 ################################################################################
     848#==============================================================================
    849849class DIFFaXcontrols(wx.Dialog):
    850850    ''' Solicit items needed to prepare DIFFaX control.dif file
     
    991991        self.EndModal(wx.ID_CANCEL)
    992992
    993 ################################################################################
     993#==============================================================================
    994994class AddHatomDialog(wx.Dialog):
    995995    '''H atom addition dialog. After :meth:`ShowModal` returns, the results
     
    11021102        self.EndModal(wx.ID_CANCEL)
    11031103
    1104 ################################################################################
    1105 #### Phase editing routines
    1106 ################################################################################
     1104#### Phase editing routines ################################################################################
    11071105def DrawAtomsReplaceByID(data,loc,atom,ID):
    11081106    '''Replace all atoms in drawing array with an ID matching the specified value'''
     
    11671165    return atomInfo
    11681166   
    1169 def getAtomSelections(AtmTbl,cn=0,action='action',includeView=False):
     1167def getAtomSelections(AtmTbl,cn=0,action='action',includeView=False,ask=True):
    11701168    '''get selected atoms from table or ask user if none are selected
    11711169   
     
    11831181    for top,bottom in zip([r for r,c in AtmTbl.GetSelectionBlockTopLeft()],
    11841182                          [r for r,c in AtmTbl.GetSelectionBlockBottomRight()]):
    1185             indx += list(range(top,bottom+1))
     1183        indx += list(range(top,bottom+1))
    11861184    indx = list(set(indx))
    1187     if indx: return indx
     1185    if indx or not ask: return indx
    11881186    choices = []
    11891187    for i in range(AtmTbl.GetNumberRows()):
     
    16091607            wx.MessageBox(msg,caption='Element symbol error')
    16101608
    1611 ################################################################################
    1612 ##### General phase routines
    1613 ################################################################################
    1614 
     1609##### General phase routines ################################################################################
    16151610    def UpdateGeneral(Scroll=0,SkipDraw=False):
    16161611        '''Draw the controls for the General phase data subpage
     
    30843079        G2frame.GPXtree.SelectItem(sub)
    30853080       
    3086 ################################################################################
    3087 #####  Atom routines
    3088 ################################################################################
    3089 
     3081#####  Atom routines ################################################################################
    30903082    def FillAtomsGrid(Atoms):
    30913083        '''Display the contents of the Atoms tab
     
    34023394                    Atoms.ClearSelection()
    34033395                    Atoms.SelectRow(r,True)
     3396            G2plt.PlotStructure(G2frame,data)
    34043397               
    34053398        def ChangeSelection(event):
     
    35803573        Atoms.Bind(wg.EVT_GRID_LABEL_LEFT_CLICK, RowSelect)
    35813574        Atoms.Bind(wg.EVT_GRID_LABEL_RIGHT_CLICK, ChangeSelection)
     3575       
     3576        lblList = ('Set refine flags','Modify selected parameters',
     3577                       'Insert new before selected','Transform selected',
     3578                       'Set selected xyz to view point','Select all',
     3579                       'Select from list','Set view point from selected',
     3580                       'Delete')
     3581        callList = (AtomRefine,AtomModify,OnAtomInsert,AtomTransform,
     3582                        OnAtomMove,OnSetAll,OnSetbyList,SetAtomsViewPoint,
     3583                        AtomDelete)
     3584        onRightClick = Atoms.setupPopup(lblList,callList)
     3585        Atoms.Bind(wg.EVT_GRID_CELL_RIGHT_CLICK, onRightClick)
     3586        Atoms.Bind(wg.EVT_GRID_LABEL_RIGHT_CLICK, onRightClick)
    35823587        Atoms.SetMargins(0,0)
    35833588       
     
    38373842        indx = getAtomSelections(Atoms)
    38383843        colLabels = [Atoms.GetColLabelValue(c) for c in range(Atoms.GetNumberCols())]
     3844        delList = ''
     3845        for i in indx:
     3846            if delList: delList += ', '
     3847            delList += data['Atoms'][i][0]
     3848        dlg = wx.MessageDialog(G2frame,
     3849            'Do you want to delete atom(s): {}?'.format(delList),
     3850                    'Confirm delete',
     3851                    wx.YES|wx.NO)
     3852        try:
     3853            dlg.CenterOnParent()
     3854            result = dlg.ShowModal()
     3855        finally:
     3856            dlg.Destroy()
     3857        if result != wx.ID_YES: return
    38393858        HydIds = data['General']['HydIds']
    38403859        ci = colLabels.index('I/A')
     
    41794198       
    41804199    def OnSetAll(event):
    4181         'set refinement flags for all atoms in table'
     4200        'set all atoms in table as selected'
    41824201        for row in range(Atoms.GetNumberRows()):
    41834202            Atoms.SelectRow(row,True)
    4184    
     4203        G2plt.PlotStructure(G2frame,data)
     4204
     4205    def OnSetbyList(event):
     4206        'select atoms using a filtered listbox'
     4207        choices = [atm[0] for atm in data['Atoms']]
     4208        dlg = G2G.G2MultiChoiceDialog(G2frame,
     4209                    'Select atoms','Choose atoms to select',choices)
     4210        indx = []
     4211        if dlg.ShowModal() == wx.ID_OK:
     4212            indx = dlg.GetSelections()
     4213        dlg.Destroy()
     4214        if len(indx) == 0: return
     4215        Atoms.ClearSelection()       
     4216        for row in indx:
     4217            Atoms.SelectRow(row,True)
     4218        G2plt.PlotStructure(G2frame,data)
     4219
     4220    def SetAtomsViewPoint(event):
     4221        cx,ct,cs,ci = G2mth.getAtomPtrs(data)
     4222        indx = getAtomSelections(Atoms,ct-1)
     4223        if not indx: return
     4224        pos = np.zeros(3)
     4225        for i in indx:
     4226            pos += data['Atoms'][i][cx:cx+3]
     4227        data['Drawing']['viewPoint'] = [list(pos/len(indx)),[indx[0],0]]
     4228        G2plt.PlotStructure(G2frame,data)
     4229                       
    41854230    def OnDistAnglePrt(event):
    41864231        'save distances and angles to a file'   
     
    43704415        wx.CallAfter(FillAtomsGrid,Atoms)
    43714416       
    4372 ################################################################################
    4373 #### Dysnomia (MEM) Data page
    4374 ################################################################################
    4375        
     4417#### Dysnomia (MEM) Data page ##############################################################################         
    43764418    def UpdateDysnomia():
    43774419        ''' Present the controls for running Dysnomia
     
    45654607                style=wx.ICON_ERROR)
    45664608
    4567 ################################################################################
    4568 #### RMC Data page
    4569 ################################################################################
    4570 
     4609#### RMC Data page ################################################################################
    45714610    def UpdateRMC():
    45724611        ''' Present the controls for running fullrmc or RMCProfile
     
    63246363       
    63256364           
    6326 ################################################################################
    6327 #### Layer Data page
    6328 ################################################################################
    6329        
     6365### Layer Data page ################################################################################
    63306366    def UpdateLayerData(Scroll=0):
    63316367        '''Present the contents of the Phase/Layers tab for stacking fault simulation
     
    71537189        wx.CallAfter(UpdateLayerData)
    71547190       
    7155 ################################################################################
    7156 #### Wave Data page
    7157 ################################################################################
    7158 
     7191#### Wave Data page ################################################################################
    71597192    def UpdateWavesData(Scroll=0):
    71607193       
     
    74197452        UpdateWavesData()
    74207453
    7421 ################################################################################
    7422 #### Structure drawing GUI stuff               
    7423 ################################################################################
     7454#### Structure drawing GUI stuff ################################################################################
    74247455    def SetupDrawingData():
    74257456        generalData = data['General']
     
    75827613        G2frame.GetStatusBar().SetStatusText('New rigid body UNKRB added to set of Residue rigid bodies',1)
    75837614
    7584 ################################################################################
    7585 ##### Draw Atom routines
    7586 ################################################################################
     7615##### Draw Atom routines ################################################################################
    75877616    def UpdateDrawAtoms(atomStyle=''):
    75887617        def RefreshDrawAtomGrid(event):
     
    77827811        drawAtoms.Bind(wg.EVT_GRID_CELL_LEFT_DCLICK, RefreshDrawAtomGrid)
    77837812        drawAtoms.Bind(wg.EVT_GRID_LABEL_LEFT_CLICK, RowSelect)
     7813
     7814        lblList = ('Delete','Set atom style','Set atom label',
     7815                           'Set atom color','Set view point','Generate copy',
     7816                           'Generate surrounding sphere','Transform atoms',
     7817                           'Generate bonded','Select from list')
     7818        callList = (DrawAtomsDelete,DrawAtomStyle, DrawAtomLabel,
     7819                            DrawAtomColor,SetViewPoint,AddSymEquiv,
     7820                            AddSphere,TransformSymEquiv,
     7821                            FillCoordSphere,SelDrawList)
     7822        onRightClick = drawAtoms.setupPopup(lblList,callList)
     7823        drawAtoms.Bind(wg.EVT_GRID_CELL_RIGHT_CLICK, onRightClick)
     7824        drawAtoms.Bind(wg.EVT_GRID_LABEL_RIGHT_CLICK, onRightClick)
     7825       
    77847826        try:
    77857827            drawAtoms.Bind(wg.EVT_GRID_TABBING, NextAtom)
     
    79157957        if not indx: return
    79167958        atomData = data['Drawing']['Atoms']
    7917         data['Drawing']['viewPoint'] = [atomData[indx[0]][cx:cx+3],[indx[0],0]]
    7918 #            drawAtoms.ClearSelection()                                  #do I really want to do this?
     7959        pos = np.zeros(3)
     7960        for i in indx:
     7961            pos += atomData[i][cx:cx+3]
     7962        data['Drawing']['viewPoint'] = [list(pos/len(indx)),[indx[0],0]]
    79197963        G2plt.PlotStructure(G2frame,data)
    79207964           
     
    84158459        G2plt.PlotStructure(G2frame,data)
    84168460        event.StopPropagation()
     8461
     8462    def SelDrawList(event):
     8463        'select atoms using a filtered listbox'
     8464        choices = []
     8465        for i in range(drawAtoms.GetNumberRows()):
     8466            val = drawAtoms.GetCellValue(i,0)
     8467            if val in choices:
     8468                val += '_' + str(i)
     8469            choices.append(val)
     8470        if not choices: return
     8471        dlg = G2G.G2MultiChoiceDialog(G2frame,
     8472                    'Select atoms','Choose atoms to select',choices)
     8473        indx = []
     8474        if dlg.ShowModal() == wx.ID_OK:
     8475            indx = dlg.GetSelections()
     8476        dlg.Destroy()
     8477        if len(indx) == 0: return
     8478        drawAtoms.ClearSelection()       
     8479        for row in indx:
     8480            drawAtoms.SelectRow(row,True)
     8481        G2plt.PlotStructure(G2frame,data)
     8482        event.StopPropagation()
     8483
     8484    def DrawLoadSel(event):
     8485        '''Copy selected atoms from the atoms list into the draw atoms list, making
     8486        sure not to duplicate any.
     8487        '''
     8488        choices = [atm[0] for atm in data['Atoms']]
     8489        dlg = G2G.G2MultiChoiceDialog(G2frame,
     8490                    'Select atoms','Choose atoms to select',choices)
     8491        indx = []
     8492        if dlg.ShowModal() == wx.ID_OK:
     8493            indx = dlg.GetSelections()
     8494        dlg.Destroy()
     8495        if len(indx) == 0: return
     8496        drawingData = data['Drawing']
     8497        cxD,ctD,_,_ = data['Drawing']['atomPtrs']
     8498        cx,ct,cs,cia = data['General']['AtomPtrs']
     8499        atmsXYZ = [np.array(a[cx:cx+3]) for a in data['Atoms']]
     8500        for i in indx:
     8501            found = False
     8502            for dA in drawingData['Atoms']:
     8503                if (dA[ctD] == data['Atoms'][i][ct] and
     8504                    dA[ctD-1] == data['Atoms'][i][ct-1] and
     8505                    dA[cxD+3] == '1' and
     8506                    np.sum((atmsXYZ[i]-dA[cxD:cxD+3])**2) < 0.001):
     8507                    found = True
     8508                    break
     8509            if not found:
     8510                DrawAtomAdd(drawingData,data['Atoms'][i])
     8511        UpdateDrawAtoms()
     8512        drawAtoms.ClearSelection()
     8513        G2plt.PlotStructure(G2frame,data)
     8514        event.StopPropagation()
    84178515       
    84188516    def OnReloadDrawAtoms(event=None):
     
    85788676        G2plt.PlotStructure(G2frame,data)
    85798677       
    8580 ################################################################################
    8581 #### Draw Options page
    8582 ################################################################################
    8583 
     8678#### Draw Options page ################################################################################
    85848679    def UpdateDrawOptions():
    85858680        import wx.lib.colourselect as wcs
     
    90529147        SetPhaseWindow(drawOptions,mainSizer)
    90539148
    9054 ################################################################################
    9055 ####  Texture routines
    9056 ################################################################################
    9057        
     9149####  Texture routines ################################################################################       
    90589150    def UpdateTexture():
    90599151               
     
    94659557        SetPhaseWindow(Texture,mainSizer)
    94669558
    9467 ################################################################################
    9468 ##### DData routines - GUI stuff in GSASIIddataGUI.py
    9469 ################################################################################
    9470        
     9559##### DData routines - GUI stuff in GSASIIddataGUI.py ################################################################################
    94719560    def OnHklfAdd(event):
    94729561        keyList = data['Histograms'].keys()
     
    98259914        wx.CallAfter(G2ddG.UpdateDData,G2frame,DData,data)
    98269915
    9827 ################################################################################
    9828 ##### Rigid bodies
    9829 ################################################################################
    9830 
     9916##### Rigid bodies ################################################################################
    98319917    def FillRigidBodyGrid(refresh=True,vecId=None,resId=None):
    98329918        '''Fill the Rigid Body Phase information tab page.
     
    1108511171        cx,ct,cs,cia = general['AtomPtrs']
    1108611172        atomData = data['Atoms']
    11087         AtLookUp = G2mth.FillAtomLookUp(atomData,cia+8)
     11173        #AtLookUp = G2mth.FillAtomLookUp(atomData,cia+8)
    1108811174        Indx = {}
    1108911175        data['testRBObj'] = {}
     
    1134511431            FillRigidBodyGrid()
    1134611432           
    11347 ################################################################################
    11348 ##### MC/SA routines
    11349 ################################################################################
    11350 
     11433##### MC/SA routines ################################################################################
    1135111434    def UpdateMCSA(Scroll=0):
    1135211435        Indx = {}
     
    1190811991        UpdateMCSA()
    1190911992       
    11910 ################################################################################
    11911 ##### Pawley routines
    11912 ################################################################################
    11913 
     11993##### Pawley routines ################################################################################
    1191411994    def FillPawleyReflectionsGrid():
    1191511995        def KeyEditPawleyGrid(event):
     
    1221312293        G2frame.PawleyRefl.ForceRefresh()
    1221412294                           
    12215 ################################################################################
    12216 ##### Fourier routines
    12217 ################################################################################
    12218 
     12295##### Fourier routines ################################################################################
    1221912296    def FillMapPeaksGrid():
    1222012297                       
     
    1271512792        print ('clear texture? - does nothing')
    1271612793
    12717 ###############################################################################
    12718 ##### Phase page routines
    12719 ###############################################################################
    12720        
     12794##### Phase page routines ###############################################################################
    1272112795    def FillSelectPageMenu(TabSelectionIdDict, menuBar):
    1272212796        '''Fill "Select tab" menu with menu items for each tab and assign
     
    1284112915        FillSelectPageMenu(TabSelectionIdDict, G2frame.dataWindow.AtomsMenu)
    1284212916        G2frame.Bind(wx.EVT_MENU, OnSetAll, id=G2G.wxID_ATOMSSETALL)
     12917        G2frame.Bind(wx.EVT_MENU, OnSetbyList, id=G2G.wxID_ATOMSSETLST)
    1284312918        G2frame.Bind(wx.EVT_MENU, AtomRefine, id=G2G.wxID_ATOMSSETSEL)
    1284412919        G2frame.Bind(wx.EVT_MENU, AtomModify, id=G2G.wxID_ATOMSMODIFY)
     
    1284812923        G2frame.Bind(wx.EVT_MENU, AtomTransform, id=G2G.wxID_ATOMSTRANSFORM)
    1284912924#        G2frame.Bind(wx.EVT_MENU, AtomRotate, id=G2G.wxID_ATOMSROTATE)
    12850        
     12925        G2frame.Bind(wx.EVT_MENU, SetAtomsViewPoint, id=G2G.wxID_ATOMSSETVP)
     12926
    1285112927        G2frame.Bind(wx.EVT_MENU, OnAtomAdd, id=G2G.wxID_ATOMSEDITADD)
    1285212928        G2frame.Bind(wx.EVT_MENU, OnAtomViewAdd, id=G2G.wxID_ATOMSVIEWADD)
     
    1291312989        G2frame.Bind(wx.EVT_MENU, FillMolecule, id=G2G.wxID_DRAWADDMOLECULE)
    1291412990        G2frame.Bind(wx.EVT_MENU, MapVoid, id=G2G.wxID_DRAWVOIDMAP)
     12991        G2frame.Bind(wx.EVT_MENU, SelDrawList, id=G2G.wxID_DRAWSETSEL)
     12992        G2frame.Bind(wx.EVT_MENU, DrawLoadSel, id=G2G.wxID_DRAWLOADSEL)
    1291512993       
    1291612994        # RB Models
  • trunk/GSASIIplot.py

    r4826 r4833  
    408408        self.status = parent.CreateStatusBar()
    409409        self.status.SetFieldsCount(2)
    410         self.status.SetStatusWidths([150,-1])
     410        self.status.firstLen = 150
     411        self.status.SetStatusWidths([self.status.firstLen,-1])           
    411412        self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
    412413        self.nb.Bind(wx.EVT_KEY_UP,self.OnNotebookKey)
     
    640641        if plotDebug:
    641642            print ('PageChanged, self='+str(self).split('0x')[1]+tabLabel)
    642             print ('event type='+event.GetEventType())
     643            print ('event type=',event.GetEventType())
    643644        self.status.DestroyChildren()    #get rid of special stuff on status bar
    644645        self.status.SetStatusText('')  # clear old status message
    645         self.status.SetStatusWidths([150,-1])
     646        self.status.SetStatusWidths([self.status.firstLen,-1])
     647
     648    def SetHelpButton(self,help):
     649        '''Adds a Help button to the status bar on plots.
     650       
     651        TODO: This has a problem with PlotPatterns where creation of the
     652        HelpButton causes the notebook tabs to be duplicated. A manual
     653        resize fixes that, but the SendSizeEvent has not worked.
     654        '''
     655        hlp = G2G.HelpButton(self.status,helpIndex=help)
     656        rect = self.status.GetFieldRect(1)
     657        rect.x += rect.width - 20
     658        rect.width = 20
     659        rect.y += 1
     660        hlp.SetRect(rect)
     661        #wx.CallLater(100,self.TopLevelParent.SendSizeEvent)
    646662           
    647663    def InvokeTreeItem(self,pid):
     
    866882            page.canvas.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))
    867883           
    868 ################################################################################
    869 ##### PlotSngl
    870 ################################################################################
    871            
     884##### PlotSngl ################################################################     
    872885def PlotSngl(G2frame,newPlot=False,Data=None,hklRef=None,Title=''):
    873886    '''Structure factor plotting package - displays zone of reflections as rings proportional
     
    11001113        Page.canvas.draw()
    11011114       
    1102 ################################################################################
    1103 ##### Plot1DSngl
    1104 ################################################################################
     1115##### Plot1DSngl ################################################################################
    11051116def Plot1DSngl(G2frame,newPlot=False,hklRef=None,Super=0,Title=False):
    11061117    '''1D Structure factor plotting package - displays reflections as sticks proportional
     
    12191230    Draw()
    12201231   
    1221 ################################################################################
    1222 ##### Plot3DSngl
    1223 ################################################################################
    1224 
     1232##### Plot3DSngl ################################################################################
    12251233def Plot3DSngl(G2frame,newPlot=False,Data=None,hklRef=None,Title=False):
    12261234    '''3D Structure factor plotting package - displays reflections as rings proportional
     
    16791687    'z: zero zone toggle','c: reset to default','o: set view point = 0,0,0','b: toggle box ','+: increase scale','-: decrease scale',
    16801688    'f: Fobs','s: Fobs**2','u: unit','d: Fo-Fc','w: DF/sig','i: toggle intensity scaling']
    1681     cb = wx.ComboBox(G2frame.G2plotNB.status,style=wx.CB_DROPDOWN|wx.CB_READONLY,choices=choice)
     1689    cb = wx.ComboBox(G2frame.G2plotNB.status,style=wx.CB_DROPDOWN|wx.CB_READONLY,choices=choice,
     1690                         size=(G2frame.G2plotNB.status.firstLen,-1))
    16821691    cb.Bind(wx.EVT_COMBOBOX, OnKeyBox)
    16831692    cb.SetValue(' save as/key:')
     
    17001709#    if firstCall: Draw('main') # draw twice the first time that graphics are displayed
    17011710
    1702 ################################################################################
    1703 ##### PlotPatterns
    1704 ################################################################################
     1711##### PlotPatterns ################################################################################
    17051712def ReplotPattern(G2frame,newPlot,plotType,PatternName=None,PickName=None):
    17061713    '''This does the same as PlotPatterns except that it expects the information
     
    27132720            return '_'+string
    27142721
    2715     #=====================================================================================
    2716     # beginning PlotPatterns execution
     2722    #### beginning PlotPatterns execution
    27172723    global exclLines,Page
    27182724    global DifLine # BHT: probably does not need to be global
     
    28462852    # now start plotting
    28472853    G2frame.G2plotNB.status.DestroyChildren() #get rid of special stuff on status bar
     2854    # TODO: figure out why the SetHelpButton creates a second tab line (BHT, Mac, wx4.1)
     2855    #G2frame.G2plotNB.SetHelpButton(G2frame.dataWindow.helpKey)
    28482856    Page.tickDict = {}
    28492857    DifLine = ['']
     
    44654473        ax0.legend(legLine,legLbl,loc='best',prop={'size':plotOpt['labelSize']})
    44664474   
    4467 ################################################################################
    4468 ##### PlotDeltSig
    4469 ################################################################################
    4470            
     4475##### PlotDeltSig #############################################################
    44714476def PlotDeltSig(G2frame,kind,PatternName=None):
    44724477    'Produces normal probability plot for a powder or single crystal histogram'
     
    45244529    Page.canvas.draw()
    45254530       
    4526 ################################################################################
    4527 ##### PlotISFG
    4528 ################################################################################
    4529            
     4531##### PlotISFG ################################################################
    45304532def PlotISFG(G2frame,data,newPlot=False,plotType='',peaks=None):
    45314533    ''' Plotting package for PDF analysis; displays I(Q), S(Q), F(Q) and G(r) as single
     
    47134715        wx.CallAfter(PlotISFG,G2frame,data,peaks=Peaks,newPlot=False)
    47144716
    4715     # PlotISFG continues here
    4716     ############################################################
     4717    ##### PlotISFG continues here ############################################################
    47174718    xylim = []
    47184719    new,plotNum,Page,Plot,lim = G2frame.G2plotNB.FindPlotTab(plotType,'mpl')
     
    49294930        Page.canvas.draw()
    49304931
    4931 ################################################################################
    4932 ##### PlotCalib
    4933 ################################################################################
    4934            
     4932##### PlotCalib ###############################################################
    49354933def PlotCalib(G2frame,Inst,XY,Sigs,newPlot=False):
    49364934    '''plot of CW or TOF peak calibration
     
    50175015        Page.canvas.draw()
    50185016
    5019 ################################################################################
    5020 ##### PlotXY
    5021 ################################################################################
    5022            
     5017##### PlotXY ##################################################################
    50235018def PlotXY(G2frame,XY,XY2=[],labelX='X',labelY='Y',newPlot=False,
    50245019    Title='',lines=False,names=[],names2=[],vertLines=[]):
     
    51435138   
    51445139       
    5145 ################################################################################
    5146 ##### PlotXYZ
    5147 ################################################################################
    5148            
     5140##### PlotXYZ ################################################################################
    51495141def PlotXYZ(G2frame,XY,Z,labelX='X',labelY='Y',newPlot=False,Title='',zrange=None,color=None,buttonHandler=None):
    51505142    '''simple contour plot of xyz data
     
    52715263        Page.canvas.draw()
    52725264       
    5273 ################################################################################
    5274 ##### PlotXYZvect
    5275 ################################################################################
    5276        
     5265##### PlotXYZvect ################################################################################
    52775266def PlotXYZvect(G2frame,X,Y,Z,R,labelX=r'X',labelY=r'Y',labelZ=r'Z',Title='',PlotName=None):
    52785267    ''' To plot a quiver of quaternion vectors colored by the rotation
     
    53205309    Page.canvas.draw()
    53215310       
    5322 ################################################################################
    5323 ##### Plot3dXYZ
    5324 ################################################################################
    5325        
     5311##### Plot3dXYZ ################################################################################
    53265312def Plot3dXYZ(G2frame,nX,nY,Zdat,labelX=r'X',labelY=r'Y',labelZ=r'Z',newPlot=False,Title='',Centro=False):
    53275313   
     
    53765362        Page.canvas.draw()
    53775363       
    5378 ################################################################################
    5379 ##### PlotAAProb
    5380 ################################################################################
     5364##### PlotAAProb ################################################################################
    53815365def PlotAAProb(G2frame,resNames,Probs1,Probs2,Title='',thresh=None,pickHandler=None):
    53825366    'Needs a description'
     
    54385422    Draw()
    54395423
    5440 ################################################################################
    5441 ##### PlotStrain
    5442 ################################################################################
    5443            
     5424##### PlotStrain ################################################################################
    54445425def PlotStrain(G2frame,data,newPlot=False):
    54455426    '''plot of strain data, used for diagnostic purposes
     
    54885469        Page.canvas.draw()
    54895470       
    5490 ################################################################################
    5491 ##### PlotBarGraph
    5492 ################################################################################
    5493            
     5471##### PlotBarGraph ################################################################################
    54945472def PlotBarGraph(G2frame,Xarray,Xname='',Yname='Number',Title='',PlotName=None,ifBinned=False,maxBins=None):
    54955473    'Needs a description'
     
    55345512    Page.canvas.draw()
    55355513
    5536 ################################################################################
    5537 ##### PlotSASDSizeDist
    5538 ################################################################################
    5539            
     5514##### PlotSASDSizeDist ################################################################################
    55405515def PlotSASDSizeDist(G2frame):
    55415516    'Needs a description'
     
    55865561    Page.canvas.draw()
    55875562
    5588 ################################################################################
    5589 ##### PlotSASDPairDist
    5590 ################################################################################
    5591            
     5563##### PlotSASDPairDist ################################################################################
    55925564def PlotSASDPairDist(G2frame):
    55935565    'Needs a description'
     
    56305602        Page.canvas.draw()
    56315603
    5632 ################################################################################
    5633 ##### PlotPowderLines
    5634 ################################################################################
    5635            
     5604##### PlotPowderLines ################################################################################
    56365605def PlotPowderLines(G2frame):
    56375606    ''' plotting of powder lines (i.e. no powder pattern) as sticks
     
    56755644    Page.toolbar.push_current()
    56765645
    5677 ################################################################################
    5678 ##### PlotPeakWidths
    5679 ################################################################################
    5680            
     5646##### PlotPeakWidths           
    56815647def PlotPeakWidths(G2frame,PatternName=None):
    56825648    ''' Plotting of instrument broadening terms as function of 2-theta
     
    57635729        Page.canvas.mpl_connect('motion_notify_event', OnMotion)
    57645730        Page.canvas.mpl_connect('key_press_event', OnKeyPress)
     5731    G2frame.G2plotNB.SetHelpButton(G2frame.dataWindow.helpKey)       
    57655732    # save information needed to reload from tree and redraw
    57665733    G2frame.G2plotNB.RegisterRedrawRoutine(G2frame.G2plotNB.lastRaisedPlotTab,
     
    58955862        Page.canvas.draw()
    58965863   
    5897 ################################################################################
    5898 ##### PlotSizeStrainPO
    5899 ################################################################################
    5900            
     5864##### PlotSizeStrainPO ################################################################################
    59015865def PlotSizeStrainPO(G2frame,data,hist='',Start=False):
    59025866    '''Plot 3D mustrain/size/preferred orientation figure. In this instance data is for a phase
     
    61786142    Page.canvas.draw()
    61796143   
    6180 ################################################################################
    6181 ##### PlotTexture
    6182 ################################################################################
    6183 
     6144##### PlotTexture ################################################################################
    61846145def PlotTexture(G2frame,data,Start=False):
    61856146    '''Pole figure, inverse pole figure plotting.
     
    62586219    Page.Choice = None
    62596220    G2frame.G2plotNB.status.SetStatusText('')   
    6260     G2frame.G2plotNB.status.SetStatusWidths([150,-1])
     6221    G2frame.G2plotNB.status.SetStatusWidths([G2frame.G2plotNB.status.firstLen,-1])
    62616222    PH = np.array(SHData['PFhkl'])
    62626223    phi,beta = G2lat.CrsAng(PH,cell,SGData)
     
    63726333    Page.canvas.draw()
    63736334
    6374 ################################################################################
    6375 ##### Plot Modulation
    6376 ################################################################################
    6377 
     6335##### Plot Modulation ################################################################################
    63786336def ModulationPlot(G2frame,data,atom,ax,off=0):
    63796337    'Needs a description'
     
    64886446    Page.canvas.draw()
    64896447   
    6490 ################################################################################
    6491 ##### PlotCovariance
    6492 ################################################################################
    6493            
     6448##### PlotCovariance ################################################################################
    64946449def PlotCovariance(G2frame,Data):
    64956450    '''Plots the covariance matrix. Also shows values for parameters
     
    65796534    G2frame.G2plotNB.status.SetStatusText('',0)
    65806535    G2frame.G2plotNB.status.SetStatusText('',1)
    6581     G2frame.G2plotNB.status.SetStatusWidths([150,-1])   #need to reset field widths here   
     6536    G2frame.G2plotNB.status.SetStatusWidths([G2frame.G2plotNB.status.firstLen,-1])
    65826537    acolor = mpl.cm.get_cmap(G2frame.VcovColor)
    65836538    Img = Plot.imshow(Page.covArray,aspect='equal',cmap=acolor,interpolation='nearest',origin='lower',
     
    65936548    Page.canvas.draw()
    65946549   
    6595 ################################################################################
    6596 ##### PlotTorsion
    6597 ################################################################################
    6598 
     6550##### PlotTorsion ################################################################################
    65996551def PlotTorsion(G2frame,phaseName,Torsion,TorName,Names=[],Angles=[],Coeff=[]):
    66006552    'needs a doc string'
     
    66556607    Page.canvas.draw()
    66566608   
    6657 ################################################################################
    6658 ##### PlotRama
    6659 ################################################################################
    6660 
     6609##### PlotRama ################################################################################
    66616610def PlotRama(G2frame,phaseName,Rama,RamaName,Names=[],PhiPsi=[],Coeff=[]):
    66626611    'needs a doc string'
     
    67516700
    67526701
    6753 ################################################################################
    6754 ##### PlotSeq
    6755 ################################################################################
     6702##### PlotSeq ################################################################################
    67566703def PlotSelectedSequence(G2frame,ColumnList,TableGet,SelectX,fitnum=None,fitvals=None):
    67576704    '''Plot a result from a sequential refinement
     
    68866833    Draw()
    68876834               
    6888 ################################################################################
    6889 ##### PlotExposedImage & PlotImage
    6890 ################################################################################
    6891            
     6835##### PlotExposedImage & PlotImage ################################################################################
    68926836def PlotExposedImage(G2frame,newPlot=False,event=None):
    68936837    '''General access module for 2D image plotting
     
    80517995        wx.EndBusyCursor()
    80527996   
    8053 ################################################################################
    8054 ##### PlotIntegration
    8055 ################################################################################
    8056            
     7997##### PlotIntegration ################################################################################
    80577998def PlotIntegration(G2frame,newPlot=False,event=None):
    80587999    '''Plot of 2D image after image integration with 2-theta and azimuth as coordinates
     
    81068047        Page.canvas.draw()
    81078048               
    8108 ################################################################################
    8109 ##### PlotTRImage
    8110 ################################################################################
    8111            
     8049##### PlotTRImage ################################################################################
    81128050def PlotTRImage(G2frame,tax,tay,taz,newPlot=False):
    81138051    '''a test plot routine - not normally used
     
    81738111        Page.canvas.draw()
    81748112       
    8175 ################################################################################
    8176 ##### PlotStructure
    8177 ################################################################################
    8178            
     8113##### PlotStructure ################################################################################
    81798114def PlotStructure(G2frame,data,firstCall=False,pageCallback=None):
    81808115    '''Crystal structure plotting package. Can show structures as balls, sticks, lines,
     
    97639698    Font = Page.GetFont()
    97649699    Page.Choice = None
    9765     choice = [' save as/key:','jpeg','tiff','bmp','c: center on 1/2,1/2,1/2']
     9700    choice = [' save as/key:','jpeg','tiff','bmp','c: center on .5,.5.,5.']
    97669701    if mapData['MapType']:
    9767         choice += ['k: contour plot switch','s: map slice colors',]
     9702        choice += ['k: contour plot','s: map slice colors',]
    97689703    if mapData.get('Flip',False):
    97699704        choice += ['u: roll up','d: roll down','l: roll left','r: roll right']
     
    97799714    G2frame.G2plotNB.status.SetStatusText('View point: %.4f, %.4f, %.4f; density: %.4f'%(Tx,Ty,Tz,rho),1)
    97809715
    9781     cb = wx.ComboBox(G2frame.G2plotNB.status,style=wx.CB_DROPDOWN|wx.CB_READONLY,choices=choice)
     9716    cb = wx.ComboBox(G2frame.G2plotNB.status,style=wx.CB_DROPDOWN|wx.CB_READONLY,choices=choice,
     9717                         size=(G2frame.G2plotNB.status.firstLen,-1))
    97829718    cb.Bind(wx.EVT_COMBOBOX, OnKeyBox)
    97839719    cb.SetValue(' save as/key:')
     9720    G2frame.G2plotNB.SetHelpButton(G2frame.dataWindow.helpKey)
    97849721    Page.canvas.Bind(wx.EVT_LEFT_DOWN, OnMouseDown)
    97859722    Page.canvas.Bind(wx.EVT_RIGHT_DOWN, OnMouseDown)
     
    98039740    return Draw,['main']
    98049741
    9805 ################################################################################
    9806 #### Plot Bead Model
    9807 ################################################################################
    9808 
     9742#### Plot Bead Model ###############################################################################
    98099743def PlotBeadModel(G2frame,Atoms,defaults,PDBtext):
    98109744    '''Bead modelplotting package. For bead models from SHAPES
     
    100099943    Page.Choice = None
    100109944    choice = [' save as:','jpeg','tiff','bmp','pdb',]
    10011     cb = wx.ComboBox(G2frame.G2plotNB.status,style=wx.CB_DROPDOWN|wx.CB_READONLY,choices=choice)
     9945    cb = wx.ComboBox(G2frame.G2plotNB.status,style=wx.CB_DROPDOWN|wx.CB_READONLY,choices=choice,
     9946                         size=(G2frame.G2plotNB.status.firstLen,-1))
    100129947    cb.Bind(wx.EVT_COMBOBOX, OnKeyBox)
    100139948    cb.SetValue(' save as/key:')
     
    100299964    Draw('main')    #to fill both buffers so save works
    100309965
    10031 ################################################################################
    10032 #### Plot Rigid Body
    10033 ################################################################################
    10034 
     9966#### Plot Rigid Body ################################################################################
    100359967def PlotRigidBody(G2frame,rbType,AtInfo,rbData,defaults):
    100369968    '''RB plotting package. Can show rigid body structures as balls & sticks
     
    1033810270    Page.Choice = None
    1033910271    choice = [' save as:','jpeg','tiff','bmp',]
    10340     cb = wx.ComboBox(G2frame.G2plotNB.status,style=wx.CB_DROPDOWN|wx.CB_READONLY,choices=choice)
     10272    cb = wx.ComboBox(G2frame.G2plotNB.status,style=wx.CB_DROPDOWN|wx.CB_READONLY,choices=choice,
     10273                         size=(G2frame.G2plotNB.status.firstLen,-1))
    1034110274    cb.Bind(wx.EVT_COMBOBOX, OnKeyBox)
    1034210275    cb.SetValue(' save as/key:')
     
    1035910292    Draw('main')    #to fill both buffers so save works
    1036010293    if rbType == 'Vector': return UpdateDraw
    10361 ################################################################################
    10362 #### Plot Layers
    10363 ################################################################################
    10364 
     10294#### Plot Layers ################################################################################
    1036510295def PlotLayers(G2frame,Layers,laySeq,defaults):
    1036610296    '''Layer plotting package. Can show layer structures as balls & sticks
     
    1079810728    Page.keyPress = OnPlotKeyPress
    1079910729    Font = Page.GetFont()
    10800     cb = wx.ComboBox(G2frame.G2plotNB.status,style=wx.CB_DROPDOWN|wx.CB_READONLY,choices=choice)
     10730    cb = wx.ComboBox(G2frame.G2plotNB.status,style=wx.CB_DROPDOWN|wx.CB_READONLY,choices=choice,
     10731                         size=(G2frame.G2plotNB.status.firstLen,-1))
    1080110732    cb.Bind(wx.EVT_COMBOBOX, OnKeyBox)
    1080210733    text = [str(Layers['Layers'][seq]['Name']) for seq in laySeq]
  • trunk/docs/source/GSASIIGUI.rst

    r3571 r4833  
    55    :members:
    66
     7.. automodule:: GSASIIseqGUI
     8    :members:
     9       
    710.. automodule:: GSASIIphsGUI
    811    :members:
  • trunk/help/gsasII.html

    r4784 r4833  
    43084308style='mso-fareast-font-family:"Times New Roman";color:windowtext;font-weight:
    43094309normal;mso-bidi-font-weight:bold'>Menu ‘</span><span style='mso-fareast-font-family:
    4310 "Times New Roman";color:windowtext'>File’ – </span><span style='mso-fareast-font-family:
     4310"Times New Roman";color:windowtext'>Background’ – </span><span style='mso-fareast-font-family:
    43114311"Times New Roman";color:windowtext;font-weight:normal;mso-bidi-font-weight:
    43124312bold'><o:p></o:p></span></h5>
     
    45504550What is plotted here?</span></h5>
    45514551<P style='margin-left:1.0in'>
    4552 The plot is the same as for <a href="#PWD">Powder Histograms -
     4552The plot is the same as for <a href="#PWDR">Powder Histograms -
    45534553type PWDR</a> and the key press commands are all the same. However,
    45544554two vertical lines are displayed, green for the lower Tmin value and
    4555 red for the upper Tmin value.
     4555red for the upper Tmin value. These can be dragged to set limits.
    45564556</P>
    45574557
     
    46444644style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span></span><![endif]><span
    46454645style='mso-fareast-font-family:"Times New Roman"'>Menu ‘<b style='mso-bidi-font-weight:
    4646 normal'>File</b>’ – <o:p></o:p></span></p>
     4646normal'>Background</b>’ – <o:p></o:p></span></p>
    46474647
    46484648<p class=MsoListParagraphCxSpMiddle style='margin-left:1.5in;mso-add-space:
     
    47174717position. Select parameters to refine; usually start with the ‘<span
    47184718class=SpellE>int</span>’ coefficients.<o:p></o:p></span></p>
     4719
     4720<h5 style='margin-left:.5in'><span
     4721style='mso-fareast-font-family:"Times New Roman"'>
     4722What is plotted here?</span></h5>
     4723<P style='margin-left:1.0in'>
     4724The plot is the same as for <a href="#PWDR">Powder Histograms -
     4725type PWDR</a> and the key press commands are largerly the same.
     4726Specific to this plot are fixed background points. These can be added,
     4727deleted and moved. Once that is done the background
     4728parameters for the selected function can be fitted to the fixed
     4729points.
     4730</P>
    47194731
    47204732<h4 style='margin-left:0.25in'><a name="PWDR_Instrument_Parameters"><u><span
     
    70127024‘<b style='mso-bidi-font-weight:normal'>Edit’ - </b>The edit menu shows
    70137025operations that can be performed on your selected atoms. You must select one or
    7014 more atoms before using any of the menu items.</p>
     7026more atoms before using any of the menu items. Most of these items can
     7027also be accessed by selecting one or more atoms and right-clicking the
     7028mouse.</p>
    70157029
    70167030<p class=MsoListParagraphCxSpMiddle style='margin-left:1.5in;mso-add-space:
     
    71717185Holding down right button translates the fractional
    71727186coordinates assigned to the view point (which is kept at the center of
    7173 the plot). The structure will appear to translate.
     7187the plot). The structure will appear to translate.
     7188(On Mac control+mouse drag will also do this).
    71747189The view point can also be entered directly in the Draw Options.
    71757190</LI><LI style='margin-left:1.4in; text-indent:-.2in'>
     
    71787193perpendicular to screen).
    71797194</LI><LI style='margin-left:1.4in; text-indent:-.2in'>
    7180 <B>Wheel</B>: 
     7195<B>Mouse Wheel</B>: 
    71817196Rotating the scroll wheel: changes “camera position” (zoom in/out)
    71827197</LI><LI style='margin-left:1.4in; text-indent:-.2in'>
     
    71867201atoms will be reset. If two atoms are overlapped in the
    71877202current view, then the top-most atom will usually be selected.
     7203Atom selection requires that either the "Atoms" or "Draw Atoms" phase
     7204be displayed.
     7205
    71887206</LI><LI style='margin-left:1.4in; text-indent:-.2in'>
    71897207<B>Shift+Right click</B>:   
     
    71927210and unselected if previously selected. Any previously selected
    71937211atoms will be continue to be selected so shift-right click can be used
    7194 to add atoms to the selection list. If two atoms are overlapped in the
     7212to add atoms to the selection list.
     7213(On Mac control+mouse click will also do this).
     7214If two atoms are overlapped in the
    71957215current view, then the top-most atom will usually be selected.
     7216Atom selection requires that either the "Atoms" or "Draw Atoms" phase
     7217be displayed.
    71967218</LI></BL>
    71977219
     
    75437565<hr size=2 width="100%" align=center>
    75447566
    7545 <!-- hhmts start -->Last modified: Tue Jan 26 16:53:06 CST 2021 <!-- hhmts end -->
     7567<!-- hhmts start -->Last modified: Sun Feb 28 12:09:25 CST 2021 <!-- hhmts end -->
    75467568
    75477569</div>
Note: See TracChangeset for help on using the changeset viewer.