Ignore:
Timestamp:
Jan 17, 2019 6:46:16 PM (4 years ago)
Author:
toby
Message:

generate cell parm constraints for magnetic cells; fix errors in display of symmetry-generated constraints

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIconstrGUI.py

    r3785 r3788  
    131131    Displays the constraints in the data window
    132132    '''
    133     if not data:
    134         data.update({'Hist':[],'HAP':[],'Phase':[],'Global':[]})       #empty dict - fill it
    135     if 'Global' not in data:                                            #patch
    136         data['Global'] = []
    137     # DEBUG code ########################################
    138     #import GSASIIconstrGUI
    139     #reload(GSASIIconstrGUI)
    140     #reload(G2obj)
    141     #reload(G2stIO)
    142     #import GSASIIstrMain
    143     #reload(GSASIIstrMain)   
    144     #reload(G2mv)
    145     #reload(G2gd)
    146     ###################################################
    147     Histograms,Phases = G2frame.GetUsedHistogramsAndPhasesfromTree()
    148     if not len(Phases) or not len(Histograms):
    149         dlg = wx.MessageDialog(G2frame,'You need both phases and histograms to see Constraints',
    150             'No phases or histograms')
    151         dlg.CenterOnParent()
    152         dlg.ShowModal()
    153         dlg.Destroy()
    154         return
    155     G2obj.IndexAllIds(Histograms,Phases)
    156     ##################################################################################
    157     # patch: convert old-style (str) variables in constraints to G2VarObj objects
    158     for key,value in data.items():
    159         if key.startswith('_'): continue
    160         j = 0
    161         for cons in value:
    162             #print cons             # DEBUG
    163             for i in range(len(cons[:-3])):
    164                 if type(cons[i][1]) is str:
    165                     cons[i][1] = G2obj.G2VarObj(cons[i][1])
    166                     j += 1
    167         if j:
    168             print (str(key) + ': '+str(j)+' variable(s) as strings converted to objects')
    169     ##################################################################################
    170     rigidbodyDict = G2frame.GPXtree.GetItemPyData(
    171         G2gd.GetGPXtreeItemId(G2frame,G2frame.root,'Rigid bodies'))
    172     rbIds = rigidbodyDict.get('RBIds',{'Vector':[],'Residue':[]})
    173     rbVary,rbDict = G2stIO.GetRigidBodyModels(rigidbodyDict,Print=False)
    174     badPhaseParms = ['Ax','Ay','Az','Amul','AI/A','Atype','SHorder','mV0','mV1','mV2','AwaveType','FwaveType','PwaveType','MwaveType','Vol','isMag',]
    175     globalList = list(rbDict.keys())
    176     globalList.sort()
    177     try:
    178         AtomDict = dict([Phases[phase]['pId'],Phases[phase]['Atoms']] for phase in Phases)
    179     except KeyError:
    180         G2frame.ErrorDialog('Constraint Error','Constraints cannot be set until a cycle of least squares'+
    181                             ' has been run.\nWe suggest you refine a scale factor.')
    182         return
    183 
    184     # create a list of the phase variables
    185     Natoms,atomIndx,phaseVary,phaseDict,pawleyLookup,FFtable,BLtable,MFtable,maxSSwave = G2stIO.GetPhaseData(Phases,rbIds=rbIds,Print=False)
    186     phaseList = []
    187     for item in phaseDict:
    188         if item.split(':')[2] not in badPhaseParms:
    189             phaseList.append(item)
    190     phaseList.sort()
    191     phaseAtNames = {}
    192     phaseAtTypes = {}
    193     TypeList = []
    194     for item in phaseList:
    195         Split = item.split(':')
    196         if Split[2][:2] in ['AU','Af','dA','AM']:
    197             Id = int(Split[0])
    198             phaseAtNames[item] = AtomDict[Id][int(Split[3])][0]
    199             phaseAtTypes[item] = AtomDict[Id][int(Split[3])][1]
    200             if phaseAtTypes[item] not in TypeList:
    201                 TypeList.append(phaseAtTypes[item])
    202         else:
    203             phaseAtNames[item] = ''
    204             phaseAtTypes[item] = ''
    205              
    206     # create a list of the hist*phase variables
    207     seqList = G2frame.testSeqRefineMode()
    208     if seqList: # for sequential refinement, only process 1st histgram in list
    209         histDict = {seqList[0]:Histograms[seqList[0]]}
    210     else:
    211         histDict = Histograms
    212     hapVary,hapDict,controlDict = G2stIO.GetHistogramPhaseData(Phases,histDict,Print=False,resetRefList=False)
    213     hapList = sorted([i for i in hapDict.keys() if i.split(':')[2] not in ('Type',)])
    214     if seqList: # convert histogram # to wildcard
    215         wildList = [] # list of variables with "*" for histogram number
    216         for i in hapList:
    217             s = i.split(':')
    218             if s[1] == "": continue
    219             s[1] = '*'
    220             sj = ':'.join(s)
    221             if sj not in wildList: wildList.append(sj)
    222         hapList = wildList
    223     histVary,histDict,controlDict = G2stIO.GetHistogramData(histDict,Print=False)
    224     histList = list(histDict.keys())
    225     histList.sort()
    226     if seqList: # convert histogram # to wildcard
    227         wildList = [] # list of variables with "*" for histogram number
    228         for i in histList:
    229             s = i.split(':')
    230             if s[1] == "": continue
    231             s[1] = '*'
    232             sj = ':'.join(s)
    233             if sj not in wildList: wildList.append(sj)
    234         histList = wildList       
    235     Indx = {}
    236     G2frame.Page = [0,'phs']
    237133       
    238134    def FindEquivVarb(name,nameList):
     
    504400        return []
    505401   
    506     def FindAllCons(data):
    507         ''' Find all constraints
     402    def ConstraintsLoad(data,newcons=[]):
     403        '''Load all constraints. Constraints based on symmetry (etc.)
     404        are generated by running :func:`GSASIIstrIO.GetPhaseData`.
    508405        '''
    509         allcons = []
     406        G2mv.InitVars()
     407        #Find all constraints
     408        constraintSet = []
    510409        for key in data:
    511410            if key.startswith('_'): continue
    512             allcons += data[key]
    513         return allcons
    514        
    515     def CheckConstraints(constraintSet):
    516         '''Check for errors in a set of constraints. Constraints based on symmetry (etc.)
    517         are generated by running :func:`GSASIIstrIO.GetPhaseData`.
    518         '''
    519         G2mv.InitVars()   
     411            constraintSet += data[key]
     412        if newcons:
     413            constraintSet = constraintSet + newcons
    520414        constDictList,fixedList,ignored = G2stIO.ProcessConstraints(constraintSet)
    521415        # generate symmetry constraints to check for conflicts
     
    526420        Natoms,atomIndx,phaseVary,phaseDict,pawleyLookup,FFtables,BLtables,MFtables,maxSSwave = G2stIO.GetPhaseData(
    527421            Phases,RestraintDict=None,rbIds=rbIds,Print=False) # generates atom symmetry constraints
     422        return constDictList,phaseDict,fixedList
     423           
     424    def ConstraintsCheck(data,newcons=[]):
     425        '''Load constraints & check them for errors. Since error checking
     426        can cause changes in constraints in case of repairable conflicts
     427        between equivalences, reload the constraints again after the check.
     428        This could probably be done more effectively, but only reloading when
     429        needed, but the reload should be quick.
     430        '''
     431        constDictList,phaseDict,fixedList = ConstraintsLoad(data,newcons)
    528432        msg = G2mv.EvaluateMultipliers(constDictList,phaseDict)
    529         if msg: return 'Unable to interpret multiplier(s): '+msg
    530         return G2mv.CheckConstraints('',constDictList,fixedList)
     433        if msg:
     434            return 'Unable to interpret multiplier(s): '+msg,''
     435        res = G2mv.CheckConstraints('',constDictList,fixedList)
     436        # reload constraints in case any were merged in MoveConfEquiv
     437        ConstraintsLoad(data,newcons)
     438        return res
    531439
    532440    def CheckAddedConstraint(newcons):
     
    540448        '''
    541449       
    542         allcons1 = FindAllCons(data)
    543         allcons = allcons1[:]
    544         allcons += newcons
    545         if not len(allcons): return True
    546         errmsg,warnmsg = CheckConstraints(allcons)
     450        errmsg,warnmsg = ConstraintsCheck(data,newcons)
    547451        if errmsg:
    548452            G2frame.ErrorDialog('Constraint Error',
    549453                'Error with newly added constraint:\n'+errmsg+
    550454                '\nIgnoring newly added constraint',parent=G2frame)
    551             # Note no multiplier formulas in GUI, skipping EvaluateMultipliers 
    552455            # reset error status
    553             errmsg,warnmsg = CheckConstraints(allcons1)
     456            errmsg,warnmsg = ConstraintsCheck(data)
    554457            if errmsg:
    555458                print (errmsg)
     
    569472        :returns: True if the edit should be retained
    570473        '''
    571         allcons = FindAllCons(data)
    572         if not len(allcons): return True
    573         # Note no multiplier formulas in GUI, skipping EvaluateMultipliers 
    574         errmsg,warnmsg = CheckConstraints(allcons)
     474        errmsg,warnmsg = ConstraintsCheck(data)
    575475        if errmsg:
    576476            G2frame.ErrorDialog('Constraint Error',
     
    578478                '\nDiscarding last constraint edit',parent=G2frame)
    579479            # reset error status
    580             errmsg,warnmsg = CheckConstraints(allcons)
     480            errmsg,warnmsg = ConstraintsCheck(data)
    581481            if errmsg:
    582482                print (errmsg)
     
    892792                eqString[-1] =  var +'   '
    893793                helptext = "Prevents variable:\n"+ var + " ("+ varMean + ")\nfrom being changed"
    894             elif isinstance(item[-1],str): # not true on original-style (2011?) constraints
     794            elif item[-1] == 'f' or item[-1] == 'e' or item[-1] == 'c': # not true on original-style (2011?) constraints
    895795                constEdit = wx.Button(pageDisplay,wx.ID_ANY,'Edit',style=wx.BU_EXACTFIT)
    896796                constEdit.Bind(wx.EVT_BUTTON,OnConstEdit)
     
    1015915        Id,name = Indx[Obj.GetId()]
    1016916        del data[name][Id]
    1017         allcons = FindAllCons(data)     #should I call CheckChangedConstraint() instead?
    1018         if len(allcons):
    1019             CheckConstraints(allcons)
     917        ConstraintsLoad(data)
    1020918        wx.CallAfter(OnPageChanged,None)
    1021919
     
    11531051
    11541052    def SetStatusLine(text):
    1155         G2frame.GetStatusBar().SetStatusText(text,1)                                     
    1156        
     1053        G2frame.GetStatusBar().SetStatusText(text,1)
     1054
     1055    # UpdateConstraints execution starts here
     1056    if not data:
     1057        data.update({'Hist':[],'HAP':[],'Phase':[],'Global':[]})       #empty dict - fill it
     1058    if 'Global' not in data:                                            #patch
     1059        data['Global'] = []
     1060    # DEBUG code ########################################
     1061    #import GSASIIconstrGUI
     1062    #reload(GSASIIconstrGUI)
     1063    #reload(G2obj)
     1064    #reload(G2stIO)
     1065    #import GSASIIstrMain
     1066    #reload(GSASIIstrMain)   
     1067    #reload(G2mv)
     1068    #reload(G2gd)
     1069    ###################################################
     1070    Histograms,Phases = G2frame.GetUsedHistogramsAndPhasesfromTree()
     1071    if not len(Phases) or not len(Histograms):
     1072        dlg = wx.MessageDialog(G2frame,'You need both phases and histograms to see Constraints',
     1073            'No phases or histograms')
     1074        dlg.CenterOnParent()
     1075        dlg.ShowModal()
     1076        dlg.Destroy()
     1077        return
     1078    G2obj.IndexAllIds(Histograms,Phases)
     1079    ##################################################################################
     1080    # patch: convert old-style (str) variables in constraints to G2VarObj objects
     1081    for key,value in data.items():
     1082        if key.startswith('_'): continue
     1083        j = 0
     1084        for cons in value:
     1085            #print cons             # DEBUG
     1086            for i in range(len(cons[:-3])):
     1087                if type(cons[i][1]) is str:
     1088                    cons[i][1] = G2obj.G2VarObj(cons[i][1])
     1089                    j += 1
     1090        if j:
     1091            print (str(key) + ': '+str(j)+' variable(s) as strings converted to objects')
     1092    ##################################################################################
     1093    rigidbodyDict = G2frame.GPXtree.GetItemPyData(
     1094        G2gd.GetGPXtreeItemId(G2frame,G2frame.root,'Rigid bodies'))
     1095    rbIds = rigidbodyDict.get('RBIds',{'Vector':[],'Residue':[]})
     1096    rbVary,rbDict = G2stIO.GetRigidBodyModels(rigidbodyDict,Print=False)
     1097    badPhaseParms = ['Ax','Ay','Az','Amul','AI/A','Atype','SHorder','mV0','mV1','mV2','AwaveType','FwaveType','PwaveType','MwaveType','Vol','isMag',]
     1098    globalList = list(rbDict.keys())
     1099    globalList.sort()
     1100    try:
     1101        AtomDict = dict([Phases[phase]['pId'],Phases[phase]['Atoms']] for phase in Phases)
     1102    except KeyError:
     1103        G2frame.ErrorDialog('Constraint Error','Constraints cannot be set until a cycle of least squares'+
     1104                            ' has been run.\nWe suggest you refine a scale factor.')
     1105        return
     1106
     1107    # create a list of the phase variables
     1108    Natoms,atomIndx,phaseVary,phaseDict,pawleyLookup,FFtable,BLtable,MFtable,maxSSwave = G2stIO.GetPhaseData(Phases,rbIds=rbIds,Print=False)
     1109    phaseList = []
     1110    for item in phaseDict:
     1111        if item.split(':')[2] not in badPhaseParms:
     1112            phaseList.append(item)
     1113    phaseList.sort()
     1114    phaseAtNames = {}
     1115    phaseAtTypes = {}
     1116    TypeList = []
     1117    for item in phaseList:
     1118        Split = item.split(':')
     1119        if Split[2][:2] in ['AU','Af','dA','AM']:
     1120            Id = int(Split[0])
     1121            phaseAtNames[item] = AtomDict[Id][int(Split[3])][0]
     1122            phaseAtTypes[item] = AtomDict[Id][int(Split[3])][1]
     1123            if phaseAtTypes[item] not in TypeList:
     1124                TypeList.append(phaseAtTypes[item])
     1125        else:
     1126            phaseAtNames[item] = ''
     1127            phaseAtTypes[item] = ''
     1128             
     1129    # create a list of the hist*phase variables
     1130    seqList = G2frame.testSeqRefineMode()
     1131    if seqList: # for sequential refinement, only process 1st histgram in list
     1132        histDict = {seqList[0]:Histograms[seqList[0]]}
     1133    else:
     1134        histDict = Histograms
     1135    hapVary,hapDict,controlDict = G2stIO.GetHistogramPhaseData(Phases,histDict,Print=False,resetRefList=False)
     1136    hapList = sorted([i for i in hapDict.keys() if i.split(':')[2] not in ('Type',)])
     1137    if seqList: # convert histogram # to wildcard
     1138        wildList = [] # list of variables with "*" for histogram number
     1139        for i in hapList:
     1140            s = i.split(':')
     1141            if s[1] == "": continue
     1142            s[1] = '*'
     1143            sj = ':'.join(s)
     1144            if sj not in wildList: wildList.append(sj)
     1145        hapList = wildList
     1146    histVary,histDict,controlDict = G2stIO.GetHistogramData(histDict,Print=False)
     1147    histList = list(histDict.keys())
     1148    histList.sort()
     1149    if seqList: # convert histogram # to wildcard
     1150        wildList = [] # list of variables with "*" for histogram number
     1151        for i in histList:
     1152            s = i.split(':')
     1153            if s[1] == "": continue
     1154            s[1] = '*'
     1155            sj = ':'.join(s)
     1156            if sj not in wildList: wildList.append(sj)
     1157        histList = wildList       
     1158    Indx = {}
     1159    G2frame.Page = [0,'phs']
     1160   
    11571161    G2gd.SetDataMenuBar(G2frame,G2frame.dataWindow.ConstraintMenu)
    11581162    SetStatusLine('')
     
    11901194    G2frame.constr.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CHANGED, OnPageChanged)
    11911195    # validate all the constrants -- should not see any errors here normally
    1192     allcons = FindAllCons(data)
    1193     if not len(allcons): return
    1194     errmsg,warnmsg = CheckConstraints(allcons)
     1196    errmsg,warnmsg = ConstraintsCheck(data)
    11951197    if errmsg:
    11961198        G2frame.ErrorDialog('Constraint Error',
     
    12011203    elif warnmsg:
    12021204        print ('Unexpected contraint warning:\n'+warnmsg)
    1203 
     1205       
    12041206################################################################################
    12051207# check scale & phase fractions, create constraint if needed
     
    12921294            if iA in [0,1,3]:
    12931295                parm = '%d::%s'%(pId,'A0')
     1296            elif iA == 2:
     1297                parm = '%d::%s'%(pId,'A2')
    12941298            else:
    12951299                parm = None
     
    14591463        if len(multDict) == 1:
    14601464            key = list(multDict.keys())[0]
    1461             constr = [[multDict[key],G2obj.G2VarObj(Nparm)],
    1462                           [1.0,G2obj.G2VarObj(key)],None,None,'e']
     1465            constr = [
     1466                [1.0,G2obj.G2VarObj(key)],
     1467                [multDict[key],G2obj.G2VarObj(Nparm)],
     1468                None,None,'e']
    14631469        else:
    14641470            constr = [[-1.0,G2obj.G2VarObj(Nparm)]]
Note: See TracChangeset for help on using the changeset viewer.