Changeset 4534


Ignore:
Timestamp:
Jul 27, 2020 10:42:49 PM (16 months ago)
Author:
toby
Message:

implement variable limits; show cell under Dij vals

Location:
trunk
Files:
7 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIctrlGUI.py

    r4532 r4534  
    38543854    '''Create frame to show least-squares parameters
    38553855    '''
    3856     def __init__(self,parent,title,parmDict,varyList,fullVaryList,
    3857                      parmMinDict={}, parmMaxDict={}, frozenList=[],
    3858                      size=(650,430)):
    3859        
    3860         wx.Dialog.__init__(self,parent,wx.ID_ANY,title,size=size,
     3856    def __init__(self,G2frame,title,parmDict,varyList,fullVaryList,
     3857                     Controls, size=(650,430)):
     3858       
     3859        wx.Dialog.__init__(self,G2frame,wx.ID_ANY,title,size=size,
    38613860                           style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
    38623861        self.parmChoice = 'Phase'
     3862        self.G2frame = G2frame
    38633863        self.parmDict = parmDict
    38643864        self.varyList = varyList
    38653865        self.fullVaryList = fullVaryList
    3866         self.parmMinDict = parmMinDict
    3867         self.parmMaxDict = parmMaxDict
    3868         self.frozenList = frozenList
     3866        self.Controls = Controls
    38693867        self.choiceDict = {}
    3870         # if GSASIIpath.GetConfigValue('debug'):
    3871         #     print('dummy settings for frozenList etc')
    3872         #     self.parmMinDict['0::Afrac:26'] = 0.0
    3873         #     self.frozenList = ['0::Afrac:26']       
    3874 
     3868
     3869        parmFrozen = Controls.get('parmFrozen',{})
     3870        if G2frame.testSeqRefineMode():
     3871            frozenList = set()
     3872            for h in parmFrozen:
     3873                if h == 'FrozenList': continue
     3874                frozenList = frozenList.union(parmFrozen[h])
     3875            self.frozenList = list(frozenList)
     3876        elif 'FrozenList' in parmFrozen:
     3877            self.frozenList = copy.copy(parmFrozen['FrozenList'])
     3878        else:
     3879            self.frozenList = []
    38753880        # make lists of variables of different types along with lists of parameter names, histogram #s, phase #s,...
    38763881        self.parmNames = sorted(list(parmDict.keys()))
     
    39073912        '''Shows the selected variables in a ListCtrl
    39083913        '''
    3909         start = time.time()
     3914        #start = time.time()
    39103915        self.varBox.SetContents(self)
    39113916        self.SendSizeEvent()
    3912         if GSASIIpath.GetConfigValue('debug'):
    3913             print('repaintScrollTbl',time.time()-start)
     3917        #if GSASIIpath.GetConfigValue('debug'):
     3918        #    print('repaintScrollTbl',time.time()-start)
    39143919                   
    39153920    def DrawPanel(self):
     
    39893994            num = len(self.fullVaryList) - len(self.varyList)
    39903995            parmSizer.Add(wx.StaticText(self,label=
    3991                 ' + {} parameters are varied via constraints'.format(
     3996                ' + {} varied via constraints'.format(
    39923997                    len(self.fullVaryList) - len(self.varyList))
    39933998                                        ))
     3999        parmFrozen = self.Controls.get('parmFrozen',{})
     4000        fcount = 0
     4001        if self.G2frame.testSeqRefineMode():
     4002            for h in parmFrozen:
     4003                if h == 'FrozenList': continue
     4004                fcount += len(parmFrozen[h])
     4005        elif 'FrozenList' in parmFrozen:
     4006            fcount = len(parmFrozen['FrozenList'])
     4007        if fcount:
     4008            parmSizer.Add(wx.StaticText(self,label=
     4009                ' - {} frozen variables'.format(fcount)))
    39944010        mainSizer.Add(parmSizer)
    39954011        choice = ['Phase','Phase/Histo','Histogram']
     
    40544070
    40554071        txt = ('"R" indicates a refined variable\n'+
    4056                     '"C" indicates generated from a constraint')
    4057         # if GSASIIpath.GetConfigValue('debug'):
    4058         #     txt += '\n"F" indicates a variable that is Frozen due to exceeding min/max'
     4072               '"C" indicates generated from a constraint\n'+
     4073               '"F" indicates a variable that is Frozen due to exceeding min/max')
    40594074        mainSizer.Add(
    40604075            wx.StaticText(self,label=txt),0, wx.ALL,0)
     
    40704085    def _onClose(self,event):
    40714086        self.EndModal(wx.ID_CANCEL)
    4072        
     4087
    40734088class VirtualVarBox(wx.ListCtrl):
    40744089    def __init__(self, parent):
     
    40794094            )
    40804095
    4081         # if GSASIIpath.GetConfigValue('debug'):
    4082         #     for i,(lbl,wid) in enumerate(zip(
    4083         #         ('#', "Parameter", "Ref?", "Value", "Min", "Max", "Explanation"),
    4084         #         (40 , 100        , 35    ,  100   ,  75  ,  75  , 700),)): 
    4085         #         self.InsertColumn(i, lbl)
    4086         #         self.SetColumnWidth(i, wid)
    4087         # else:
    4088         if True:
    4089             for i,(lbl,wid) in enumerate(zip(
    4090                 ('#', "Parameter", "Ref?", "Value", "", "", "Explanation"),
    4091                 (40 , 100        , 35    ,  100   ,  5  ,  5  , 700),)): 
    4092                 self.InsertColumn(i, lbl)
    4093                 self.SetColumnWidth(i, wid)
     4096        for i,(lbl,wid) in enumerate(zip(
     4097                ('#', "Parameter", "Ref", "Value", "Min", "Max", "Explanation"),
     4098                (40 , 125        , 30    ,  100   ,  75  ,  75  , 700),)): 
     4099            self.InsertColumn(i, lbl)
     4100            self.SetColumnWidth(i, wid)
    40944101
    40954102        self.SetItemCount(0)
     
    40984105        self.attr1.SetBackgroundColour((255,255,150))
    40994106
    4100         if GSASIIpath.GetConfigValue('debug'):
    4101             self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
    4102         #self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColSelected)
     4107        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnRowSelected)
    41034108
    41044109    def SetContents(self,parent):
     
    41224127        self.SetItemCount(len(self.varList))
    41234128       
    4124     def OnItemSelected(self, event):
    4125         print('OnItemSelected: "%s"\n' % (event.Index))
    4126     #def OnColSelected(self, event):
    4127     #    print('Column selected:',event.Column)
    4128     #    #G2p.IPyBreak_base()
     4129    def OnRowSelected(self, event, row=None):
     4130        'Creates an edit window when a parameter is selected'
     4131        def ResetFrozen(event):
     4132            '''release a frozen parameter (from all histograms in the case of a
     4133            sequential fit).
     4134            '''
     4135            if name in self.parmWin.frozenList:
     4136                del self.parmWin.frozenList[self.parmWin.frozenList.index(name)]
     4137            parmFrozen = self.parmWin.Controls.get('parmFrozen',{})
     4138            if self.parmWin.G2frame.testSeqRefineMode():
     4139                for h in parmFrozen:
     4140                    if h == 'FrozenList': continue
     4141                    if name in parmFrozen[h]:
     4142                        del parmFrozen[h][parmFrozen[h].index(name)]
     4143            elif 'FrozenList' in parmFrozen:
     4144                if name in parmFrozen['FrozenList']:
     4145                    del parmFrozen['FrozenList'][parmFrozen['FrozenList'].index(name)]
     4146            dlg.EndModal(wx.ID_CANCEL)
     4147            self.parmWin.SendSizeEvent()
     4148
     4149        def delM(event):
     4150            'Get event info & prepare to delete Max or Min limit'
     4151            if hasattr(event.EventObject,'max'):
     4152                d = self.parmWin.Controls['parmMaxDict']
     4153            else:
     4154                d = self.parmWin.Controls['parmMinDict']
     4155            # close sub-dialog then delete item and redraw
     4156            dlg.EndModal(wx.ID_OK)
     4157            wx.CallAfter(delMafter,d,name)
     4158        def delMafter(d,name):
     4159            'Delete Max or Min limit once dialog is deleted'
     4160            n,val = G2obj.prmLookup(name,d) # is this a wild-card?
     4161            if val is not None:
     4162                del d[n]
     4163            self.OnRowSelected(None, row)
     4164           
     4165        def AddM(event):
     4166            'Get event info & add a Max or Min limit'
     4167            if hasattr(event.EventObject,'max'):
     4168                d = self.parmWin.Controls['parmMaxDict']
     4169            else:
     4170                d = self.parmWin.Controls['parmMinDict']
     4171            # close sub-dialog then delete item and redraw
     4172            dlg.EndModal(wx.ID_OK)
     4173            wx.CallAfter(AddMafter,d,name)
     4174        def AddMafter(d,name):
     4175            'Add a Max or Min limit & redraw'
     4176            try:
     4177                d[name] = float(value)
     4178            except:
     4179                d[name] = 0.0
     4180            self.OnRowSelected(None, row)
     4181           
     4182        def SetWild(event):
     4183            'Get event info & prepare to set/clear item as wildcard'
     4184            if hasattr(event.EventObject,'max'):
     4185                d = self.parmWin.Controls['parmMaxDict']
     4186            else:
     4187                d = self.parmWin.Controls['parmMinDict']
     4188            ns = name.split(':')
     4189            if hasattr(event.EventObject,'hist'):
     4190                ns[1] = '*'
     4191            else:
     4192                ns[3] = '*'
     4193            wname = ':'.join(ns)           
     4194            # close sub-dialog then delete item and redraw
     4195            dlg.EndModal(wx.ID_OK)
     4196            wx.CallAfter(SetWildAfter,d,name,wname,event.EventObject.GetValue())
     4197        def SetWildAfter(d,name,wname,mode):
     4198            'Set/clear item as wildcard & delete old name(s), redraw'
     4199            n,val = G2obj.prmLookup(name,d) # is this a wild-card?
     4200            if mode: # make wildcard
     4201                if n == name: # confirm not wildcard already
     4202                    d[wname] = d[name]
     4203                for n in list(d.keys()): # delete names matching wildcard
     4204                    if n == wname: continue
     4205                    if G2obj.prmLookup(n,d)[0] == wname:
     4206                        del d[n]
     4207            else:
     4208                if n != name:
     4209                    d[name] = d[wname]               
     4210                    del d[wname]
     4211            self.OnRowSelected(None, row)
     4212
     4213        if event is not None:
     4214            row = event.Index
     4215        elif row is None:
     4216            print('Error: row and event should not be None!')
     4217            return
     4218        name = self.varList[row]
     4219        dlg = wx.Dialog(self,wx.ID_ANY,'Parameter {} info'.format(name),
     4220                            size=(600,-1),
     4221                        style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
     4222        mainSizer = wx.BoxSizer(wx.VERTICAL)
     4223        mainSizer.Add((5,5))
     4224        subSizer = wx.BoxSizer(wx.HORIZONTAL)
     4225        subSizer.Add((-1,-1),1,wx.EXPAND)
     4226        try:
     4227            value = G2py3.FormatSigFigs(self.parmWin.parmDict[name])
     4228        except TypeError:
     4229            value = str(self.parmWin.parmDict[name])+' -?' # unexpected
     4230        subSizer.Add(wx.StaticText(dlg,wx.ID_ANY,
     4231                        'Parameter "{}" information and settings. Value={}'
     4232                                       .format(name,value)))
     4233        subSizer.Add((-1,-1),1,wx.EXPAND)
     4234        mainSizer.Add(subSizer,0,wx.EXPAND,0)
     4235        mainSizer.Add((0,10))
     4236        v = G2obj.getVarDescr(name)
     4237        if v is not None and v[-1] is not None:
     4238            txt = G2obj.fmtVarDescr(name)
     4239            if txt:
     4240                txt.replace('Ph=','Phase: ')
     4241                txt.replace('Pwd=','Histogram: ')
     4242                txtwid = wx.StaticText(dlg,wx.ID_ANY,'Parameter meaning is "'+txt+'"')
     4243                txtwid.Wrap(580)
     4244                mainSizer.Add(txtwid)
     4245                mainSizer.Add((0,10))
     4246
     4247        freezebtn = None
     4248        if name in self.parmWin.fullVaryList and name in self.parmWin.frozenList:
     4249            msg = "Parameter {} exceeded limits and has been frozen".format(name)
     4250            freezebtn = wx.Button(dlg, wx.ID_ANY,'Unfreeze')
     4251            freezebtn.Bind(wx.EVT_BUTTON, ResetFrozen)
     4252        elif name in self.parmWin.varyList:
     4253            msg = "Parameter {} is refined".format(name)
     4254        elif name in self.parmWin.fullVaryList:
     4255            msg = "Parameter {} is refined via a constraint".format(name)
     4256        else:
     4257            msg = ""
     4258        if msg:
     4259            subSizer = wx.BoxSizer(wx.HORIZONTAL)
     4260            subSizer.Add(wx.StaticText(dlg,wx.ID_ANY,msg),0,wx.CENTER)
     4261        if freezebtn:
     4262            subSizer.Add(freezebtn,0,wx.ALL|wx.CENTER,5)
     4263        mainSizer.Add(subSizer,0)
     4264
     4265        # draw min value widgets
     4266        mainSizer.Add((-1,10),0)
     4267        n,val = G2obj.prmLookup(name,self.parmWin.Controls['parmMinDict']) # is this a wild-card?
     4268        if val is None:
     4269            addMbtn = wx.Button(dlg, wx.ID_ANY,'Add Lower limit')
     4270            addMbtn.Bind(wx.EVT_BUTTON, AddM)
     4271            mainSizer.Add(addMbtn,0)
     4272        else:
     4273            subSizer = wx.BoxSizer(wx.HORIZONTAL)
     4274            subSizer.Add(wx.StaticText(dlg,wx.ID_ANY,'Minimum limit'),0,wx.CENTER)
     4275            subSizer.Add(ValidatedTxtCtrl(dlg,self.parmWin.Controls['parmMinDict'],n,nDig=(10,2,'g')),0,WACV)
     4276            delMbtn = wx.Button(dlg, wx.ID_ANY,'Delete',style=wx.BU_EXACTFIT)
     4277            subSizer.Add((5,-1),0,WACV)
     4278            subSizer.Add(delMbtn,0,WACV)
     4279            delMbtn.Bind(wx.EVT_BUTTON, delM)
     4280            if name.split(':')[1]:             # is this using a histogram?
     4281                subSizer.Add((5,-1),0,WACV)
     4282                wild = wx.CheckBox(dlg,wx.ID_ANY,label='Match all histograms ')
     4283                wild.SetValue(n.split(':')[1] == '*')
     4284                wild.Bind(wx.EVT_CHECKBOX,SetWild)
     4285                wild.hist = True
     4286                subSizer.Add(wild,0,WACV)
     4287            elif len(name.split(':')) > 3:
     4288                subSizer.Add((5,-1),0,WACV)
     4289                wild = wx.CheckBox(dlg,wx.ID_ANY,label='Match all atoms ')
     4290                wild.SetValue(n.split(':')[3] == '*')
     4291                wild.Bind(wx.EVT_CHECKBOX,SetWild)
     4292                subSizer.Add(wild,0,WACV)
     4293            mainSizer.Add(subSizer,0)
     4294
     4295        # draw max value widgets
     4296        mainSizer.Add((-1,10),0)
     4297        n,val = G2obj.prmLookup(name,self.parmWin.Controls['parmMaxDict']) # is this a wild-card?
     4298        if val is None:
     4299            addMbtn = wx.Button(dlg, wx.ID_ANY,'Add Upper limit')
     4300            addMbtn.Bind(wx.EVT_BUTTON, AddM)
     4301            addMbtn.max = True
     4302            mainSizer.Add(addMbtn,0)
     4303        else:
     4304            subSizer = wx.BoxSizer(wx.HORIZONTAL)
     4305            subSizer.Add(wx.StaticText(dlg,wx.ID_ANY,'Maximum limit'),0,wx.CENTER)
     4306            subSizer.Add(ValidatedTxtCtrl(dlg,self.parmWin.Controls['parmMaxDict'],n,nDig=(10,2,'g')),0,WACV)
     4307            delMbtn = wx.Button(dlg, wx.ID_ANY,'Delete',style=wx.BU_EXACTFIT)
     4308            subSizer.Add((5,-1),0,WACV)
     4309            subSizer.Add(delMbtn,0,WACV)
     4310            delMbtn.Bind(wx.EVT_BUTTON, delM)
     4311            delMbtn.max = True
     4312            if name.split(':')[1]:             # is this using a histogram?
     4313                subSizer.Add((5,-1),0,WACV)
     4314                wild = wx.CheckBox(dlg,wx.ID_ANY,label='Match all histograms ')
     4315                wild.SetValue(n.split(':')[1] == '*')
     4316                wild.Bind(wx.EVT_CHECKBOX,SetWild)
     4317                wild.max = True
     4318                wild.hist = True
     4319                subSizer.Add(wild,0,WACV)
     4320            elif len(name.split(':')) > 3:
     4321                subSizer.Add((5,-1),0,WACV)
     4322                wild = wx.CheckBox(dlg,wx.ID_ANY,label='Match all atoms ')
     4323                wild.SetValue(n.split(':')[3] == '*')
     4324                wild.Bind(wx.EVT_CHECKBOX,SetWild)
     4325                wild.max = True
     4326                subSizer.Add(wild,0,WACV)
     4327            mainSizer.Add(subSizer,0)
     4328           
     4329        btnsizer = wx.StdDialogButtonSizer()
     4330        OKbtn = wx.Button(dlg, wx.ID_OK)
     4331        OKbtn.SetDefault()
     4332        OKbtn.Bind(wx.EVT_BUTTON,lambda event: dlg.EndModal(wx.ID_OK))
     4333        btnsizer.AddButton(OKbtn)
     4334        btnsizer.Realize()
     4335        mainSizer.Add((-1,5),1,wx.EXPAND,1)
     4336        mainSizer.Add(btnsizer,0,wx.ALIGN_CENTER,0)
     4337        mainSizer.Add((-1,10))
     4338
     4339        dlg.SetSizer(mainSizer)
     4340        dlg.CenterOnParent()
     4341        if dlg.ShowModal() != wx.ID_OK: # if not OK, destroy & reopen
     4342            dlg.Destroy()
     4343            wx.CallAfter(self.OnRowSelected, None, row)
     4344            return
     4345        dlg.Destroy()
     4346        self.parmWin.SendSizeEvent()
     4347       
    41294348    #-----------------------------------------------------------------
    4130     # Callbacks to set info in table
     4349    # Callbacks to display info in table
    41314350    def OnGetItemText(self, item, col):
    41324351        name = self.varList[item]
     
    41364355            return name
    41374356        elif col == 2:
    4138             if name in self.parmWin.varyList:
    4139                 if name in self.parmWin.frozenList:
     4357            if name in self.parmWin.fullVaryList and name in self.parmWin.frozenList:
    41404358                    return "F"
     4359            elif name in self.parmWin.varyList:
    41414360                return "R"
    41424361            elif name in self.parmWin.fullVaryList:
     
    41494368                value = str(self.parmWin.parmDict[name])+' -?' # unexpected
    41504369            return value
    4151                 #continue
    4152         elif col == 4:
    4153             if name in self.parmWin.parmMinDict:
    4154                 return G2py3.FormatSigFigs(self.parmWin.parmMinDict[name],8)
    4155             return "" # min value
    4156         elif col == 5:
    4157             if name in self.parmWin.parmMaxDict:
    4158                 return G2py3.FormatSigFigs(self.parmWin.parmMaxDict[name],8)
    4159             return "" # max value
     4370        elif col == 4 or col == 5: # min/max value
     4371            if col == 4: # min
     4372                d = self.parmWin.Controls['parmMinDict']
     4373            else:
     4374                d = self.parmWin.Controls['parmMaxDict']
     4375            n,val = G2obj.prmLookup(name,d)
     4376            if val is None: return ""
     4377            try:
     4378                return G2py3.FormatSigFigs(val,8)
     4379            except TypeError:
     4380                return "?"
    41604381        elif col == 6:
    41614382            v = G2obj.getVarDescr(name)
  • trunk/GSASIIdataGUI.py

    r4532 r4534  
    49664966        except G2mv.ConstraintException:
    49674967            pass
     4968        Controls = self.GPXtree.GetItemPyData(GetGPXtreeItemId(self,self.root, 'Controls'))
     4969        for key in ('parmMinDict','parmMaxDict','parmFrozen'):
     4970            if key not in Controls: Controls[key] = {}
    49684971        wx.EndBusyCursor()
    49694972        # debug stuff
    4970         if GSASIIpath.GetConfigValue('debug'):
    4971             print('reloading',G2G)
    4972             import imp
    4973             imp.reload(G2G)
     4973        #if GSASIIpath.GetConfigValue('debug'):
     4974        #    print('reloading',G2G)
     4975        #    import imp
     4976        #    imp.reload(G2G)
    49744977        # end debug stuff           
    49754978        dlg = G2G.ShowLSParms(self,'Least Squares Parameters',parmValDict,
    4976                                   varyList,reqVaryList)
     4979                    varyList,reqVaryList,Controls)
    49774980        dlg.ShowModal()
    49784981        dlg.Destroy()
     
    64676470       
    64686471    def AuthSizer():
    6469 
    64706472        def OnAuthor(event):
    64716473            event.Skip()
     
    64806482        authSizer.Add(auth,0,WACV)
    64816483        return authSizer
     6484
     6485    def ClearFrozen(event):
     6486        Controls['parmFrozen'] = {}
     6487        wx.CallAfter(UpdateControls,G2frame,data)
    64826488       
    64836489    if 'SVD' in data['deriv type']:
     
    64896495    mainSizer = wx.BoxSizer(wx.VERTICAL)
    64906496    mainSizer.Add((5,5),0)
    6491     mainSizer.Add(wx.StaticText(G2frame.dataWindow,label=' Refinement Controls:'),0,WACV)   
     6497    subSizer = wx.BoxSizer(wx.HORIZONTAL)
     6498    subSizer.Add((-1,-1),1,wx.EXPAND)
     6499    subSizer.Add(wx.StaticText(G2frame.dataWindow,label='Refinement Controls'),0,WACV)   
     6500    subSizer.Add((-1,-1),1,wx.EXPAND)
     6501    mainSizer.Add(subSizer,0,wx.EXPAND)
     6502    mainSizer.Add((5,5),0)
    64926503    mainSizer.Add(LSSizer())
    64936504    mainSizer.Add((5,5),0)
     
    64966507    mainSizer.Add(AuthSizer())
    64976508    mainSizer.Add((5,5),0)
     6509    Controls = data
     6510    if 'parmFrozen' not in Controls:
     6511        Controls['parmFrozen'] = {}
     6512    parmFrozen = Controls['parmFrozen']
     6513    if G2frame.testSeqRefineMode():
     6514        frozenList = set()
     6515        for h in parmFrozen:
     6516            if h == 'FrozenList': continue
     6517            frozenList = frozenList.union(parmFrozen[h])
     6518        count = len(frozenList)
     6519    elif 'FrozenList' in parmFrozen:
     6520        count = len(parmFrozen['FrozenList'])
     6521    else:
     6522        count = 0
     6523    if count > 0:
     6524        subSizer = wx.BoxSizer(wx.HORIZONTAL)
     6525        subSizer.Add(wx.StaticText(G2frame.dataWindow,
     6526                    label='There are {} frozen variables (values refined outside limits)'
     6527                                .format(count)),0,WACV)
     6528        subSizer.Add((5,-1))
     6529        btn = wx.Button(G2frame.dataWindow, wx.ID_ANY,'Clear All Frozen')
     6530        btn.Bind(wx.EVT_BUTTON,ClearFrozen)
     6531        subSizer.Add(btn)
     6532        mainSizer.Add(subSizer)
    64986533       
    64996534    mainSizer.Layout()
     
    65016536    G2frame.dataWindow.SetSizer(mainSizer)
    65026537    G2frame.dataWindow.SetDataSize()
     6538    G2frame.SendSizeEvent()
    65036539     
    65046540################################################################################
     
    72937329        '''
    72947330        if G2frame.colSigs[col]:
     7331            if G2frame.colSigs[col][row] == -0.1: return 'frozen'
    72957332            return u'\u03c3 = '+str(G2frame.colSigs[col][row])
    72967333        return ''
  • trunk/GSASIIddataGUI.py

    r4523 r4534  
    1919from __future__ import division, print_function
    2020import wx
     21import numpy as np
     22import numpy.linalg as nl
    2123import GSASIIpath
    2224GSASIIpath.SetVersionNumber("$Revision$")
     
    2729import GSASIIphsGUI as G2phsGUI
    2830import GSASIIctrlGUI as G2G
    29 import numpy as np
    30 import numpy.linalg as nl
     31import GSASIIpy3 as G2py3
    3132
    3233WACV = wx.ALIGN_CENTER_VERTICAL
     
    392393            UseList[G2frame.hist]['HStrain'][1][pid] = Obj.GetValue()
    393394           
     395        hSizer = wx.BoxSizer(wx.VERTICAL)
    394396        hstrainSizer = wx.FlexGridSizer(0,6,5,5)
    395397        Hsnames = G2spc.HStrainNames(SGData)
    396398        parms = zip(Hsnames,UseList[G2frame.hist]['HStrain'][1],range(len(Hsnames)))
     399        allzero = True
    397400        for Pa,ref,Id in parms:
    398401            hstrainRef = wx.CheckBox(DData,wx.ID_ANY,label=Pa)
     
    402405            hstrainRef.Bind(wx.EVT_CHECKBOX, OnHstrainRef)
    403406            hstrainSizer.Add(hstrainRef,0,WACV|wx.LEFT,5)
    404             hstrainVal = G2G.ValidatedTxtCtrl(DData,UseList[G2frame.hist]['HStrain'][0],Id,nDig=(10,3,'g'))
     407            hstrainVal = G2G.ValidatedTxtCtrl(DData,
     408                        UseList[G2frame.hist]['HStrain'][0],Id,nDig=(10,3,'g'),
     409                        OnLeave=OnNewValueReDraw)
     410            if abs(UseList[G2frame.hist]['HStrain'][0][Id]) > 1e-8:
     411                allzero = False
    405412            hstrainSizer.Add(hstrainVal,0,WACV)
    406         return hstrainSizer
     413        hSizer.Add(hstrainSizer,0,WACV)
     414        if not allzero:   # show Dij shifted unit cell
     415            DijVals = UseList[G2frame.hist]['HStrain'][0][:]
     416            # apply the Dij values to the reciprocal cell
     417            newA = []
     418            Dijdict = dict(zip(G2spc.HStrainNames(SGData),DijVals))
     419            for Aij,lbl in zip(G2lat.cell2A(data['General']['Cell'][1:7]),
     420                            ['D11','D22','D33','D12','D13','D23']):
     421                newA.append(Aij + Dijdict.get(lbl,0.0))
     422            cell = G2lat.A2cell(newA)   # convert back to direct cell
     423            laue = generalData['SGData']['SGLaue']
     424            if laue == '2/m':
     425                laue += generalData['SGData']['SGUniq']
     426            for cellGUI in G2py3.cellGUIlist:
     427                if laue in cellGUI[0]:
     428                    useGUI = cellGUI
     429                    break
     430            else:
     431                return hSizer
     432            cellstr = ''
     433            for txt,fmt,ifEdit,Id in zip(*useGUI[2:]):
     434                if cellstr: cellstr += ", "
     435                cellstr += txt+fmt.format(cell[Id])
     436            cellstr += ', Vol = {:.3f}'.format(G2lat.calc_V(newA))
     437            hSizer.Add(wx.StaticText(DData,wx.ID_ANY,'     '+cellstr),0,WACV)
     438        return hSizer
    407439       
    408440    def PoTopSizer(POData):
     
    967999
    9681000    ######################################################################
    969     # Beginning of UpdateDData execution here
     1001    ### Beginning of UpdateDData execution here
    9701002    ######################################################################
    9711003    G2frame.SetStatusText('',1)
  • trunk/GSASIIobj.py

    r4521 r4534  
    19281928    return sorted([var for var in varlist if rexp.match(var)])
    19291929
     1930def prmLookup(name,prmDict):
     1931    '''looks for a parameter in a min/max dictionary, optionally
     1932    considering a wild card for histogram & atom number
     1933    '''
     1934    sn = name.split(':')
     1935    if sn[1] != '': sn[1] = '*'
     1936    if len(sn) >= 4 and sn[3] != '': sn[3] = '*'
     1937    wname = ':'.join(sn)
     1938    if wname in prmDict:
     1939        return wname,prmDict[wname]
     1940    elif name in prmDict:
     1941        return name,prmDict[name]
     1942    else:
     1943        return None,None
     1944       
    19301945
    19311946def _lookup(dic,key):
  • trunk/GSASIIpy3.py

    r3825 r4534  
    1717sqrt = sq = lambda x: np.sqrt(x)
    1818pi = np.pi
     19
     20# formatting for unique cell parameters by Laue type
     21cellGUIlist = [[['m3','m3m'],4,[" Unit cell: a = "],["{:.5f}"],[True],[0]],
     22[['3R','3mR'],6,[" a = ",u" \u03B1 = "],["{:.5f}","{:.3f}"],[True,True],[0,3]],
     23[['3','3m1','31m','6/m','6/mmm','4/m','4/mmm'],6,[" a = "," c = "],["{:.5f}","{:.5f}"],[True,True],[0,2]],
     24[['mmm'],8,[" a = "," b = "," c = "],["{:.5f}","{:.5f}","{:.5f}"],
     25    [True,True,True],[0,1,2]],
     26[['2/m'+'a'],10,[" a = "," b = "," c = ",u" \u03B1 = "],
     27    ["{:.5f}","{:.5f}","{:.5f}","{:.3f}"],[True,True,True,True,],[0,1,2,3]],
     28[['2/m'+'b'],10,[" a = "," b = "," c = ",u" \u03B2 = "],
     29    ["{:.5f}","{:.5f}","{:.5f}","{:.3f}"],[True,True,True,True,],[0,1,2,4]],
     30[['2/m'+'c'],10,[" a = "," b = "," c = ",u" \u03B3 = "],
     31    ["{:.5f}","{:.5f}","{:.5f}","{:.3f}"],[True,True,True,True,],[0,1,2,5]],
     32[['-1'],7,[" a = "," b = "," c = ",u" \u03B1 = ",u" \u03B2 = ",u" \u03B3 = "],
     33    ["{:.5f}","{:.5f}","{:.5f}","{:.3f}","{:.3f}","{:.3f}"],
     34    [True,True,True,False,True,True,True],[0,1,2,3,4,5]]]
    1935
    2036def FormulaEval(string):
     
    88104        if ':' in string: # deal with weird bug where a colon pops up in a number when formatting (EPD 7.3.2!)
    89105            string = str(val)
    90         if digits[1] > 0: # strip off extra zeros on right side
     106        if digits[1] > 0 and not 'e' in string.lower(): # strip off extra zeros on right side
    91107            string = string.rstrip('0')
    92108            if string[-1] == '.': string += "0"
  • trunk/GSASIIstrIO.py

    r4520 r4534  
    132132    :return: dictionary of control items
    133133    '''
    134     Controls = copy.copy(G2obj.DefaultControls)
     134    Controls = copy.deepcopy(G2obj.DefaultControls)
    135135    IndexGPX(GPXfile)
    136136    pos = gpxIndex.get('Controls')
     
    648648    return GPXback
    649649
    650 def SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,RigidBodies,CovData,makeBack=True):
     650def SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,RigidBodies,CovData,parmFrozenList,makeBack=True):
    651651    ''' Updates gpxfile from all histograms that are found in any phase
    652652    and any phase that used a histogram. Also updates rigid body definitions.
     
    658658    :param dict RigidBodies: dictionary of rigid bodies
    659659    :param dict CovData: dictionary of refined variables, varyList, & covariance matrix
     660    :param list parmFrozenList: list of parameters that are frozen due to limits
    660661    :param bool makeBack: True if new backup of .gpx file is to be made; else use the last one made
    661662
     
    684685        elif datum[0] == 'Rigid bodies':
    685686            data[0][1] = RigidBodies
     687        elif datum[0] == 'Controls':
     688            Controls = data[0][1]
     689            if 'parmFrozen' not in Controls:
     690                Controls['parmFrozen'] = {}
     691            Controls['parmFrozen']['FrozenList'] = parmFrozenList
    686692        try:
    687693            histogram = Histograms[datum[0]]
     
    754760    fp.close()
    755761
    756 def SaveUpdatedHistogramsAndPhases(GPXfile,Histograms,Phases,RigidBodies,CovData):
     762def SaveUpdatedHistogramsAndPhases(GPXfile,Histograms,Phases,RigidBodies,CovData,parmFrozen):
    757763    '''
    758764    Save phase and histogram information into "pseudo-gpx" files. The phase
     
    765771    :param dict RigidBodies: dictionary of rigid bodies
    766772    :param dict CovData: dictionary of refined variables, varyList, & covariance matrix
     773    :param dict parmFrozen: dict with frozen parameters for all phases
    767774    '''
    768775                       
     
    785792    cPickle.dump([['Covariance',CovData]],fp,1)
    786793    cPickle.dump([['Rigid bodies',RigidBodies]],fp,1)
     794    cPickle.dump([['parmFrozen',parmFrozen]],fp,1)
    787795    fp.close()
    788796    # create an entry that looks like a PWDR tree item
     
    841849    Phases = {}
    842850    for name,vals in data[1:]:
    843         Phases[name] = vals
     851        Phases[name] = vals       
    844852    name,CovData = cPickleLoad(fp)[0] # 2nd block in file should be Covariance
    845853    name,RigidBodies = cPickleLoad(fp)[0] # 3rd block in file should be Rigid Bodies
     854    name,parmFrozen = cPickleLoad(fp)[0] # 4th block in file should be frozen parameters
    846855    fp.close()
    847856    GPXhist = os.path.splitext(GPXfile)[0]+'.seqHist'
     
    876885            data[0][1] = RigidBodies
    877886        elif datum[0] == 'Controls': # reset the Copy Next flag after a sequential fit
    878             data[0][1]['Copy2Next'] = False
     887            Controls = data[0][1]
     888            Controls['Copy2Next'] = False
     889            Controls['parmFrozen'] = parmFrozen
    879890        elif datum[0] in histIndex:
    880891            hist.seek(histIndex[datum[0]])
  • trunk/GSASIIstrMain.py

    r4456 r4534  
    253253#    print G2mv.VarRemapShow(varyList)
    254254
     255    # remove frozen vars from refinement
     256    if 'parmFrozen' not in Controls:
     257        Controls['parmFrozen'] = {}
     258    if 'FrozenList' not in Controls['parmFrozen']:
     259        Controls['parmFrozen']['FrozenList'] = []
     260    parmFrozenList = Controls['parmFrozen']['FrozenList']
     261    frozenList = [i for i in varyList if i in parmFrozenList]
     262    if len(frozenList) != 0:
     263        varyList = [i for i in varyList if i not in parmFrozenList]
     264        G2fil.G2Print(
     265            'Frozen refined variables (due to exceeding limits)\n\t:{}'
     266            .format(frozenList))
     267       
    255268    ifSeq = False
    256269    printFile.write('\n Refinement results:\n')
     
    271284            # add the uncertainties into the esd dictionary (sigDict)
    272285            sigDict.update(G2mv.ComputeDepESD(covMatrix,varyList,parmDict))
     286            # check for variables outside their allowed range, reset and freeze them
     287            frozen = dropOOBvars(varyList,parmDict,sigDict,Controls,parmFrozenList)
    273288            G2mv.PrintIndependentVars(parmDict,varyList,sigDict,pFile=printFile)
    274289            G2stMth.ApplyRBModels(parmDict,Phases,rigidbodyDict,True)
     
    278293            G2stIO.SetHistogramPhaseData(parmDict,sigDict,Phases,Histograms,calcControls['FFtables'],pFile=printFile)
    279294            G2stIO.SetHistogramData(parmDict,sigDict,Histograms,calcControls['FFtables'],pFile=printFile)
    280             G2stIO.SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,rigidbodyDict,covData,makeBack)
     295            if len(frozen) > 0:
     296                G2fil.G2Print(
     297                    ' {} variables were outside limits and were frozen (now {} frozen total)\n'
     298                    .format(len(frozen),len(parmFrozenList)))
     299            G2stIO.SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,rigidbodyDict,covData,parmFrozenList,makeBack)
    281300            printFile.close()
    282301            G2fil.G2Print (' Refinement results are in file: '+ospath.splitext(GPXfile)[0]+'.lst')
     
    507526        printFile.write('\n Refinement results for histogram: %s\n'%histogram)
    508527        printFile.write(135*'-'+'\n')
     528        # remove frozen vars
     529        if 'parmFrozen' not in Controls:
     530            Controls['parmFrozen'] = {}
     531        if histogram not in Controls['parmFrozen']:
     532            Controls['parmFrozen'][histogram] = []
     533        parmFrozenList = Controls['parmFrozen'][histogram]
     534        frozenList = [i for i in varyList if i in parmFrozenList]
     535        if len(frozenList) != 0:
     536           varyList = [i for i in varyList if i not in parmFrozenList]
     537           printFile.write(
     538               ' The following refined variables have previously been frozen due to exceeding limits\n\t:{}\n'
     539               .format(frozenList))
    509540        try:
    510541            IfOK,Rvals,result,covMatrix,sig = RefineCore(Controls,Histo,Phases,restraintDict,
     
    520551            # the uncertainties for dependent constrained parms into the esd dict
    521552            sigDict.update(G2mv.ComputeDepESD(covMatrix,varyList,parmDict))
    522 
     553            # check for variables outside their allowed range, reset and freeze them
     554            frozen = dropOOBvars(varyList,parmDict,sigDict,Controls,parmFrozenList)
     555            if len(frozen) > 0:
     556               msg = ('Hist {}: {} variables were outside limits and were frozen (now {} frozen total)'
     557                   .format(ihst,len(frozen),len(parmFrozenList)))
     558               G2fil.G2Print(msg)
     559               printFile.write(msg+'\n')
     560               for p in frozen:
     561                   if p not in varyList:
     562                       print('Frozen Warning: {} not in varyList. This should not happen!'.format(p))
     563                       continue
     564                   i = varyList.index(p)
     565                   result[0][i] = parmDict[p]
     566                   sig[i] = -0.1
    523567            # a dict with values & esds for dependent (constrained) parameters - avoid extraneous holds
    524568            depParmDict = {i:(parmDict[i],sigDict[i]) for i in varyListStart if i in sigDict and i not in varyList}
     
    531575                'newCellDict':newCellDict,'depParmDict':depParmDict,
    532576                'constraintInfo':constraintInfo,
    533                 'parmDict':parmDict}
     577                'parmDict':parmDict,
     578                }
    534579            SeqResult[histogram] = histRefData
    535580            G2stMth.ApplyRBModels(parmDict,Phases,rigidbodyDict,True)
     
    537582            G2stIO.SetHistogramPhaseData(parmDict,sigDict,Phases,Histo,None,ifPrint,printFile)
    538583            G2stIO.SetHistogramData(parmDict,sigDict,Histo,None,ifPrint,printFile)
    539             G2stIO.SaveUpdatedHistogramsAndPhases(GPXfile,Histo,Phases,rigidbodyDict,histRefData)
     584            G2stIO.SaveUpdatedHistogramsAndPhases(GPXfile,Histo,Phases,rigidbodyDict,histRefData,Controls['parmFrozen'])
    540585            NewparmDict = {}
    541586            # make dict of varied parameters in current histogram, renamed to
     
    569614            t1 = t2
    570615    SeqResult['histNames'] = [itm for itm in G2stIO.GetHistogramNames(GPXfile,['PWDR',]) if itm in SeqResult.keys()]
    571     G2stIO.SetSeqResult(GPXfile,Histograms,SeqResult)
     616    try:
     617        G2stIO.SetSeqResult(GPXfile,Histograms,SeqResult)
     618    except Exception as msg:
     619        print('Error reading Sequential results')
     620        if GSASIIpath.GetConfigValue('debug'):
     621            import traceback
     622            print(traceback.format_exc())       
    572623    printFile.close()
    573624    G2fil.G2Print (' Sequential refinement results are in file: '+ospath.splitext(GPXfile)[0]+'.lst')
    574625    G2fil.G2Print (' ***** Sequential refinement successful *****')
    575626    return True,'Success'
     627
     628def dropOOBvars(varyList,parmDict,sigDict,Controls,parmFrozenList):
     629    '''Find variables in the parameters dict that are outside the ranges
     630    (in parmMinDict and parmMaxDict) and set them to the limits values.
     631    Add any such variables into the list of frozen variable
     632    (parmFrozenList). Returns a list of newly frozen variables, if any.
     633    '''
     634    parmMinDict = Controls.get('parmMinDict',{})
     635    parmMaxDict = Controls.get('parmMaxDict',{})
     636    freeze = []
     637    if parmMinDict or parmMaxDict:
     638        for name in varyList:
     639            if name not in parmDict: continue
     640            n,val = G2obj.prmLookup(name,parmMinDict)
     641            if n is not None:
     642                if parmDict[name] < parmMinDict[n]:
     643                    parmDict[name] = parmMinDict[n]
     644                    sigDict[name] = 0.0
     645                    freeze.append(name)
     646                    continue
     647            n,val = G2obj.prmLookup(name,parmMaxDict)
     648            if n is not None:
     649                if parmDict[name] > parmMaxDict[n]:
     650                    parmDict[name] = parmMaxDict[n]
     651                    sigDict[name] = 0.0
     652                    freeze.append(name)
     653                    continue
     654        for v in freeze:
     655            if v not in parmFrozenList:
     656                parmFrozenList.append(v)
     657    return freeze
    576658
    577659def RetDistAngle(DisAglCtls,DisAglData,dlg=None):
Note: See TracChangeset for help on using the changeset viewer.