source: branch/2frame/GSASIIrestrGUI.py @ 2900

Last change on this file since 2900 was 2900, checked in by toby, 6 years ago

reorg for GUI separation pretty much complete (GSASIIIO.py still needs some thought)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 88.1 KB
Line 
1# -*- coding: utf-8 -*-
2#GSASIIrestr - restraint GUI routines
3########### SVN repository information ###################
4# $Date: 2017-07-04 14:37:13 +0000 (Tue, 04 Jul 2017) $
5# $Author: toby $
6# $Revision: 2900 $
7# $URL: branch/2frame/GSASIIrestrGUI.py $
8# $Id: GSASIIrestrGUI.py 2900 2017-07-04 14:37:13Z toby $
9########### SVN repository information ###################
10'''
11*GSASIIrestrGUI: Restraint GUI routines*
12----------------------------------------
13
14Used to define restraints.
15
16'''
17import wx
18import wx.grid as wg
19import numpy as np
20import numpy.ma as ma
21import os.path
22import GSASIIpath
23GSASIIpath.SetVersionNumber("$Revision: 2900 $")
24import GSASIImath as G2mth
25import GSASIIlattice as G2lat
26import GSASIIspc as G2spc
27import GSASIIdataGUI as G2gd
28import GSASIIplot as G2plt
29import GSASIIdata as G2data
30import GSASIIctrlGUI as G2G
31
32VERY_LIGHT_GREY = wx.Colour(235,235,235)
33
34################################################################################
35#####  Restraints
36################################################################################           
37def GetSelectedRows(widget):
38    '''Returns a list of selected rows. Rows can be selected, blocks of cells
39    or individual cells can be selected. The column for selected cells is ignored.
40    '''
41    rows = widget.GetSelectedRows()
42    if not rows:
43        top = widget.GetSelectionBlockTopLeft()
44        bot = widget.GetSelectionBlockBottomRight()
45        if top and bot:
46            rows = range(top[0][0],bot[0][0]+1)
47    if not rows:
48        rows = sorted(list(set([cell[0] for cell in widget.GetSelectedCells()])))
49    return rows
50       
51def UpdateRestraints(G2frame,data,Phases,phaseName):
52    '''Respond to selection of the Restraints item on the
53    data tree
54    '''
55    if not Phases:
56        print 'There are no phases to form restraints'
57        return
58    if not len(Phases):
59        print 'There are no phases to form restraints'
60        return
61    phasedata = Phases[phaseName]
62    if phaseName not in data:
63        data[phaseName] = {}
64    restrData = data[phaseName]
65    if 'Bond' not in restrData:
66        restrData['Bond'] = {'wtFactor':1.0,'Range':1.1,'Bonds':[],'Use':True}
67    if 'Angle' not in restrData:
68        restrData['Angle'] = {'wtFactor':1.0,'Range':0.85,'Angles':[],'Use':True}
69    if 'Plane' not in restrData:
70        restrData['Plane'] = {'wtFactor':1.0,'Planes':[],'Use':True}
71    if 'Chiral' not in restrData:
72        restrData['Chiral'] = {'wtFactor':1.0,'Volumes':[],'Use':True}
73    if 'Torsion' not in restrData:
74        restrData['Torsion'] = {'wtFactor':1.0,'Coeff':{},'Torsions':[],'Use':True}
75    if 'Rama' not in restrData:
76        restrData['Rama'] = {'wtFactor':1.0,'Coeff':{},'Ramas':[],'Use':True}
77    if 'Texture' not in restrData:
78        restrData['Texture'] = {'wtFactor':1.0,'HKLs':[],'Use':True}
79    if 'ChemComp' not in restrData:
80        restrData['ChemComp'] = {'wtFactor':1.0,'Sites':[],'Use':True}
81    General = phasedata['General']
82    Cell = General['Cell'][1:7]          #skip flag & volume   
83    Amat,Bmat = G2lat.cell2AB(Cell)
84    SGData = General['SGData']
85    cx,ct,cs,cia = General['AtomPtrs']
86    Atoms = phasedata['Atoms']
87    AtLookUp = G2mth.FillAtomLookUp(Atoms,cia+8)
88    if 'macro' in General['Type']:
89        Names = [atom[0]+':'+atom[1]+atom[2]+' '+atom[3] for atom in Atoms]
90        Ids = []
91        Coords = []
92        Types = []
93    else:   
94        Names = ['all '+ name for name in General['AtomTypes']]
95        iBeg = len(Names)
96        Types = [name for name in General['AtomTypes']]
97        Coords = [ [] for type in Types]
98        Ids = [ 0 for type in Types]
99        Names += [atom[ct-1] for atom in Atoms]
100    Types += [atom[ct] for atom in Atoms]
101    Coords += [atom[cx:cx+3] for atom in Atoms]
102    Ids += [atom[cia+8] for atom in Atoms]
103    rama = G2data.ramachandranDist['All']
104    ramaName = 'All'
105   
106    def OnSelectPhase(event):
107        dlg = wx.SingleChoiceDialog(G2frame,'Select','Phase',Phases.keys())
108        try:
109            if dlg.ShowModal() == wx.ID_OK:
110                phaseName = Phases.keys()[dlg.GetSelection()]
111                UpdateRestraints(G2frame,data,Phases,phaseName)
112        finally:
113            dlg.Destroy()
114   
115    def getMacroFile(macName):
116        defDir = os.path.join(os.path.split(__file__)[0],'GSASIImacros')
117        dlg = wx.FileDialog(G2frame,message='Choose '+macName+' restraint macro file',
118            defaultDir=defDir,defaultFile="",wildcard="GSAS-II macro file (*.mac)|*.mac",
119            style=wx.OPEN | wx.CHANGE_DIR)
120        try:
121            macro = ''
122            if dlg.ShowModal() == wx.ID_OK:
123                macfile = dlg.GetPath()
124                macro = open(macfile,'Ur')
125                head = macro.readline()
126                if macName not in head:
127                    print head
128                    print '**** ERROR - wrong restraint macro file selected, try again ****'
129                    macro = []
130        finally:
131            dlg.Destroy()
132        return macro        #advanced past 1st line
133       
134    def OnPlotAARestraint(event):
135        page = G2frame.dataDisplay.GetSelection()
136        if 'Torsion' in G2frame.dataDisplay.GetPageText(page):
137            torNames = []
138            torNames += restrData['Torsion']['Coeff'].keys()
139            dlg = wx.SingleChoiceDialog(G2frame,'Select','Torsion data',torNames)
140            try:
141                if dlg.ShowModal() == wx.ID_OK:
142                    torName = torNames[dlg.GetSelection()]
143                    torsion = G2data.torsionDist[torName]
144                    torCoeff = restrData['Torsion']['Coeff'][torName]
145                    torList = restrData['Torsion']['Torsions']
146                    Names = []
147                    Angles = []
148                    for i,[indx,ops,cofName,esd] in enumerate(torList):
149                        if cofName == torName:
150                            atoms = G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,0,4)
151                            name = '('+atoms[2][1]+atoms[2][0].strip()+atoms[2][2]+')'
152                            for atom in atoms:
153                                name += '  '+atom[3]
154                            XYZ = np.array(G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,cx,3))
155                            angle = G2mth.getRestTorsion(XYZ,Amat)
156                            Angles.append(angle)
157                            Names.append(name) 
158                    G2plt.PlotTorsion(G2frame,phaseName,torsion,torName,Names,np.array(Angles),torCoeff)
159            finally:
160                dlg.Destroy()
161           
162        elif 'Rama' in G2frame.dataDisplay.GetPageText(page):
163            ramaNames = ['All',]
164            ramaNames += restrData['Rama']['Coeff'].keys()
165            dlg = wx.SingleChoiceDialog(G2frame,'Select','Ramachandran data',ramaNames)
166            try:
167                if dlg.ShowModal() == wx.ID_OK:
168                    ramaName = ramaNames[dlg.GetSelection()]
169                    rama = G2data.ramachandranDist[ramaName]
170                    ramaCoeff = []
171                    if ramaName != 'All':
172                        ramaCoeff = restrData['Rama']['Coeff'][ramaName]
173                    ramaList = restrData['Rama']['Ramas']
174                    Names = []
175                    PhiPsi = []
176                    for i,[indx,ops,cofName,esd] in enumerate(ramaList):
177                        if cofName == ramaName or (ramaName == 'All' and '-1' in cofName):
178                            atoms = G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,0,4)
179                            name = '('+atoms[3][1]+atoms[3][0].strip()+atoms[3][2]+')'
180                            for atom in atoms:
181                                name += '  '+atom[3]
182                            XYZ = np.array(G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,cx,3))
183                            phi,psi = G2mth.getRestRama(XYZ,Amat)
184                            PhiPsi.append([phi,psi])
185                            Names.append(name) 
186                    G2plt.PlotRama(G2frame,phaseName,rama,ramaName,Names,np.array(PhiPsi),ramaCoeff)
187            finally:
188                dlg.Destroy()
189           
190    def OnAddRestraint(event):
191        page = G2frame.restrBook.GetSelection()
192        if 'Bond' in G2frame.restrBook.GetPageText(page):
193            AddBondRestraint(restrData['Bond'])
194        elif 'Angle' in G2frame.restrBook.GetPageText(page):
195            AddAngleRestraint(restrData['Angle'])
196        elif 'Plane' in G2frame.restrBook.GetPageText(page):
197            AddPlaneRestraint(restrData['Plane'])
198        elif 'Chem' in G2frame.restrBook.GetPageText(page):
199            AddChemCompRestraint(restrData['ChemComp'])
200        elif 'Texture' in G2frame.restrBook.GetPageText(page):
201            AddTextureRestraint(restrData['Texture'])
202           
203    def OnAddAARestraint(event):
204        page = G2frame.restrBook.GetSelection()
205        if 'Bond' in G2frame.restrBook.GetPageText(page):
206            AddAABondRestraint(restrData['Bond'])
207        elif 'Angle' in G2frame.restrBook.GetPageText(page):
208            AddAAAngleRestraint(restrData['Angle'])
209        elif 'Plane' in G2frame.restrBook.GetPageText(page):
210            AddAAPlaneRestraint(restrData['Plane'])
211        elif 'Chiral' in G2frame.restrBook.GetPageText(page):
212            AddAAChiralRestraint(restrData['Chiral'])
213        elif 'Torsion' in G2frame.restrBook.GetPageText(page):
214            AddAATorsionRestraint(restrData['Torsion'])
215        elif 'Rama' in G2frame.restrBook.GetPageText(page):
216            AddAARamaRestraint(restrData['Rama'])
217           
218    def AddBondRestraint(bondRestData):
219        Lists = {'origin':[],'target':[]}
220        for listName in ['origin','target']:
221            dlg = wx.MultiChoiceDialog(G2frame,'Bond restraint '+listName+' for '+General['Name'],
222                    'Select bond restraint '+listName+' atoms',Names)
223            if dlg.ShowModal() == wx.ID_OK:
224                sel = dlg.GetSelections()
225                for x in sel:
226                    if 'all' in Names[x]:
227                        allType = Types[x]
228                        for name,Type,coords,id in zip(Names,Types,Coords,Ids):
229                            if Type == allType and 'all' not in name:
230                                Lists[listName].append([id,Type,coords])
231                    else:
232                        Lists[listName].append([Ids[x],Types[x],Coords[x],])
233            else:
234                break
235        if len(Lists['origin']) and len(Lists['target']):
236            bond = 1.54
237            dlg = G2G.SingleFloatDialog(G2frame,'Distance','Enter restraint distance for bond',bond,[0.01,4.],'%.4f')
238            if dlg.ShowModal() == wx.ID_OK:
239                bond = dlg.GetValue()
240            dlg.Destroy()
241        Factor = bondRestData['Range']
242        indices = (-2,-1,0,1,2)
243        Units = np.array([[h,k,l] for h in indices for k in indices for l in indices])
244        origAtoms = Lists['origin']
245        targAtoms = Lists['target']
246        dlg = wx.ProgressDialog("Generating bond restraints","Processed origin atoms",len(origAtoms), 
247            style = wx.PD_ELAPSED_TIME|wx.PD_AUTO_HIDE|wx.PD_REMAINING_TIME)
248        try:
249            Norig = 0
250            for Oid,Otype,Ocoord in origAtoms:
251                Norig += 1
252                dlg.Update(Norig)
253                for Tid,Ttype,Tcoord in targAtoms:
254                    if 'macro' in General['Type']:
255                        result = [[Tcoord,1,[0,0,0]],]
256                    else:
257                        result = G2spc.GenAtom(Tcoord,SGData,False,Move=False)
258                    for Txyz,Top,Tunit in result:
259                        Dx = (Txyz-np.array(Ocoord))+Units
260                        dx = np.inner(Amat,Dx)
261                        dist = ma.masked_less(np.sqrt(np.sum(dx**2,axis=0)),bond/Factor)
262                        IndB = ma.nonzero(ma.masked_greater(dist,bond*Factor))
263                        if np.any(IndB):
264                            for indb in IndB:
265                                for i in range(len(indb)):
266                                    unit = Units[indb][i]+Tunit
267                                    if np.any(unit):
268                                        Topstr = '%d+%d,%d,%d'%(Top,unit[0],unit[1],unit[2])
269                                    else:
270                                        Topstr = str(Top)
271                                    newBond = [[Oid,Tid],['1',Topstr],bond,0.01]
272                                    if newBond not in bondRestData['Bonds']:
273                                        bondRestData['Bonds'].append(newBond)
274        finally:
275            dlg.Destroy()
276        UpdateBondRestr(bondRestData)               
277
278    def AddAABondRestraint(bondRestData):
279        macro = getMacroFile('bond')
280        if not macro:
281            return
282        macStr = macro.readline()
283        atoms = zip(Names,Coords,Ids)
284       
285        Factor = bondRestData['Range']
286        while macStr:
287            items = macStr.split()
288            if 'F' in items[0]:
289                restrData['Bond']['wtFactor'] = float(items[1])
290            elif 'S' in items[0]:
291                oIds = []
292                oCoords = []
293                tIds = []
294                tCoords = []
295                res = items[1]
296                dist = float(items[2])
297                esd = float(items[3])
298                oAtm,tAtm = items[4:6]
299                for Name,coords,Id in atoms:
300                    names = Name.split()
301                    if res == '*' or res in names[0]:
302                        if oAtm == names[2]:
303                            oIds.append(Id)
304                            oCoords.append(np.array(coords))
305                        if tAtm == names[2]:
306                            tIds.append(Id)
307                            tCoords.append(np.array(coords))
308                for i,[oId,oCoord] in enumerate(zip(oIds,oCoords)):
309                    for tId,tCoord in zip(tIds,tCoords)[i:]:
310                        obsd = np.sqrt(np.sum(np.inner(Amat,tCoord-oCoord)**2))
311                        if dist/Factor < obsd < dist*Factor:
312                            newBond = [[oId,tId],['1','1'],dist,esd]
313                            if newBond not in bondRestData['Bonds']:
314                                bondRestData['Bonds'].append(newBond)                         
315            macStr = macro.readline()
316        macro.close()
317        UpdateBondRestr(bondRestData)               
318           
319    def AddAngleRestraint(angleRestData):
320        Radii = dict(zip(General['AtomTypes'],zip(General['BondRadii'],General['AngleRadii'])))
321        Lists = {'A-atom':[],'B-atom':[],'C-atom':[]}
322        for listName in ['A-atom','B-atom']:
323            dlg = wx.MultiChoiceDialog(G2frame,'Select '+listName+' for angle A-B-C for '+General['Name']                                                                           ,
324                    'Select angle restraint '+listName,Names)
325            if dlg.ShowModal() == wx.ID_OK:
326                sel = dlg.GetSelections()
327                for x in sel:
328                    if 'all' in Names[x]:
329                        allType = Types[x]
330                        for name,Type,coords,id in zip(Names,Types,Coords,Ids):
331                            if Type == allType and 'all' not in name:
332                                if 'A' in listName:
333                                    Lists[listName].append(Type)
334                                else:
335                                    Lists[listName].append([id,Type,coords])
336                    else:
337                        if 'A' in listName:
338                            Lists[listName].append(Types[x])
339                        else:
340                            Lists[listName].append([Ids[x],Types[x],Coords[x],])
341            else:
342                break
343            targAtoms = [[Ids[x+iBeg],Types[x+iBeg],Coords[x+iBeg]] for x in range(len(Names[iBeg:]))]
344        if len(Lists['B-atom']):
345            value = 109.54
346            dlg = G2G.SingleFloatDialog(G2frame,'Angle','Enter restraint angle ',value,[30.,180.],'%.2f')
347            if dlg.ShowModal() == wx.ID_OK:
348                value = dlg.GetValue()
349            dlg.Destroy()
350
351        Factor = angleRestData['Range']
352        indices = (-2,-1,0,1,2)
353        Units = np.array([[h,k,l] for h in indices for k in indices for l in indices])
354        VectA = []
355        for Oid,Otype,Ocoord in Lists['B-atom']:
356            IndBlist = []
357            VectB = []
358            for Tid,Ttype,Tcoord in targAtoms:
359                result = G2spc.GenAtom(Tcoord,SGData,False,Move=False)
360                BsumR = (Radii[Otype][0]+Radii[Ttype][0])*Factor
361                AsumR = (Radii[Otype][1]+Radii[Ttype][1])*Factor
362                for Txyz,Top,Tunit in result:
363                    Dx = (Txyz-Ocoord)+Units
364                    dx = np.inner(Amat,Dx)
365                    dist = ma.masked_less(np.sqrt(np.sum(dx**2,axis=0)),0.5)
366                    IndB = ma.nonzero(ma.masked_greater(dist,BsumR))
367                    if np.any(IndB):
368                        for indb in IndB:
369                            for i in range(len(indb)):
370                                if str(dx.T[indb][i]) not in IndBlist:
371                                    IndBlist.append(str(dx.T[indb][i]))
372                                    unit = Units[indb][i]+Tunit
373                                if np.any(unit):
374                                    Topstr = '%d+%d,%d,%d'%(Top,unit[0],unit[1],unit[2])
375                                else:
376                                    Topstr = str(Top)
377                                Dist = ma.getdata(dist[indb])[i]
378                                if (Dist-AsumR) <= 0.:
379                                    VectB.append([Oid,'1',Ocoord,Ttype,Tid,Topstr,Tcoord,Dist])
380            VectA.append(VectB)
381        for Vects in VectA:
382            for i,vecta in enumerate(Vects):                   
383                for vectb in Vects[:i]:
384                    if vecta[3] in Lists['A-atom']:
385                        ids = [vecta[4],vecta[0],vectb[4]]
386                        ops = [vecta[5],vecta[1],vectb[5]]
387                        angle = [ids,ops,value,1.0]
388                        if angle not in angleRestData['Angles']:
389                            angleRestData['Angles'].append(angle)
390        UpdateAngleRestr(angleRestData)               
391
392    def AddAAAngleRestraint(angleRestData):
393        macro = getMacroFile('angle')
394        if not macro:
395            return
396        atoms = zip(Names,Ids)
397        macStr = macro.readline()
398        while macStr:
399            items = macStr.split()
400            if 'F' in items[0]:
401                restrData['Angle']['wtFactor'] = float(items[1])
402            elif 'S' in items[0]:
403                res = items[1]
404                value = float(items[2])
405                esd = float(items[3])
406                Atms = items[4:7]
407                pAtms = ['','','']
408                for i,atm in enumerate(Atms):
409                    if '+' in atm:
410                        pAtms[i] = atm.strip('+')
411                ids = np.array([0,0,0])
412                rNum = -1
413                for name,id in atoms:
414                    names = name.split()
415                    tNum = int(names[0].split(':')[0])
416                    if res in names[0]:
417                        try:
418                            ipos = Atms.index(names[2])
419                            ids[ipos] = id
420                        except ValueError:
421                            continue
422                    elif res == '*':
423                        try:
424                            ipos = Atms.index(names[2])
425                            if not np.all(ids):
426                                rNum = int(names[0].split(':')[0])
427                            ids[ipos] = id
428                        except ValueError:
429                            try:
430                                if tNum == rNum+1:
431                                    ipos = pAtms.index(names[2])
432                                    ids[ipos] = id
433                            except ValueError:
434                                continue
435                    if np.all(ids):
436                        angle = [list(ids),['1','1','1'],value,esd]
437                        if angle not in angleRestData['Angles']:
438                            angleRestData['Angles'].append(angle)
439                        ids = np.array([0,0,0])
440            macStr = macro.readline()
441        macro.close()
442        UpdateAngleRestr(angleRestData)               
443       
444    def AddPlaneRestraint(restrData):
445        ids = []
446        dlg = wx.MultiChoiceDialog(G2frame,'Select 4 or more atoms for plane in '+General['Name'],
447                'Select 4+ atoms',Names[iBeg:])
448        if dlg.ShowModal() == wx.ID_OK:
449            sel = dlg.GetSelections()
450            if len(sel) > 3:
451                for x in sel:
452                    ids.append(Ids[x+iBeg])
453                ops = ['1' for i in range(len(sel))]
454                plane = [ids,ops,0.0,0.01]
455                if plane not in restrData['Planes']:
456                    restrData['Planes'].append(plane)
457            else:
458                print '**** ERROR - not enough atoms for a plane restraint - try again ****'
459        UpdatePlaneRestr(restrData)               
460
461    def AddAAPlaneRestraint(planeRestData):
462        macro = getMacroFile('plane')
463        if not macro:
464            return
465        atoms = zip(Names,Ids)
466        macStr = macro.readline()
467        while macStr:
468            items = macStr.split()
469            if 'F' in items[0]:
470                restrData['Plane']['wtFactor'] = float(items[1])
471            elif 'S' in items[0]:
472                res = items[1]
473                esd = float(items[2])
474                Atms = items[3:]
475                pAtms = ['' for i in Atms]
476                for i,atm in enumerate(Atms):
477                    if '+' in atm:
478                        pAtms[i] = atm.strip('+')
479                rNum = -1
480                ids = np.zeros(len(Atms))
481                ops = ['1' for i in range(len(Atms))]
482                for name,id in atoms:
483                    names = name.split()
484                    tNum = int(names[0].split(':')[0])
485                    if res in names[0]:
486                        try:
487                            ipos = Atms.index(names[2])
488                            ids[ipos] = id
489                        except ValueError:
490                            continue
491                    elif res == '*':
492                        try:
493                            ipos = Atms.index(names[2])
494                            if not np.all(ids):
495                                rNum = int(names[0].split(':')[0])
496                            ids[ipos] = id
497                        except ValueError:
498                            try:
499                                if tNum == rNum+1:
500                                    ipos = pAtms.index(names[2])
501                                    ids[ipos] = id
502                            except ValueError:
503                                continue
504                    if np.all(ids):
505                        plane = [list(ids),ops,0.0,esd]
506                        if plane not in planeRestData['Planes']:
507                            planeRestData['Planes'].append(plane)
508                        ids = np.zeros(len(Atms))
509            macStr = macro.readline()
510        macro.close()
511        UpdatePlaneRestr(planeRestData)               
512
513    def AddAAChiralRestraint(chiralRestData):
514        macro = getMacroFile('chiral')
515        if not macro:
516            return
517        atoms = zip(Names,Ids)
518        macStr = macro.readline()
519        while macStr:
520            items = macStr.split()
521            if 'F' in items[0]:
522                restrData['Chiral']['wtFactor'] = float(items[1])
523            elif 'S' in items[0]:
524                res = items[1]
525                value = float(items[2])
526                esd = float(items[3])
527                Atms = items[4:8]
528                ids = np.array([0,0,0,0])
529                for name,id in atoms:
530                    names = name.split()
531                    if res in names[0]:
532                        try:
533                            ipos = Atms.index(names[2])
534                            ids[ipos] = id
535                        except ValueError:
536                            pass
537                        if np.all(ids):
538                            chiral = [list(ids),['1','1','1','1'],value,esd]
539                            if chiral not in chiralRestData['Volumes']:
540                                chiralRestData['Volumes'].append(chiral)
541                            ids = np.array([0,0,0,0])
542            macStr = macro.readline()
543        macro.close()
544        UpdateChiralRestr(chiralRestData)               
545       
546    def makeChains(Names,Ids):
547        Chains = {}
548        atoms = zip(Names,Ids)
549        for name,id in atoms:
550            items = name.split()
551            rnum,res = items[0].split(':')
552            if items[1] not in Chains:
553                Residues = {}
554                Chains[items[1]] = Residues
555            if int(rnum) not in Residues:
556                Residues[int(rnum)] = []
557            Residues[int(rnum)].append([res,items[2],id])
558        return Chains
559       
560    def AddAATorsionRestraint(torsionRestData):
561        macro = getMacroFile('torsion')
562        if not macro:
563            return
564        Chains = makeChains(Names,Ids)           
565        macStr = macro.readline()[:-1]
566        while macStr:
567            items = macStr.split()
568            if 'F' in items[0]:
569                restrData['Torsion']['wtFactor'] = float(items[1])
570            elif 'A' in items[0]:
571                name = items[10]
572                coeff = np.zeros(9)
573                for i,item in enumerate(items[1:10]):
574                    coeff[i] = float(item)
575                torsionRestData['Coeff'][name] = coeff
576            elif 'S' in items[0]:
577                Name = items[1]
578                Res = items[2]
579                Esd = float(items[3])
580                Atms = items[4:8]
581                pAtms = ['','','','']
582                for i,atm in enumerate(Atms):
583                    if '+' in atm:
584                        pAtms[i] = atm.strip('+')
585                ids = np.array([0,0,0,0])
586                chains = Chains.keys()
587                chains.sort()
588                for chain in chains:
589                    residues = Chains[chain].keys()
590                    residues.sort()
591                    for residue in residues:
592                        if residue == residues[-1] and Res == '*':
593                            continue
594                        if Res != '*':
595                            for res,name,id in Chains[chain][residue]:
596                                if Res == res:
597                                    try:
598                                        ipos = Atms.index(name)
599                                        ids[ipos] = id
600                                    except ValueError:
601                                        continue
602                        else:
603                            try:
604                                for res,name,id in Chains[chain][residue]:
605                                    try:
606                                        ipos = Atms.index(name)
607                                        ids[ipos] = id
608                                    except ValueError:
609                                        continue
610                                for res,name,id in Chains[chain][residue+1]:
611                                    try:
612                                        ipos = pAtms.index(name)
613                                        ids[ipos] = id
614                                    except ValueError:
615                                        continue
616                            except KeyError:
617                                continue
618                        if np.all(ids):
619                            torsion = [list(ids),['1','1','1','1'],Name,Esd]
620                            if torsion not in torsionRestData['Torsions']:
621                                torsionRestData['Torsions'].append(torsion)
622                            ids = np.array([0,0,0,0])                           
623            macStr = macro.readline()
624        macro.close()
625        UpdateTorsionRestr(torsionRestData)                       
626       
627    def AddAARamaRestraint(ramaRestData):
628        macro = getMacroFile('Ramachandran')
629        if not macro:
630            return
631        Chains = makeChains(Names,Ids)           
632        macStr = macro.readline()
633        while macStr:
634            items = macStr.split()
635            if 'F' in items[0]:
636                restrData['Rama']['wtFactor'] = float(items[1])
637            elif 'A' in items[0]:
638                nTerms = int(items[1])
639                name = items[2]
640                coeff = np.zeros((nTerms,6))
641                for i in range(nTerms):
642                    macStr = macro.readline()
643                    items = macStr.split()
644                    for j,val in enumerate(items):
645                        coeff[i][j] = float(val)
646                ramaRestData['Coeff'][name] = coeff
647            elif 'S' in items[0]:
648                Name = items[1]
649                Res = items[2]
650                Esd = float(items[3])
651                Atms = items[4:9]
652                mAtms = ['','','','','']
653                pAtms = ['','','','','']
654                for i,atm in enumerate(Atms):
655                    if '+' in atm:
656                        pAtms[i] = atm.strip('+')
657                    elif '-' in atm:
658                        mAtms[i] = atm.strip('-')
659                ids = np.array([0,0,0,0,0])
660                chains = Chains.keys()
661                chains.sort()
662                for chain in chains:
663                    residues = Chains[chain].keys()
664                    residues.sort()
665                    if not (any(mAtms) or any(pAtms)):
666                        for residue in residues:
667                            for res,name,id in Chains[chain][residue]:
668                                if Res == res:
669                                    try:
670                                        ipos = Atms.index(name)
671                                        ids[ipos] = id
672                                    except ValueError:
673                                        continue
674                            if np.all(ids):
675                                rama = [list(ids),['1','1','1','1','1'],Name,Esd]
676                                if rama not in ramaRestData['Ramas']:
677                                    ramaRestData['Ramas'].append(rama)
678                                ids = np.array([0,0,0,0,0])
679                    else:
680                        for residue in residues[1:-1]:
681                            try:
682                                for res,name,id in Chains[chain][residue-1]:
683                                    try:
684                                        ipos = mAtms.index(name)
685                                        ids[ipos] = id
686                                    except ValueError:
687                                        continue
688                                for res,name,id in Chains[chain][residue+1]:
689                                    try:
690                                        ipos = pAtms.index(name)
691                                        ids[ipos] = id
692                                    except ValueError:
693                                        continue
694                                for res,name,id in Chains[chain][residue]:
695                                    if Res == res:
696                                        try:
697                                            ipos = Atms.index(name)
698                                            ids[ipos] = id
699                                        except ValueError:
700                                            continue
701                                if np.all(ids):
702                                    rama = [list(ids),['1','1','1','1','1'],Name,Esd]
703                                    if rama not in ramaRestData['Ramas']:
704                                        ramaRestData['Ramas'].append(rama)
705                                    ids = np.array([0,0,0,0,0])
706                            except KeyError:
707                                continue
708            macStr = macro.readline()
709        macro.close()
710        UpdateRamaRestr(ramaRestData)
711       
712    def AddChemCompRestraint(chemcompRestData):
713        ids = []
714        factors = []
715        dlg = wx.MultiChoiceDialog(G2frame,'Select atoms for chemical restraint in '+General['Name'],
716                'Select atoms',Names)
717        if dlg.ShowModal() == wx.ID_OK:
718            sel = dlg.GetSelections()
719            for x in sel:
720                if 'all' in Names[x]:
721                    allType = Types[x]
722                    for name,Type,id in zip(Names,Types,Ids):
723                        if Type == allType and 'all' not in name:
724                            ids.append(id)
725                            factors.append(1.0)
726                else:
727                    ids.append(Ids[x])
728                    factors.append(1.0)
729            dlg.Destroy()
730            if len(ids) > 0:
731                value = 1.0
732                dlg = G2G.SingleFloatDialog(G2frame,'Angle','Enter unit cell sum ',value,[-1.e6,1.e6],'%.2f')
733                if dlg.ShowModal() == wx.ID_OK:
734                    value = dlg.GetValue()               
735                    comp = [ids,factors,value,0.01]
736                    if comp not in chemcompRestData['Sites']:
737                        chemcompRestData['Sites'].append(comp)
738                UpdateChemcompRestr(chemcompRestData)
739            else:
740                print '**** ERROR - not enough atoms for a composition restraint - try again ****'
741       
742    def AddTextureRestraint(textureRestData):
743        dlg = wx.TextEntryDialog(G2frame,'Enter h k l for pole figure restraint','Enter HKL','')
744        if dlg.ShowModal() == wx.ID_OK:
745            text = dlg.GetValue()
746            vals = text.split()
747            try:
748                hkl = [int(vals[i]) for i in range(3)]
749                texture = [hkl,24,0.01,False,1.0]
750                if texture not in textureRestData['HKLs']:
751                        textureRestData['HKLs'].append(texture)
752                UpdateTextureRestr(textureRestData)
753            except (ValueError,IndexError):
754                print '**** ERROR - bad input of h k l - try again ****'
755        dlg.Destroy()
756               
757    def WtBox(wind,restData):
758        if 'Range' not in restData: restData['Range'] = 1.1     #patch
759       
760        def OnUseData(event):
761            Obj = event.GetEventObject()
762            restData['Use'] = Obj.GetValue()
763
764        wtBox = wx.BoxSizer(wx.HORIZONTAL)
765        wtBox.Add(wx.StaticText(wind,-1,'Restraint weight factor: '),0,wx.ALIGN_CENTER_VERTICAL)
766        wtfactor = G2G.ValidatedTxtCtrl(wind,restData,'wtFactor',nDig=(10,2),typeHint=float)
767        wtBox.Add(wtfactor,0,wx.ALIGN_CENTER_VERTICAL)
768        useData = wx.CheckBox(wind,-1,label=' Use?')
769        useData.Bind(wx.EVT_CHECKBOX, OnUseData)
770        useData.SetValue(restData['Use'])       
771        wtBox.Add(useData,0,wx.ALIGN_CENTER_VERTICAL)
772        if 'Bonds' in restData or 'Angles' in restData:
773            wtBox.Add(wx.StaticText(wind,-1,'  Search range: '),0,wx.ALIGN_CENTER_VERTICAL)
774            sRange = G2G.ValidatedTxtCtrl(wind,restData,'Range',nDig=(10,2),typeHint=float)
775            wtBox.Add(sRange,0,wx.ALIGN_CENTER_VERTICAL)
776            wtBox.Add(wx.StaticText(wind,-1,' x sum(atom radii)'),0,wx.ALIGN_CENTER_VERTICAL)
777        return wtBox
778       
779    def OnRowSelect(event):
780        r,c =  event.GetRow(),event.GetCol()
781        Obj = event.GetEventObject()
782        if r < 0 and c < 0:
783            if Obj.IsSelection():
784                Obj.ClearSelection()
785            else:
786                for row in range(Obj.GetNumberRows()):
787                    Obj.SelectRow(row,True)
788        elif c < 0:                   #only row clicks
789            if event.ControlDown():                   
790                if r in Obj.GetSelectedRows():
791                    Obj.DeselectRow(r)
792                else:
793                    Obj.SelectRow(r,True)
794            elif event.ShiftDown():
795                indxs = Obj.GetSelectedRows()
796                Obj.ClearSelection()
797                ibeg = 0
798                if indxs:
799                    ibeg = indxs[-1]
800                for row in range(ibeg,r+1):
801                    Obj.SelectRow(row,True)
802            else:
803                Obj.ClearSelection()
804                Obj.SelectRow(r,True)
805               
806                   
807    def UpdateBondRestr(bondRestData):
808       
809        def OnCellChange(event):
810            r,c =  event.GetRow(),event.GetCol()
811            try:
812                new = float(bondTable.GetValue(r,c))
813                if new <= 0.:
814                    raise ValueError
815                bondRestData['Bonds'][r][c] = new
816            except ValueError:
817                pass           
818            wx.CallAfter(UpdateBondRestr,bondRestData)               
819
820        def OnChangeValue(event):
821            rows = GetSelectedRows(Bonds)
822            if not rows:
823                return
824            Bonds.ClearSelection()
825            val = bondList[rows[0]][2]
826            dlg = G2G.SingleFloatDialog(G2frame,'New value','Enter new value for bond',val,[0.,5.],'%.4f')
827            if dlg.ShowModal() == wx.ID_OK:
828                parm = dlg.GetValue()
829                for r in rows:
830                    bondRestData['Bonds'][r][2] = parm
831            dlg.Destroy()
832            UpdateBondRestr(bondRestData)               
833
834        def OnChangeEsd(event):
835            rows = GetSelectedRows(Bonds)
836            if not rows:
837                return
838            Bonds.ClearSelection()
839            val = bondList[rows[0]][3]
840            dlg = G2G.SingleFloatDialog(G2frame,'New value','Enter new esd for bond',val,[0.,1.],'%.4f')
841            if dlg.ShowModal() == wx.ID_OK:
842                parm = dlg.GetValue()
843                for r in rows:
844                    bondRestData['Bonds'][r][3] = parm
845            dlg.Destroy()
846            UpdateBondRestr(bondRestData)               
847                               
848        def OnDeleteRestraint(event):
849            rows = GetSelectedRows(Bonds)
850            if not rows:
851                return
852            Bonds.ClearSelection()
853            rows.sort()
854            rows.reverse()
855            for row in rows:
856                bondList.remove(bondList[row])
857            UpdateBondRestr(bondRestData)               
858           
859        BondRestr.DestroyChildren()
860#        if BondRestr.GetSizer():
861#            BondRestr.GetSizer().Clear(True)
862        mainSizer = wx.BoxSizer(wx.VERTICAL)
863        mainSizer.Add((5,5),0)
864        mainSizer.Add(WtBox(BondRestr,bondRestData),0,wx.ALIGN_CENTER_VERTICAL)
865
866        bondList = bondRestData['Bonds']
867        if len(bondList) and len(bondList[0]) == 6:   #patch
868            bondList = bondRestData['Bonds'] = []
869        if len(bondList):
870            table = []
871            rowLabels = []
872            bad = []
873            chisq = 0.
874            Types = [wg.GRID_VALUE_STRING,]+4*[wg.GRID_VALUE_FLOAT+':10,3',]
875            if 'macro' in General['Type']:
876                colLabels = ['(res) A - (res) B','calc','target','esd','delt/sig']
877                for i,[indx,ops,obs,esd] in enumerate(bondList):
878                    try:
879                        atoms = G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,0,4)
880                        name = ''
881                        for atom in atoms:
882                            name += '('+atom[1]+atom[0].strip()+atom[2]+') '+atom[3]+' - '
883                        XYZ = np.array(G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,cx,3))
884                        calc = G2mth.getRestDist(XYZ,Amat)
885                        chisq += bondRestData['wtFactor']*((obs-calc)/esd)**2
886                        table.append([name[:-3],calc,obs,esd,(obs-calc)/esd])
887                        rowLabels.append(str(i))               
888                    except KeyError:
889                        print '**** WARNING - missing atom - restraint deleted ****'
890                        bad.append(i)
891            else:
892                colLabels = ['A+SymOp - B+SymOp','calc','target','esd','delt/sig']
893                for i,[indx,ops,obs,esd] in enumerate(bondList):
894                    try:
895                        names = G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,ct-1)
896                        XYZ = np.array(G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,cx,3))
897                        XYZ = G2mth.getSyXYZ(XYZ,ops,SGData)
898                        calc = G2mth.getRestDist(XYZ,Amat)
899                        chisq += bondRestData['wtFactor']*((obs-calc)/esd)**2
900                        table.append([names[0]+'+('+ops[0]+') - '+names[1]+'+('+ops[1]+')',calc,obs,esd,(obs-calc)/esd])
901                        rowLabels.append(str(i))
902                    except KeyError:
903                        print '**** WARNING - missing atom - restraint deleted ****'
904                        bad.append(i)
905            if len(bad):
906                bad.reverse()
907                for ibad in bad:
908                    del bondList[ibad]
909            if len(bondList):
910                bondTable = G2G.Table(table,rowLabels=rowLabels,colLabels=colLabels,types=Types)
911                Bonds = G2G.GSGrid(BondRestr)
912                Bonds.SetTable(bondTable, True)
913                Bonds.AutoSizeColumns(False)
914                for r in range(len(bondList)):
915                    for c in [0,1,4]:
916                        Bonds.SetReadOnly(r,c,True)
917                        Bonds.SetCellStyle(r,c,VERY_LIGHT_GREY,True)
918                Bonds.Bind(wg.EVT_GRID_LABEL_LEFT_CLICK,OnRowSelect)
919                Bonds.Bind(wg.EVT_GRID_CELL_CHANGE, OnCellChange)
920                G2frame.dataFrame.Bind(wx.EVT_MENU, OnDeleteRestraint, id=G2gd.wxID_RESTDELETE)
921                G2frame.dataFrame.Bind(wx.EVT_MENU, OnChangeValue, id=G2gd.wxID_RESRCHANGEVAL)
922                G2frame.dataFrame.Bind(wx.EVT_MENU, OnChangeEsd, id=G2gd.wxID_RESTCHANGEESD)
923                mainSizer.Add(wx.StaticText(BondRestr,-1,
924                    'Bond restraints: sum(wt*(delt/sig)^2) =    %.2f, mean(wt*(delt/sig)^2) =    %.2f'    \
925                    %(chisq,chisq/len(bondList))),0,wx.ALIGN_CENTER_VERTICAL)
926                mainSizer.Add(Bonds,0,)
927            else:
928                mainSizer.Add(wx.StaticText(BondRestr,-1,'No bond distance restraints for this phase'),0,)
929        else:
930            mainSizer.Add(wx.StaticText(BondRestr,-1,'No bond distance restraints for this phase'),0,)
931
932        BondRestr.SetSizer(mainSizer)
933        Size = mainSizer.Fit(BondRestr)
934        Size[0] = 600
935        Size[1] = min(Size[1]+50,500)       #make room for tab, but not too big
936        BondRestr.SetSize(Size)
937        BondRestr.SetScrollbars(10,10,Size[0]/10-4,Size[1]/10-1)
938       
939    def UpdateAngleRestr(angleRestData):
940       
941        def OnCellChange(event):
942            r,c =  event.GetRow(),event.GetCol()
943            try:
944                new = float(angleTable.GetValue(r,c))
945                if new <= 0. or new > 180.:
946                    raise ValueError
947                angleRestData['Angles'][r][c] = new
948            except ValueError:
949                pass           
950            wx.CallAfter(UpdateAngleRestr,angleRestData)               
951           
952        def OnChangeValue(event):
953            rows = GetSelectedRows(Angles)
954            if not rows:
955                return
956            Angles.ClearSelection()
957            val = angleList[rows[0]][2]
958            dlg = G2G.SingleFloatDialog(G2frame,'New value','Enter new value for angle',val,[0.,360.],'%.2f')
959            if dlg.ShowModal() == wx.ID_OK:
960                parm = dlg.GetValue()
961                for r in rows:
962                    angleRestData['Angles'][r][2] = parm
963            dlg.Destroy()
964            UpdateAngleRestr(angleRestData)               
965
966        def OnChangeEsd(event):
967            rows = GetSelectedRows(Angles)
968            if not rows:
969                return
970            Angles.ClearSelection()
971            val = angleList[rows[0]][3]
972            dlg = G2G.SingleFloatDialog(G2frame,'New value','Enter new esd for angle',val,[0.,5.],'%.2f')
973            if dlg.ShowModal() == wx.ID_OK:
974                parm = dlg.GetValue()
975                for r in rows:
976                    angleRestData['Angles'][r][3] = parm
977            dlg.Destroy()
978            UpdateAngleRestr(angleRestData)               
979                                           
980        def OnDeleteRestraint(event):
981            rows = GetSelectedRows(Angles)
982            if not rows:
983                return
984            rows.sort()
985            rows.reverse()
986            for row in rows:
987                angleList.remove(angleList[row])
988            UpdateAngleRestr(angleRestData)               
989           
990        AngleRestr.DestroyChildren()
991#        if AngleRestr.GetSizer():
992#            AngleRestr.GetSizer().Clear(True)
993        mainSizer = wx.BoxSizer(wx.VERTICAL)
994        mainSizer.Add((5,5),0)
995        mainSizer.Add(WtBox(AngleRestr,angleRestData),0,wx.ALIGN_CENTER_VERTICAL)
996
997        angleList = angleRestData['Angles']
998        if len(angleList):
999            table = []
1000            rowLabels = []
1001            bad = []
1002            chisq = 0.
1003            Types = [wg.GRID_VALUE_STRING,]+4*[wg.GRID_VALUE_FLOAT+':10,2',]
1004            if 'macro' in General['Type']:
1005                colLabels = ['(res) A - (res) B - (res) C','calc','target','esd','delt/sig']
1006                for i,[indx,ops,obs,esd] in enumerate(angleList):
1007                    try:
1008                        atoms = G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,0,4)
1009                        name = ''
1010                        for atom in atoms:
1011                            name += '('+atom[1]+atom[0].strip()+atom[2]+') '+atom[3]+' - '
1012                        XYZ = np.array(G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,cx,3))
1013                        calc = G2mth.getRestAngle(XYZ,Amat)
1014                        chisq += angleRestData['wtFactor']*((obs-calc)/esd)**2
1015                        table.append([name[:-3],calc,obs,esd,(obs-calc)/esd])
1016                        rowLabels.append(str(i))                               
1017                    except KeyError:
1018                        print '**** WARNING - missing atom - restraint deleted ****'
1019                        bad.append(i)
1020            else:
1021                colLabels = ['A+SymOp - B+SymOp - C+SymOp','calc','target','esd','delt/sig']
1022                for i,[indx,ops,obs,esd] in enumerate(angleList):
1023                    try:
1024                        atoms = G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,ct-1)
1025                        name = atoms[0]+'+('+ops[0]+') - '+atoms[1]+'+('+ops[1]+') - '+atoms[2]+ \
1026                        '+('+ops[2]+')'
1027                        XYZ = np.array(G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,cx,3))
1028                        XYZ = G2mth.getSyXYZ(XYZ,ops,SGData)
1029                        calc = G2mth.getRestAngle(XYZ,Amat)
1030                        chisq += angleRestData['wtFactor']*((obs-calc)/esd)**2
1031                        table.append([name,calc,obs,esd,(obs-calc)/esd])
1032                        rowLabels.append(str(i))
1033                    except KeyError:
1034                        print '**** WARNING - missing atom - restraint deleted ****'
1035                        bad.append(i)
1036            if len(bad):
1037                bad.reverse()
1038                for ibad in bad:
1039                    del angleList[ibad]
1040            if len(angleList):
1041                angleTable = G2G.Table(table,rowLabels=rowLabels,colLabels=colLabels,types=Types)
1042                Angles = G2G.GSGrid(AngleRestr)
1043                Angles.SetTable(angleTable, True)
1044                Angles.AutoSizeColumns(False)
1045                for r in range(len(angleList)):
1046                    for c in [0,1,4]:
1047                        Angles.SetReadOnly(r,c,True)
1048                        Angles.SetCellStyle(r,c,VERY_LIGHT_GREY,True)
1049                Angles.Bind(wg.EVT_GRID_LABEL_LEFT_CLICK,OnRowSelect)
1050                Angles.Bind(wg.EVT_GRID_CELL_CHANGE, OnCellChange)
1051                G2frame.dataFrame.Bind(wx.EVT_MENU, OnDeleteRestraint, id=G2gd.wxID_RESTDELETE)
1052                G2frame.dataFrame.Bind(wx.EVT_MENU, OnChangeValue, id=G2gd.wxID_RESRCHANGEVAL)
1053                G2frame.dataFrame.Bind(wx.EVT_MENU, OnChangeEsd, id=G2gd.wxID_RESTCHANGEESD)
1054                mainSizer.Add(wx.StaticText(AngleRestr,-1,
1055                    'Angle restraints: sum(wt*(delt/sig)^2) =    %.2f, mean(wt*(delt/sig)^2) =    %.2f'    \
1056                    %(chisq,chisq/len(angleList))),0,wx.ALIGN_CENTER_VERTICAL)
1057                mainSizer.Add(Angles,0,)
1058            else:
1059                mainSizer.Add(wx.StaticText(AngleRestr,-1,'No bond angle restraints for this phase'),0,)
1060        else:
1061            mainSizer.Add(wx.StaticText(AngleRestr,-1,'No bond angle restraints for this phase'),0,)
1062
1063        AngleRestr.SetSizer(mainSizer)
1064        Size = mainSizer.Fit(AngleRestr)
1065        Size[0] = 600
1066        Size[1] = min(Size[1]+50,500)       #make room for tab, but not too big
1067        AngleRestr.SetSize(Size)
1068        AngleRestr.SetScrollbars(10,10,Size[0]/10-4,Size[1]/10-1)
1069   
1070    def UpdatePlaneRestr(planeRestData):
1071       
1072        items = G2frame.dataFrame.RestraintEdit.GetMenuItems()
1073        for item in items:
1074            if item.GetLabel() in ['Change value']:
1075                item.Enable(False)
1076
1077        def OnCellChange(event):
1078            r,c =  event.GetRow(),event.GetCol()
1079            try:
1080                new = float(planeTable.GetValue(r,c))
1081                if new <= 0.:
1082                    raise ValueError
1083                planeRestData['Planes'][r][c] = new
1084            except ValueError:
1085                pass           
1086            wx.CallAfter(UpdatePlaneRestr,planeRestData)               
1087           
1088        def OnChangeEsd(event):
1089            rows = GetSelectedRows(Planes)
1090            if not rows:
1091                return
1092            Planes.ClearSelection()
1093            val = planeList[rows[0]][3]
1094            dlg = G2G.SingleFloatDialog(G2frame,'New value','Enter new esd for plane',val,[0.,5.],'%.2f')
1095            if dlg.ShowModal() == wx.ID_OK:
1096                parm = dlg.GetValue()
1097                for r in rows:
1098                    planeRestData['Planes'][r][3] = parm
1099            dlg.Destroy()
1100            UpdatePlaneRestr(planeRestData)               
1101                                           
1102        def OnDeleteRestraint(event):
1103            rows = GetSelectedRows(Planes)
1104            if not rows:
1105                return
1106            rows.sort()
1107            rows.reverse()
1108            for row in rows:
1109                planeList.remove(planeList[row])
1110            UpdatePlaneRestr(planeRestData)               
1111           
1112        PlaneRestr.DestroyChildren()
1113#        if PlaneRestr.GetSizer():
1114#            PlaneRestr.GetSizer().Clear(True)
1115        mainSizer = wx.BoxSizer(wx.VERTICAL)
1116        mainSizer.Add((5,5),0)
1117        mainSizer.Add(WtBox(PlaneRestr,planeRestData),0,wx.ALIGN_CENTER_VERTICAL)
1118
1119        planeList = planeRestData['Planes']
1120        if len(planeList):
1121            table = []
1122            rowLabels = []
1123            bad = []
1124            chisq = 0.
1125            Types = [wg.GRID_VALUE_STRING,]+3*[wg.GRID_VALUE_FLOAT+':10,2',]
1126            if 'macro' in General['Type']:
1127                colLabels = ['(res) atom','calc','target','esd']
1128                for i,[indx,ops,obs,esd] in enumerate(planeList):
1129                    try:
1130                        atoms = G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,0,4)
1131                        name = ''
1132                        for a,atom in enumerate(atoms):
1133                            name += '('+atom[1]+atom[0].strip()+atom[2]+') '+atom[3]+' - '
1134                            if (a+1)%3 == 0:
1135                                name += '\n'
1136                        XYZ = np.array(G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,cx,3))
1137                        calc = G2mth.getRestPlane(XYZ,Amat)
1138                        chisq += planeRestData['wtFactor']*((calc)/esd)**2
1139                        table.append([name[:-3],calc,obs,esd])
1140                        rowLabels.append(str(i))
1141                    except KeyError:
1142                        print '**** WARNING - missing atom - restraint deleted ****'
1143                        bad.append(i)
1144            else:                               
1145                colLabels = ['atom+SymOp','calc','target','esd']
1146                for i,[indx,ops,obs,esd] in enumerate(planeList):
1147                    try:
1148                        atoms = G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,ct-1)
1149                        XYZ = np.array(G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,cx,3))
1150                        XYZ = G2mth.getSyXYZ(XYZ,ops,SGData)
1151                        calc = G2mth.getRestPlane(XYZ,Amat)
1152                        chisq += planeRestData['wtFactor']*((calc)/esd)**2
1153                        name = ''
1154                        for a,atom in enumerate(atoms):
1155                            name += atom+'+ ('+ops[a]+'),'
1156                            if (a+1)%3 == 0:
1157                                name += '\n'
1158                        table.append([name[:-1],calc,obs,esd])
1159                        rowLabels.append(str(i))
1160                    except KeyError:
1161                        print '**** WARNING - missing atom - restraint deleted ****'
1162                        bad.append(i)
1163            if len(bad):
1164                bad.reverse()
1165                for ibad in bad:
1166                    del planeList[ibad]
1167            if len(planeList):
1168                planeTable = G2G.Table(table,rowLabels=rowLabels,colLabels=colLabels,types=Types)
1169                Planes = G2G.GSGrid(PlaneRestr)
1170                Planes.SetTable(planeTable, True)
1171                Planes.AutoSizeColumns(False)
1172                Planes.AutoSizeRows(False)
1173                for r in range(len(planeList)):
1174                    for c in range(3):
1175                        Planes.SetReadOnly(r,c,True)
1176                        Planes.SetCellStyle(r,c,VERY_LIGHT_GREY,True)
1177                Planes.Bind(wg.EVT_GRID_LABEL_LEFT_CLICK,OnRowSelect)
1178                Planes.Bind(wg.EVT_GRID_CELL_CHANGE, OnCellChange)
1179                G2frame.dataFrame.Bind(wx.EVT_MENU, OnDeleteRestraint, id=G2gd.wxID_RESTDELETE)
1180                G2frame.dataFrame.Bind(wx.EVT_MENU, OnChangeEsd, id=G2gd.wxID_RESTCHANGEESD)
1181                mainSizer.Add(wx.StaticText(PlaneRestr,-1,
1182                    'Plane restraints: sum(wt*(delt/sig)^2) =    %.2f, mean(wt*(delt/sig)^2) =    %.2f'    \
1183                    %(chisq,chisq/len(planeList))),0,wx.ALIGN_CENTER_VERTICAL)
1184                mainSizer.Add(Planes,0,)
1185            else:
1186                mainSizer.Add(wx.StaticText(PlaneRestr,-1,'No plane restraints for this phase'),0,)
1187        else:
1188            mainSizer.Add(wx.StaticText(PlaneRestr,-1,'No plane restraints for this phase'),0,)
1189
1190        PlaneRestr.SetSizer(mainSizer)
1191        Size = mainSizer.Fit(PlaneRestr)
1192        Size[0] = 600
1193        Size[1] = min(Size[1]+50,500)       #make room for tab, but not too big
1194        PlaneRestr.SetSize(Size)
1195        PlaneRestr.SetScrollbars(10,10,Size[0]/10-4,Size[1]/10-1)
1196   
1197    def UpdateChiralRestr(chiralRestData):
1198
1199        def OnCellChange(event):
1200            r,c =  event.GetRow(),event.GetCol()
1201            try:
1202                new = float(volumeTable.GetValue(r,c))
1203                if new <= 0.:
1204                    raise ValueError
1205                chiralRestData['Volumes'][r][c] = new
1206            except ValueError:
1207                pass           
1208            wx.CallAfter(UpdateChiralRestr,chiralRestData)               
1209           
1210        def OnDeleteRestraint(event):
1211            rows = GetSelectedRows(Volumes)
1212            if not rows:
1213                return
1214            rows.sort()
1215            rows.reverse()
1216            for row in rows:
1217                volumeList.remove(volumeList[row])
1218            UpdateChiralRestr(chiralRestData)               
1219           
1220        def OnChangeValue(event):
1221            rows = GetSelectedRows(Volumes)
1222            if not rows:
1223                return
1224            Volumes.ClearSelection()
1225            val = volumeList[rows[0]][2]
1226            dlg = G2G.SingleFloatDialog(G2frame,'New value','Enter new value for chiral volume',val,[0.,360.],'%.2f')
1227            if dlg.ShowModal() == wx.ID_OK:
1228                parm = dlg.GetValue()
1229                for r in rows:
1230                    chiralRestData['Volumes'][r][2] = parm
1231            dlg.Destroy()
1232            UpdateChiralRestr(chiralRestData)               
1233
1234        def OnChangeEsd(event):
1235            rows = GetSelectedRows(Volumes)
1236            if not rows:
1237                return
1238            Volumes.ClearSelection()
1239            val = volumeList[rows[0]][3]
1240            dlg = G2G.SingleFloatDialog(G2frame,'New value','Enter new esd for chiral volume',val,[0.,5.],'%.2f')
1241            if dlg.ShowModal() == wx.ID_OK:
1242                parm = dlg.GetValue()
1243                for r in rows:
1244                    chiralRestData['Volumes'][r][3] = parm
1245            dlg.Destroy()
1246            UpdateChiralRestr(chiralRestData)               
1247                                           
1248        ChiralRestr.DestroyChildren()
1249#        if ChiralRestr.GetSizer():
1250#            ChiralRestr.GetSizer().Clear(True)
1251        mainSizer = wx.BoxSizer(wx.VERTICAL)
1252        mainSizer.Add((5,5),0)
1253        mainSizer.Add(WtBox(ChiralRestr,chiralRestData),0,wx.ALIGN_CENTER_VERTICAL)
1254
1255        volumeList = chiralRestData['Volumes']
1256        if len(volumeList):
1257            table = []
1258            rowLabels = []
1259            bad = []
1260            chisq = 0.
1261            Types = [wg.GRID_VALUE_STRING,]+4*[wg.GRID_VALUE_FLOAT+':10,2',]
1262            if 'macro' in General['Type']:
1263                colLabels = ['(res) O (res) A (res) B (res) C','calc','target','esd','delt/sig']
1264                for i,[indx,ops,obs,esd] in enumerate(volumeList):
1265                    try:
1266                        atoms = G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,0,4)
1267                        name = ''
1268                        for atom in atoms:
1269                            name += '('+atom[1]+atom[0].strip()+atom[2]+') '+atom[3]+' '
1270                        XYZ = np.array(G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,cx,3))
1271                        calc = G2mth.getRestChiral(XYZ,Amat)
1272                        chisq += chiralRestData['wtFactor']*((obs-calc)/esd)**2
1273                        table.append([name,calc,obs,esd,(obs-calc)/esd])
1274                        rowLabels.append(str(i))
1275                    except KeyError:
1276                        print '**** WARNING - missing atom - restraint deleted ****'
1277                        bad.append(i)
1278            else:
1279                colLabels = ['O+SymOp  A+SymOp  B+SymOp  C+SymOp)','calc','target','esd','delt/sig']
1280                for i,[indx,ops,obs,esd] in enumerate(volumeList):
1281                    try:
1282                        atoms = G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,ct-1)
1283                        name = atoms[0]+'+('+ops[0]+') '+atoms[1]+'+('+ops[1]+') '+atoms[2]+ \
1284                            '+('+ops[2]+') '+atoms[3]+'+('+ops[3]+')'
1285                        XYZ = np.array(G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,cx,3))
1286                        XYZ = G2mth.getSyXYZ(XYZ,ops,SGData)
1287                        calc = G2mth.getRestChiral(XYZ,Amat)
1288                        chisq += chiralRestData['wtFactor']*((obs-calc)/esd)**2
1289                        table.append([name,calc,obs,esd,(obs-calc)/esd])
1290                        rowLabels.append(str(i))
1291                    except KeyError:
1292                        print '**** WARNING - missing atom - restraint deleted ****'
1293                        bad.append(i)
1294            if len(bad):
1295                bad.reverse()
1296                for ibad in bad:
1297                    del volumeList[ibad]
1298            if len(volumeList):
1299                volumeTable = G2G.Table(table,rowLabels=rowLabels,colLabels=colLabels,types=Types)
1300                Volumes = G2G.GSGrid(ChiralRestr)
1301                Volumes.SetTable(volumeTable, True)
1302                Volumes.AutoSizeColumns(False)
1303                for r in range(len(volumeList)):
1304                    for c in [0,1,4]:
1305                        Volumes.SetReadOnly(r,c,True)
1306                        Volumes.SetCellStyle(r,c,VERY_LIGHT_GREY,True)
1307                Volumes.Bind(wg.EVT_GRID_LABEL_LEFT_CLICK,OnRowSelect)
1308                Volumes.Bind(wg.EVT_GRID_CELL_CHANGE, OnCellChange)
1309                G2frame.dataFrame.Bind(wx.EVT_MENU, OnDeleteRestraint, id=G2gd.wxID_RESTDELETE)
1310                G2frame.dataFrame.Bind(wx.EVT_MENU, OnChangeValue, id=G2gd.wxID_RESRCHANGEVAL)
1311                G2frame.dataFrame.Bind(wx.EVT_MENU, OnChangeEsd, id=G2gd.wxID_RESTCHANGEESD)
1312                mainSizer.Add(wx.StaticText(ChiralRestr,-1,
1313                    'Chiral volume restraints: sum(wt*(delt/sig)^2) =    %.2f, mean(wt*(delt/sig)^2) =    %.2f'    \
1314                    %(chisq,chisq/len(volumeList))),0,wx.ALIGN_CENTER_VERTICAL)
1315                mainSizer.Add(Volumes,0,)
1316            else:
1317                mainSizer.Add(wx.StaticText(ChiralRestr,-1,'No chiral volume restraints for this phase'),0,)
1318        else:
1319            mainSizer.Add(wx.StaticText(ChiralRestr,-1,'No chiral volume restraints for this phase'),0,)
1320
1321        ChiralRestr.SetSizer(mainSizer)
1322        Size = mainSizer.Fit(ChiralRestr)
1323        Size[0] = 600
1324        Size[1] = min(Size[1]+50,500)       #make room for tab, but not too big
1325        ChiralRestr.SetSize(Size)
1326        ChiralRestr.SetScrollbars(10,10,Size[0]/10-4,Size[1]/10-1)
1327   
1328    def UpdateTorsionRestr(torsionRestData):
1329
1330        def OnCellChange(event):
1331            r,c =  event.GetRow(),event.GetCol()
1332            try:
1333                new = float(torsionTable.GetValue(r,c))
1334                if new <= 0. or new > 5.:
1335                    raise ValueError
1336                torsionRestData['Torsions'][r][3] = new     #only esd is editable
1337            except ValueError:
1338                pass           
1339            wx.CallAfter(UpdateTorsionRestr,torsionRestData)               
1340           
1341        def OnDeleteRestraint(event):
1342            rows = GetSelectedRows(TorsionRestr.Torsions)
1343            if not rows:
1344                return
1345            rows.sort()
1346            rows.reverse()
1347            for row in rows:
1348                torsionList.remove(torsionList[row])
1349            wx.CallAfter(UpdateTorsionRestr,torsionRestData)               
1350           
1351        def OnChangeEsd(event):
1352            rows = GetSelectedRows(TorsionRestr.Torsions)
1353            if not rows:
1354                return
1355            TorsionRestr.Torsions.ClearSelection()
1356            val = torsionList[rows[0]][4]
1357            dlg = G2G.SingleFloatDialog(G2frame,'New value','Enter new esd for torsion restraints',val,[0.,5.],'%.2f')
1358            if dlg.ShowModal() == wx.ID_OK:
1359                parm = dlg.GetValue()
1360                for r in rows:
1361                    torsionRestData['Torsions'][r][4] = parm
1362            dlg.Destroy()
1363            wx.CallAfter(UpdateTorsionRestr,torsionRestData)               
1364                                           
1365        TorsionRestr.DestroyChildren()
1366#        if TorsionRestr.GetSizer():
1367#            TorsionRestr.GetSizer().Clear(True)
1368        mainSizer = wx.BoxSizer(wx.VERTICAL)
1369        mainSizer.Add((5,5),0)
1370        mainSizer.Add(WtBox(TorsionRestr,torsionRestData),0,wx.ALIGN_CENTER_VERTICAL)
1371       
1372        coeffDict = torsionRestData['Coeff']
1373        torsionList = torsionRestData['Torsions']
1374        if len(torsionList):
1375            table = []
1376            rowLabels = []
1377            bad = []
1378            chisq = 0.
1379            Types = 2*[wg.GRID_VALUE_STRING,]+4*[wg.GRID_VALUE_FLOAT+':10,2',]
1380            if 'macro' in General['Type']:
1381                colLabels = ['(res) A  B  C  D','coef name','torsion','obs E','restr','esd']
1382                for i,[indx,ops,cofName,esd] in enumerate(torsionList):
1383                    try:
1384                        atoms = G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,0,4)
1385                        name = '('+atoms[2][1]+atoms[2][0].strip()+atoms[2][2]+')'
1386                        for atom in atoms:
1387                            name += '  '+atom[3]
1388                        XYZ = np.array(G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,cx,3))
1389                        tor = G2mth.getRestTorsion(XYZ,Amat)
1390                        restr,calc = G2mth.calcTorsionEnergy(tor,coeffDict[cofName])
1391                        chisq += torsionRestData['wtFactor']*(restr/esd)**2
1392                        table.append([name,cofName,tor,calc,restr,esd])
1393                        rowLabels.append(str(i))
1394                    except KeyError:
1395                        print '**** WARNING - missing atom - restraint deleted ****'
1396                        bad.append(i)
1397            if len(bad):
1398                bad.reverse()
1399                for ibad in bad:
1400                    del torsionList[ibad]
1401            if len(torsionList):
1402                torsionTable = G2G.Table(table,rowLabels=rowLabels,colLabels=colLabels,types=Types)
1403                TorsionRestr.Torsions = G2G.GSGrid(TorsionRestr)
1404                TorsionRestr.Torsions.SetTable(torsionTable, True)
1405                TorsionRestr.Torsions.AutoSizeColumns(False)
1406                for r in range(len(torsionList)):
1407                    for c in range(5):
1408                        TorsionRestr.Torsions.SetReadOnly(r,c,True)
1409                        TorsionRestr.Torsions.SetCellStyle(r,c,VERY_LIGHT_GREY,True)
1410                TorsionRestr.Torsions.Bind(wg.EVT_GRID_LABEL_LEFT_CLICK,OnRowSelect)
1411                TorsionRestr.Torsions.Bind(wg.EVT_GRID_CELL_CHANGE, OnCellChange)
1412                G2frame.dataFrame.Bind(wx.EVT_MENU, OnDeleteRestraint, id=G2gd.wxID_RESTDELETE)
1413                G2frame.dataFrame.Bind(wx.EVT_MENU, OnChangeEsd, id=G2gd.wxID_RESTCHANGEESD)
1414                mainSizer.Add(wx.StaticText(TorsionRestr,-1,
1415                    'Torsion restraints: sum(wt*(delt/sig)^2) =    %.2f, mean(wt*(delt/sig)^2) =    %.2f'    \
1416                    %(chisq,chisq/len(torsionList))),0,wx.ALIGN_CENTER_VERTICAL)
1417                mainSizer.Add(TorsionRestr.Torsions,0,)
1418               
1419                mainSizer.Add((5,5))
1420                mainSizer.Add(wx.StaticText(TorsionRestr,-1,'Torsion function coefficients:'),0,wx.ALIGN_CENTER_VERTICAL)
1421                table = []
1422                rowLabels = []
1423                Types = 9*[wg.GRID_VALUE_FLOAT+':10,4',]
1424                colLabels = ['Mag A','Pos A','Width A','Mag B','Pos B','Width B','Mag C','Pos C','Width C']
1425                for item in coeffDict:
1426                    rowLabels.append(item)
1427                    table.append(coeffDict[item])
1428                coeffTable = G2G.Table(table,rowLabels=rowLabels,colLabels=colLabels,types=Types)
1429                Coeff = G2G.GSGrid(TorsionRestr)
1430                Coeff.SetTable(coeffTable, True)
1431                Coeff.AutoSizeColumns(False)
1432                for r in range(len(coeffDict)):
1433                    for c in range(9):
1434                        Coeff.SetReadOnly(r,c,True)
1435                        Coeff.SetCellStyle(r,c,VERY_LIGHT_GREY,True)
1436                mainSizer.Add(Coeff,0,)
1437            else:
1438                mainSizer.Add(wx.StaticText(TorsionRestr,-1,'No torsion restraints for this phase'),0,)
1439        else:
1440            mainSizer.Add(wx.StaticText(TorsionRestr,-1,'No torsion restraints for this phase'),0,)
1441
1442        TorsionRestr.SetSizer(mainSizer)
1443        Size = mainSizer.Fit(TorsionRestr)
1444        Size[0] = 600
1445        Size[1] = min(Size[1]+50,500)       #make room for tab, but not too big
1446        TorsionRestr.SetSize(Size)
1447        TorsionRestr.SetScrollbars(10,10,Size[0]/10-4,Size[1]/10-1)
1448
1449    def UpdateRamaRestr(ramaRestData):
1450
1451        def OnCellChange(event):
1452            r,c =  event.GetRow(),event.GetCol()
1453            try:
1454                new = float(ramaTable.GetValue(r,c))
1455                if new <= 0. or new > 5.:
1456                    raise ValueError
1457                ramaRestData['Ramas'][r][4] = new     #only esd is editable
1458            except ValueError:
1459                pass           
1460            wx.CallAfter(UpdateRamaRestr,ramaRestData)               
1461           
1462        def OnDeleteRestraint(event):
1463            rows = GetSelectedRows(RamaRestr.Ramas)
1464            if not rows:
1465                return
1466            rows.sort()
1467            rows.reverse()
1468            for row in rows:
1469                ramaList.remove(ramaList[row])
1470            UpdateRamaRestr(ramaRestData)               
1471           
1472        def OnChangeEsd(event):
1473            rows = GetSelectedRows(RamaRestr.Ramas)
1474            if not rows:
1475                return
1476            RamaRestr.Ramas.ClearSelection()
1477            val = ramaList[rows[0]][4]
1478            dlg = G2G.SingleFloatDialog(G2frame,'New value','Enter new esd for energy',val,[0.,5.],'%.2f')
1479            if dlg.ShowModal() == wx.ID_OK:
1480                parm = dlg.GetValue()
1481                for r in rows:
1482                    ramaRestData['Ramas'][r][4] = parm
1483            dlg.Destroy()
1484            UpdateRamaRestr(ramaRestData)               
1485                                           
1486        RamaRestr.DestroyChildren()
1487#        if RamaRestr.GetSizer():
1488#            RamaRestr.GetSizer().Clear(True)
1489        mainSizer = wx.BoxSizer(wx.VERTICAL)
1490        mainSizer.Add((5,5),0)
1491        mainSizer.Add(WtBox(RamaRestr,ramaRestData),0,wx.ALIGN_CENTER_VERTICAL)
1492
1493        ramaList = ramaRestData['Ramas']
1494        coeffDict = ramaRestData['Coeff']
1495        if len(ramaList):
1496            mainSizer.Add(wx.StaticText(RamaRestr,-1,'Ramachandran restraints:'),0,wx.ALIGN_CENTER_VERTICAL)
1497            table = []
1498            rowLabels = []
1499            bad = []
1500            chisq = 0.
1501            Types = 2*[wg.GRID_VALUE_STRING,]+5*[wg.GRID_VALUE_FLOAT+':10,2',]
1502            if 'macro' in General['Type']:
1503                colLabels = ['(res) A  B  C  D  E','coef name','phi','psi','obs E','restr','esd']
1504                for i,[indx,ops,cofName,esd] in enumerate(ramaList):
1505                    try:
1506                        atoms = G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,0,4)
1507                        name = '('+atoms[3][1]+atoms[3][0].strip()+atoms[3][2]+')'
1508                        for atom in atoms:
1509                            name += '  '+atom[3]
1510                        XYZ = np.array(G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,cx,3))
1511                        phi,psi = G2mth.getRestRama(XYZ,Amat)
1512                        restr,calc = G2mth.calcRamaEnergy(phi,psi,coeffDict[cofName])
1513                        chisq += ramaRestData['wtFactor']*(restr/esd)**2
1514                        table.append([name,cofName,phi,psi,calc,restr,esd])
1515                        rowLabels.append(str(i))
1516                    except KeyError:
1517                        print '**** WARNING - missing atom - restraint deleted ****'
1518                        bad.append(i)
1519            if len(bad):
1520                bad.reverse()
1521                for ibad in bad:
1522                    del ramaList[ibad]
1523            if len(ramaList):
1524                ramaTable = G2G.Table(table,rowLabels=rowLabels,colLabels=colLabels,types=Types)
1525                RamaRestr.Ramas = G2G.GSGrid(RamaRestr)
1526                RamaRestr.Ramas.SetTable(ramaTable, True)
1527                RamaRestr.Ramas.AutoSizeColumns(False)
1528                for r in range(len(ramaList)):
1529                    for c in range(6):
1530                        RamaRestr.Ramas.SetReadOnly(r,c,True)
1531                        RamaRestr.Ramas.SetCellStyle(r,c,VERY_LIGHT_GREY,True)
1532                RamaRestr.Ramas.Bind(wg.EVT_GRID_LABEL_LEFT_CLICK,OnRowSelect)
1533                RamaRestr.Ramas.Bind(wg.EVT_GRID_CELL_CHANGE, OnCellChange)
1534                G2frame.dataFrame.Bind(wx.EVT_MENU, OnDeleteRestraint, id=G2gd.wxID_RESTDELETE)
1535                G2frame.dataFrame.Bind(wx.EVT_MENU, OnChangeEsd, id=G2gd.wxID_RESTCHANGEESD)
1536                mainSizer.Add(wx.StaticText(RamaRestr,-1,
1537                    'Ramachandran restraints: sum(wt*(delt/sig)^2) =    %.2f, mean(wt*(delt/sig)^2) =    %.2f'    \
1538                    %(chisq,chisq/len(ramaList))),0,wx.ALIGN_CENTER_VERTICAL)
1539                mainSizer.Add(RamaRestr.Ramas,0,)
1540            else:
1541                mainSizer.Add(wx.StaticText(RamaRestr,-1,'No Ramachandran restraints for this phase'),0,)
1542        else:
1543            mainSizer.Add(wx.StaticText(RamaRestr,-1,'No Ramachandran restraints for this phase'),0,)
1544        mainSizer.Add((5,5))
1545        mainSizer.Add(wx.StaticText(RamaRestr,-1,'Ramachandran function coefficients:'),0,wx.ALIGN_CENTER_VERTICAL)
1546        if len(coeffDict):
1547            table = []
1548            rowLabels = []
1549            Types = 6*[wg.GRID_VALUE_FLOAT+':10,4',]
1550            colLabels = ['Mag','Pos phi','Pos psi','sig(phi)','sig(psi)','sig(cov)']
1551            for item in coeffDict:
1552                for i,term in enumerate(coeffDict[item]):
1553                    rowLabels.append(item+' term:'+str(i))
1554                    table.append(term)
1555            coeffTable = G2G.Table(table,rowLabels=rowLabels,colLabels=colLabels,types=Types)
1556            Coeff = G2G.GSGrid(RamaRestr)
1557            Coeff.SetTable(coeffTable, True)
1558            Coeff.AutoSizeColumns(False)
1559            for r in range(Coeff.GetNumberRows()):
1560                for c in range(6):
1561                    Coeff.SetReadOnly(r,c,True)
1562                    Coeff.SetCellStyle(r,c,VERY_LIGHT_GREY,True)
1563            mainSizer.Add(Coeff,0,)
1564
1565        RamaRestr.SetSizer(mainSizer)
1566        Size = mainSizer.Fit(RamaRestr)
1567        Size[0] = 600
1568        Size[1] = min(Size[1]+50,500)       #make room for tab, but not too big
1569        RamaRestr.SetSize(Size)
1570        RamaRestr.SetScrollbars(10,10,Size[0]/10-4,Size[1]/10-1)
1571
1572    def UpdateChemcompRestr(chemcompRestData):
1573       
1574        def OnCellChange(event):
1575            r,c =  event.GetRow(),event.GetCol()
1576            rowLabl = ChemComps.GetRowLabelValue(r)
1577            row = int(rowLabl.split(':')[1])
1578            if 'Restr' in rowLabl:
1579                try:
1580                    new = float(chemcompTable.GetValue(r,c))
1581                    chemcompRestData['Sites'][row][c-2] = new         #obsd or esd
1582                except ValueError:
1583                    pass
1584            else:
1585                try:
1586                    new = float(chemcompTable.GetValue(r,c))
1587                    id = int(rowLabl.split(':')[2])
1588                    chemcompRestData['Sites'][row][1][id] = new     #only factor
1589                except ValueError:
1590                    pass
1591            wx.CallAfter(UpdateChemcompRestr,chemcompRestData)               
1592           
1593        def OnDeleteRestraint(event):
1594            #rows = GetSelectedRows()
1595            rows = ChemComps.GetSelectedRows()
1596            if not rows:
1597                return
1598            rowLabl = ChemComps.GetRowLabelValue(r)
1599            row = int(rowLabl.split(':')[1])
1600            if 'Restr' in rowLabl:
1601                del chemcompList[row]
1602            else:
1603                term = int(rowLabl.split(':')[2])
1604                del chemcompList[row][0][term]
1605                del chemcompList[row][1][term]
1606            UpdateChemcompRestr(chemcompRestData)               
1607           
1608        def OnChangeValue(event):
1609            rows = GetSelectedRows(ChemComps)
1610            if not rows:
1611                return
1612            ChemComps.ClearSelection()
1613            dlg = G2G.SingleFloatDialog(G2frame,'New value',
1614                'Enter new value for restraint multiplier',1.0,[-1.e6,1.e6],'%.2f')
1615            if dlg.ShowModal() == wx.ID_OK:
1616                parm = dlg.GetValue()
1617                for r in rows:
1618                    rowLabl = ChemComps.GetRowLabelValue(r)
1619                    if 'term' in rowLabl:
1620                        items = rowLabl.split(':')
1621                        chemcompRestData['Sites'][int(items[1])][1][int(items[2])] = parm
1622            dlg.Destroy()
1623            UpdateChemcompRestr(chemcompRestData)               
1624
1625        ChemCompRestr.DestroyChildren()
1626#        if ChemCompRestr.GetSizer():
1627#            ChemCompRestr.GetSizer().Clear(True)
1628        mainSizer = wx.BoxSizer(wx.VERTICAL)
1629        mainSizer.Add((5,5),0)
1630        mainSizer.Add(WtBox(ChemCompRestr,chemcompRestData),0,wx.ALIGN_CENTER_VERTICAL)
1631        mainSizer.Add(wx.StaticText(ChemCompRestr,-1, 
1632            'NB: The chemical restraint sum is over the unit cell contents'),0,wx.ALIGN_CENTER_VERTICAL)
1633        mainSizer.Add((5,5),0)
1634
1635        chemcompList = chemcompRestData['Sites']
1636        if len(chemcompList):
1637            table = []
1638            rowLabels = []
1639            bad = []
1640            chisq = 0.
1641            Types = [wg.GRID_VALUE_STRING,]+5*[wg.GRID_VALUE_FLOAT+':10,2',]
1642            colLabels = ['Atoms','mul*frac','factor','calc','target','esd']
1643            for i,[indx,factors,obs,esd] in enumerate(chemcompList):
1644                try:
1645                    atoms = G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,ct-1)
1646                    mul = np.array(G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,cs+1))
1647                    frac = np.array(G2mth.GetAtomItemsById(Atoms,AtLookUp,indx,cs-1))
1648                    mulfrac = mul*frac
1649                    calcs = mul*frac*factors
1650                    chisq += chemcompRestData['wtFactor']*((obs-np.sum(calcs))/esd)**2
1651                    for iatm,[atom,mf,fr,clc] in enumerate(zip(atoms,mulfrac,factors,calcs)):
1652                        table.append([atom,mf,fr,clc,'',''])
1653                        rowLabels.append('term:'+str(i)+':'+str(iatm))
1654                    table.append(['Sum','','',np.sum(calcs),obs,esd])
1655                    rowLabels.append('Restr:'+str(i))
1656                except KeyError:
1657                    print '**** WARNING - missing atom - restraint deleted ****'
1658                    bad.append(i)
1659            if len(bad):
1660                bad.reverse()
1661                for ibad in bad:
1662                    del chemcompList[ibad]
1663            if len(chemcompList):
1664                chemcompTable = G2G.Table(table,rowLabels=rowLabels,colLabels=colLabels,types=Types)
1665                ChemComps = G2G.GSGrid(ChemCompRestr)
1666                ChemComps.SetTable(chemcompTable, True)
1667                ChemComps.AutoSizeColumns(False)
1668                for r in range(chemcompTable.GetNumberRows()):
1669                    for c in range(2):
1670                        ChemComps.SetReadOnly(r,c,True)
1671                        ChemComps.SetCellStyle(r,c,VERY_LIGHT_GREY,True)
1672                    if 'Restr' in ChemComps.GetRowLabelValue(r):
1673                        for c in range(4):
1674                            ChemComps.SetReadOnly(r,c,True)
1675                            ChemComps.SetCellStyle(r,c,VERY_LIGHT_GREY,True)
1676                        for c in [1,2]:
1677                            ChemComps.SetCellTextColour(r,c,VERY_LIGHT_GREY)
1678                    else:
1679                        for c in [3,4,5]:
1680                            ChemComps.SetReadOnly(r,c,True)
1681                            ChemComps.SetCellStyle(r,c,VERY_LIGHT_GREY,True)
1682                        for c in [4,5]:
1683                            ChemComps.SetCellTextColour(r,c,VERY_LIGHT_GREY)
1684                           
1685                ChemComps.Bind(wg.EVT_GRID_LABEL_LEFT_CLICK,OnRowSelect)
1686                ChemComps.Bind(wg.EVT_GRID_CELL_CHANGE, OnCellChange)
1687                G2frame.dataFrame.Bind(wx.EVT_MENU, OnDeleteRestraint, id=G2gd.wxID_RESTDELETE)
1688                G2frame.dataFrame.Bind(wx.EVT_MENU, OnChangeValue, id=G2gd.wxID_RESRCHANGEVAL)
1689                mainSizer.Add(wx.StaticText(ChemCompRestr,-1,
1690                    'Chemical composition restraints: sum(wt*(delt/sig)^2) =    %.2f, mean(wt*(delt/sig)^2) =    %.2f'    \
1691                    %(chisq,chisq/len(chemcompList))),0,wx.ALIGN_CENTER_VERTICAL)
1692                mainSizer.Add(ChemComps,0,)
1693            else:
1694                mainSizer.Add(wx.StaticText(ChemCompRestr,-1,'No chemical composition restraints for this phase'),0,)
1695        else:
1696            mainSizer.Add(wx.StaticText(ChemCompRestr,-1,'No chemical composition restraints for this phase'),0,)
1697
1698        ChemCompRestr.SetSizer(mainSizer)
1699        Size = mainSizer.Fit(ChemCompRestr)
1700        Size[0] = 600
1701        Size[1] = min(Size[1]+50,500)       #make room for tab, but not too big
1702        ChemCompRestr.SetSize(Size)
1703        ChemCompRestr.SetScrollbars(10,10,Size[0]/10-4,Size[1]/10-1)
1704           
1705    def UpdateTextureRestr(textureRestData):
1706           
1707        def OnDeleteRestraint(event):
1708            rows = GetSelectedRows(Textures)
1709            if not rows:
1710                return
1711            rows.sort()
1712            rows.reverse()
1713            for row in rows:
1714                textureList.remove(textureList[row])
1715            wx.CallAfter(UpdateTextureRestr,textureRestData)               
1716           
1717        def OnCellChange(event):
1718            r,c = event.GetRow(),event.GetCol()
1719            try:
1720                if c == 1:  #grid size
1721                    new = int(textureTable.GetValue(r,c))
1722                    if new < 6 or new > 24:
1723                        raise ValueError
1724                elif c in [2,4]:   #esds
1725                    new = float(textureTable.GetValue(r,c))
1726                    if new < -1. or new > 2.:
1727                        raise ValueError
1728                else:
1729                    new = textureTable.GetValue(r,c)
1730                textureRestData['HKLs'][r][c] = new
1731            except ValueError:
1732                pass           
1733            wx.CallAfter(UpdateTextureRestr,textureRestData)               
1734
1735        TextureRestr.DestroyChildren()
1736        mainSizer = wx.BoxSizer(wx.VERTICAL)
1737        mainSizer.Add((5,5),0)
1738        mainSizer.Add(WtBox(TextureRestr,textureRestData),0,wx.ALIGN_CENTER_VERTICAL)
1739        mainSizer.Add(wx.StaticText(TextureRestr,-1, 
1740            'NB: The texture restraints suppress negative pole figure values for the selected HKLs\n'
1741            '    "unit esd" gives a bias toward a flatter polefigure'),0,wx.ALIGN_CENTER_VERTICAL)
1742        mainSizer.Add((5,5),0)
1743
1744        textureList = textureRestData['HKLs']
1745        if len(textureList):
1746            table = []
1747            rowLabels = []
1748            Types = [wg.GRID_VALUE_STRING,wg.GRID_VALUE_LONG,wg.GRID_VALUE_FLOAT+':10,2',
1749                wg.GRID_VALUE_BOOL,wg.GRID_VALUE_FLOAT+':10,2']
1750            colLabels = ['HKL','grid','neg esd','use unit?','unit esd']
1751            for i,[hkl,grid,esd1,ifesd2,esd2] in enumerate(textureList):
1752                table.append(['%d %d %d'%(hkl[0],hkl[1],hkl[2]),grid,esd1,ifesd2,esd2])
1753                rowLabels.append(str(i))
1754            textureTable = G2G.Table(table,rowLabels=rowLabels,colLabels=colLabels,types=Types)
1755            Textures = G2G.GSGrid(TextureRestr)
1756            Textures.SetTable(textureTable, True)
1757            Textures.AutoSizeColumns(False)
1758            for r in range(len(textureList)):
1759                Textures.SetReadOnly(r,0,True)
1760                Textures.SetCellStyle(r,0,VERY_LIGHT_GREY,True)
1761                if not textureTable.GetValue(r,3):
1762                    Textures.SetReadOnly(r,4,True)
1763                    Textures.SetCellStyle(r,4,VERY_LIGHT_GREY,True)
1764                    Textures.SetCellTextColour(r,4,VERY_LIGHT_GREY)
1765            Textures.Bind(wg.EVT_GRID_LABEL_LEFT_CLICK,OnRowSelect)
1766            Textures.Bind(wg.EVT_GRID_CELL_CHANGE, OnCellChange)
1767            G2frame.dataFrame.Bind(wx.EVT_MENU, OnDeleteRestraint, id=G2gd.wxID_RESTDELETE)
1768            mainSizer.Add(Textures,0,)
1769        else:
1770            mainSizer.Add(wx.StaticText(TextureRestr,-1,'No texture restraints for this phase'),0,)
1771        TextureRestr.SetSizer(mainSizer)
1772        Size = mainSizer.Fit(TextureRestr)
1773        Size[0] = 600
1774        Size[1] = min(Size[1]+50,500)       #make room for tab, but not too big
1775        TextureRestr.SetSize(Size)
1776        TextureRestr.SetScrollbars(10,10,Size[0]/10-4,Size[1]/10-1)
1777           
1778    def OnPageChanged(event):
1779        #print 'OnPageChanged'
1780        page = event.GetSelection()
1781        G2frame.restrBook.SetSize(G2frame.dataWindow.GetClientSize())    #TODO -almost right
1782        text = G2frame.restrBook.GetPageText(page)
1783        G2frame.dataFrame.RestraintEdit.SetLabel(G2gd.wxID_RESRCHANGEVAL,'Change value')
1784        if text == 'Bond':
1785            G2gd.SetDataMenuBar(G2frame,G2frame.dataWindow.RestraintMenu)
1786            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESTRAINTADD,True)
1787            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESRCHANGEVAL,True)
1788            bondRestData = restrData['Bond']
1789            UpdateBondRestr(bondRestData)
1790        elif text == 'Angle':
1791            G2gd.SetDataMenuBar(G2frame,G2frame.dataWindow.RestraintMenu)
1792            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESTRAINTADD,True)
1793            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESRCHANGEVAL,True)
1794            angleRestData = restrData['Angle']
1795            UpdateAngleRestr(angleRestData)
1796        elif text == 'Plane':
1797            G2gd.SetDataMenuBar(G2frame,G2frame.dataWindow.RestraintMenu)
1798            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESTRAINTADD,True)
1799            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESRCHANGEVAL,False)
1800            planeRestData = restrData['Plane']
1801            UpdatePlaneRestr(planeRestData)
1802        elif text == 'Chiral':
1803            G2gd.SetDataMenuBar(G2frame,G2frame.dataWindow.RestraintMenu)
1804            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESTRAINTADD,False)
1805            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESRCHANGEVAL,True)
1806            chiralRestData = restrData['Chiral']
1807            UpdateChiralRestr(chiralRestData)
1808        elif text == 'Torsion':
1809            G2gd.SetDataMenuBar(G2frame,G2frame.dataWindow.RestraintMenu)
1810            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESTRAINTADD,False)
1811            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESRCHANGEVAL,False)
1812            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_AARESTRAINTPLOT,True)
1813            torsionRestData = restrData['Torsion']
1814            UpdateTorsionRestr(torsionRestData)
1815        elif text == 'Ramachandran':
1816            G2gd.SetDataMenuBar(G2frame,G2frame.dataWindow.RestraintMenu)
1817            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESTRAINTADD,False)
1818            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESRCHANGEVAL,False)
1819            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_AARESTRAINTPLOT,True)
1820            ramaRestData = restrData['Rama']
1821            UpdateRamaRestr(ramaRestData)
1822            wx.CallAfter(G2plt.PlotRama,G2frame,phaseName,rama,ramaName)
1823        elif text == 'Chem. comp.':
1824            G2gd.SetDataMenuBar(G2frame,G2frame.dataWindow.RestraintMenu)
1825            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESTRAINTADD,True)
1826            G2frame.dataFrame.RestraintEdit.SetLabel(G2gd.wxID_RESRCHANGEVAL,'Change factor')
1827            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESRCHANGEVAL,True)
1828            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESTCHANGEESD,False)
1829            chemcompRestData = restrData['ChemComp']
1830            UpdateChemcompRestr(chemcompRestData)
1831        elif text == 'Texture':
1832            G2gd.SetDataMenuBar(G2frame,G2frame.dataWindow.RestraintMenu)
1833            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESTRAINTADD,True)
1834            G2frame.dataFrame.RestraintEdit.Enable(G2gd.wxID_RESRCHANGEVAL,True)
1835            textureRestData = restrData['Texture']
1836            UpdateTextureRestr(textureRestData)
1837        event.Skip()
1838
1839#    def RaisePage(event):
1840#        'Respond to a "select tab" menu button'
1841#        # class PseudoEvent(object):
1842#        #     def __init__(self,page): self.page = page
1843#        #     def Skip(self): pass
1844#        #     def GetSelection(self): return self.page
1845#        try:
1846#            i = tabIndex.get(event.GetId())
1847#            G2frame.restrBook.SetSelection(i)
1848#            #OnPageChanged(PseudoEvent(i))
1849#        except ValueError:
1850#            print('Unexpected event in RaisePage')
1851#       
1852    G2gd.SetDataMenuBar(G2frame,G2frame.dataWindow.RestraintMenu)
1853    G2frame.SetLabel(G2frame.GetLabel().split('||')[0]+' || '+'restraints for '+phaseName)
1854    G2frame.dataWindow.ClearData()
1855    G2frame.restrBook = G2G.GSNoteBook(parent=G2frame.dataWindow,size=G2frame.dataWindow.GetClientSize())
1856   
1857    G2frame.dataWindow.RestraintEdit.Enable(G2gd.wxID_RESTSELPHASE,False)
1858    if len(Phases) > 1:
1859        G2frame.dataWindow.RestraintEdit.Enable(G2gd.wxID_RESTSELPHASE,True)
1860        G2frame.dataWindow.Bind(wx.EVT_MENU, OnSelectPhase, id=G2gd.wxID_RESTSELPHASE)
1861    G2frame.dataFrame.Bind(wx.EVT_MENU, OnAddRestraint, id=G2gd.wxID_RESTRAINTADD)
1862    if 'macro' in phasedata['General']['Type']:
1863        G2frame.dataWindow.RestraintEdit.Enable(G2gd.wxID_AARESTRAINTADD,True)
1864        G2frame.dataWindow.Bind(wx.EVT_MENU, OnAddAARestraint, id=G2gd.wxID_AARESTRAINTADD)
1865        G2frame.dataWindow.Bind(wx.EVT_MENU, OnPlotAARestraint, id=G2gd.wxID_AARESTRAINTPLOT)
1866   
1867    # clear menu and menu pointers
1868
1869    txt = 'Bond'
1870    BondRestr = wx.ScrolledWindow(G2frame.restrBook)
1871    G2frame.restrBook.AddPage(BondRestr,txt)
1872
1873    txt = 'Angle'
1874    AngleRestr = wx.ScrolledWindow(G2frame.restrBook)
1875    G2frame.restrBook.AddPage(AngleRestr,txt) 
1876   
1877    txt = 'Plane'
1878    PlaneRestr = wx.ScrolledWindow(G2frame.restrBook)
1879    G2frame.restrBook.AddPage(PlaneRestr,txt)
1880
1881    txt = 'Chiral'
1882    ChiralRestr = wx.ScrolledWindow(G2frame.restrBook)
1883    G2frame.restrBook.AddPage(ChiralRestr,txt)
1884
1885    if 'macro' in General['Type']:
1886        txt = 'Torsion'
1887        TorsionRestr = wx.ScrolledWindow(G2frame.restrBook)
1888        G2frame.restrBook.AddPage(TorsionRestr,txt)
1889
1890        txt = 'Ramachandran'
1891        RamaRestr = wx.ScrolledWindow(G2frame.restrBook)
1892        G2frame.restrBook.AddPage(RamaRestr,txt)
1893
1894    txt = 'Chem. comp.'
1895    ChemCompRestr = wx.ScrolledWindow(G2frame.restrBook)
1896    G2frame.restrBook.AddPage(ChemCompRestr,txt)
1897   
1898    if General['SH Texture']['Order']:
1899        txt = 'Texture'
1900        TextureRestr = wx.ScrolledWindow(G2frame.restrBook)
1901        G2frame.restrBook.AddPage(TextureRestr,txt)
1902   
1903    UpdateBondRestr(restrData['Bond'])
1904
1905    G2frame.restrBook.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CHANGED, OnPageChanged)
Note: See TracBrowser for help on using the repository browser.