Changeset 5130


Ignore:
Timestamp:
Jan 8, 2022 11:21:35 AM (23 months ago)
Author:
vondreele
Message:

revise ISODISTORT operation - now uses Method 4 by default.
Revise ISODISTORT cif import to retain mode displacements
ApplyModeDisp? now uses mode normalization
move OnRunISODISTORT to UpdateISODISTORT - where it is now called from
revise UpdateISODISTORT to allow Method 4 along with 1; 2 & 3 are not currently supported in GSAS-II
mode display sliders now initialized from ISODISTORT cif data; reset goes back to cif values (not zeros)
fix errors in instrument parm plots; also provide alert in plot title if negatives encountered
recover _iso_displacivemode_value from ISODISTORT cif file
revise ISODISTORT.py to work with method 4 as well as method 1.

Location:
trunk
Files:
7 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIImath.py

    r5112 r5130  
    21812181    Atoms= data['Atoms']
    21822182    ISOdata = data['ISODISTORT']
    2183     modeDisp = np.array(ISOdata['modeDispl'])
     2183    coords = ISOdata['G2parentCoords']
     2184    modeDisp = np.array(ISOdata['modeDispl'])*np.array(ISOdata['NormList'])
    21842185    mode2var = np.array(ISOdata['Mode2VarMatrix'])
    21852186    varDisp = np.sum(mode2var*modeDisp,axis=1)
     
    21972198        drawAtoms = drawingData['Atoms']
    21982199        for iat,atom in enumerate(atoms):
    2199             atxyz = np.array(atom[cx:cx+3])
     2200            atxyz = coords[iat]
    22002201            displ = np.zeros(3)
    22012202            for ip,parm in enumerate(parNames[iat]):
    22022203                if parm in vardict:
    22032204                    displ[ip] = vardict[parm]
     2205            atom[cx:cx+3] = atxyz+displ
    22042206            indx = FindAtomIndexByIDs(drawAtoms,dci,[atom[cia+8],],True)
    22052207            for ind in indx:
     
    47084710        gam = getTOFgamma(ins,dsp)
    47094711        XY = [pos,0,mag,1,alp,0,bet,0,sig,0,gam,0]
    4710     elif 'C' in Parms['Type'][0]:                            #CW data - TOF later in an else
     4712    elif 'C' in Parms['Type'][0]:
    47114713        for x in ['U','V','W','X','Y','Z']:
    47124714            ins[x] = Parms.get(x,[0.0,0.0])[ind]
  • trunk/GSASIIobj.py

    r5118 r5130  
    11791179to obtain the delta values) that are taken from the parent structure coordinate and the initial offset value
    11801180(in ``_iso_deltacoordinate_value``) and these are placed in
    1181 ``.Phase['ISODISTORT']['G2coordOffset']`` in the same order as ``.Phase['ISODISTORT']['G2ModeList']`` and
    1182 ``.Phase['ISODISTORT']['IsoVarList']``.
     1181``.Phase['ISODISTORT']['G2coordOffset']`` in the same order as ``.Phase['ISODISTORT']['G2ModeList']``,
     1182``.Phase['ISODISTORT']['IsoVarList']`` and ''.Phase[ISODISTORT']['G2parentCoords']''.'
    11831183
    11841184The normalization factors (which the delta values are divided by)
  • trunk/GSASIIphsGUI.py

    r5123 r5130  
    6969import numpy.linalg as nl
    7070import atmdata
     71import ISODISTORT as ISO
    7172
    7273try:
     
    29342935        G2frame.GPXtree.SelectItem(sub)
    29352936       
    2936     def OnRunISODISTORT(event):
    2937         ''' this needs to setup for method #3 or #4 in ISODISTORT
    2938         after providing parent cif:
    2939         #3 asks for transformation matrix & space group of child structure
    2940         #4 asks for cif file of child structure
    2941         '''
    2942         import ISODISTORT as ISO
    2943         # Use GSAS2Scriptable to make a CIF for the current phase in a
    2944         # scratch directory
    2945         data['pId'] = data.get('pId',0) # needs a pId
    2946         import GSASIIscriptable as G2sc
    2947         import tempfile
    2948         wx.BeginBusyCursor()
    2949         proj = G2sc.G2Project(newgpx='tmp4cif.gpx')
    2950         ph = G2sc.G2Phase(data,data['General']['Name'],proj)
    2951         tmpdir = tempfile.TemporaryDirectory()
    2952         parentcif = os.path.join(tmpdir.name,'ISOin.cif')
    2953         ph.export_CIF(parentcif)
    2954         radio,rundata = ISO.GetISODISTORT(data,parentcif)
    2955         wx.EndBusyCursor()
    2956         tmpdir.cleanup()
    2957         if radio and rundata:
    2958             data['ISODISTORT']['radio'] = radio
    2959             data['ISODISTORT']['rundata'] = rundata
    2960             data['ISODISTORT']['SGselect'] =  {'Tric':True,'Mono':True,'Orth':True,'Tetr':True,'Trig':True,'Hexa':True,'Cubi':True}
    2961             data['ISODISTORT']['selection'] = None
    2962             print('ISODISTORT run complete')
    2963             wx.CallAfter(UpdateISODISTORT)
    2964         else:
    2965             G2G.G2MessageBox(G2frame,'ISODISTORT run failed - see page opened in web browser')
    2966                
    29672937    def OnCompare(event):
    29682938        generalData = data['General']
     
    66376607            if not os.path.exists(engineFilePath):
    66386608                dlg = wx.FileDialog(G2frame, 'Open fullrmc directory',
    6639                                         defaultFile='*.rmc',
    6640                                         wildcard='*.rmc')
     6609                    defaultFile='*.rmc',wildcard='*.rmc')
    66416610                try:
    66426611                    if dlg.ShowModal() == wx.ID_OK:
     
    70266995
    70276996    def UpdateISODISTORT(Scroll=0):
    7028         ''' Present the results of an ISODISTORT run & allow selection of a distortion model for PDFfit
    7029         & refinement constraints
     6997        ''' Setup ISODISTORT and present the results. Allow selection of a distortion model for PDFfit or
     6998        GSAS-II structure refinement as a cif file produced by ISODISTORT. Allows manipulation of distortion
     6999        mode displacements selection their refinement for this new phase.
    70307000        '''
    7031         def OnLaue(event):
    7032             Obj = event.GetEventObject()
    7033             name = Indx[Obj.GetId()]
    7034             data['ISODISTORT']['SGselect'][name[:4]] = not data['ISODISTORT']['SGselect'][name[:4]]
    7035             data['ISODISTORT']['selection'] = None
    7036             UpdateISODISTORT()
    7037            
    7038         def OnAllBtn(event):
    7039             for item in data['ISODISTORT']['SGselect']:
    7040                 data['ISODISTORT']['SGselect'][item] = not data['ISODISTORT']['SGselect'][item]
    7041             data['ISODISTORT']['selection'] = None
    7042             UpdateISODISTORT()
    7043            
    7044         def CheckItem(item):
    7045             SGnum = int(item.split()[1].split('*')[0])
    7046             for SGtype in data['ISODISTORT']['SGselect']:
    7047                 if data['ISODISTORT']['SGselect'][SGtype] and SGnum in SGrange[SGtype]:
    7048                     return True
    7049             return False
    7050        
    7051         def OnSelect(event):
    7052             r,c = event.GetRow(),event.GetCol()
    7053             if c == 0:
    7054                 data['ISODISTORT']['selection'] = [r,isoTable.GetValue(r,1)]
    7055                 for row in range(isoGrid.GetNumberRows()):
    7056                     isoTable.SetValue(row,c,False)
    7057                 isoTable.SetValue(r,c,True)
    7058                 isoGrid.ForceRefresh()
    7059                
    7060         def OnDispl(event):
    7061             '''Respond to movement of distortion mode slider'''
    7062             Obj = event.GetEventObject()
    7063             idsp,dispVal = Indx[Obj.GetId()]
    7064             modeDisp[idsp] = (Obj.GetValue()-100)/1000.
    7065             dispVal.SetValue(modeDisp[idsp])
    7066             err = G2mth.ApplyModeDisp(data)
    7067             if err:
    7068                 G2G.G2MessageBox(G2frame,'Do Draw atoms first')     
    7069             FindBondsDraw(data)               
    7070             G2plt.PlotStructure(G2frame,data)
    7071            
    7072         def OnDispVal(invalid,value,tc):
    7073             '''Respond to entry of a value into a distortion mode entry widget'''
    7074             idsp,displ = Indx[tc.GetId()]
    7075             displ.SetValue(int(value*1000)+100)
    7076             err = G2mth.ApplyModeDisp(data)
    7077             if err:
    7078                 G2G.G2MessageBox(G2frame,'Do Draw atoms first')               
    7079             FindBondsDraw(data)               
    7080             G2plt.PlotStructure(G2frame,data)
     7001       
     7002        def displaySetup():
     7003           
     7004            def OnParentCif(event):
     7005                dlg = wx.FileDialog(ISODIST, 'Select parent cif file',G2frame.LastGPXdir,
     7006                    style=wx.FD_OPEN ,wildcard='cif file(*.cif)|*.cif')
     7007                if dlg.ShowModal() == wx.ID_OK:
     7008                    fName = dlg.GetFilename()
     7009                    ISOdata['ParentCIF'] = fName
     7010                    dlg.Destroy()
     7011                else:
     7012                    dlg.Destroy()
     7013                UpdateISODISTORT()
     7014               
     7015            def OnUsePhase(event):
     7016                ISOdata['ParentCIF'] = 'Use this phase'                   
     7017                UpdateISODISTORT()
     7018               
     7019            def OnMethodSel(event):
     7020                method = methodSel.GetSelection()+1
     7021                if method in [1,4]:
     7022                    ISOdata['ISOmethod'] = method
     7023                UpdateISODISTORT()
     7024               
     7025            def OnChildCif(event):
     7026                dlg = wx.FileDialog(ISODIST, 'Select child cif file',G2frame.LastGPXdir,
     7027                    style=wx.FD_OPEN ,wildcard='cif file(*.cif)|*.cif')
     7028                if dlg.ShowModal() == wx.ID_OK:
     7029                    fName = dlg.GetFilename()
     7030                    ISOdata['ChildCIF'] = fName
     7031                    dlg.Destroy()
     7032                else:
     7033                    dlg.Destroy()
     7034                UpdateISODISTORT()
     7035
     7036            def OnUsePhase2(event):
     7037                ISOdata['ChildCIF'] = 'Use this phase'                   
     7038                UpdateISODISTORT()
     7039
     7040            topSizer = wx.BoxSizer(wx.VERTICAL)
     7041            topSizer.Add(wx.StaticText(ISODIST,label=' ISODISTORT setup controls:'))
     7042            parentSizer = wx.BoxSizer(wx.HORIZONTAL)
     7043            parentSizer.Add(wx.StaticText(ISODIST,label=' Parent cif file:'),0,WACV)
     7044            parentCif = wx.Button(ISODIST,label=ISOdata['ParentCIF'],size=(200,24))
     7045            parentCif.Bind(wx.EVT_BUTTON,OnParentCif)
     7046            parentSizer.Add(parentCif,0,WACV)
     7047            if 'Use this phase' not in ISOdata['ChildCIF'] and 'Use this phase' not in ISOdata['ParentCIF']:
     7048                usePhase = wx.Button(ISODIST,label=' Use this phase? ')
     7049                usePhase.Bind(wx.EVT_BUTTON,OnUsePhase)
     7050                parentSizer.Add(usePhase,0,WACV)
     7051            topSizer.Add(parentSizer)
     7052            #patch
     7053            if 'ISOmethod' not in ISOdata:
     7054                ISOdata['ISOmethod'] = 1
     7055            #end patch
     7056            choice = ['Method 1: Search over all special k points - yields only single Irrep models',
     7057                'Method 2: not implemented in GSAS-II',
     7058                'Method 3: not implemented in GSAS-II',
     7059                'Method 4: Mode decomposition of known child structure']
     7060            methodSel = wx.RadioBox(ISODIST,label='Select ISODISTORT method:',choices=choice,
     7061                majorDimension=1,style=wx.RA_SPECIFY_COLS)
     7062            methodSel.SetSelection(ISOdata['ISOmethod']-1)
     7063            methodSel.Bind(wx.EVT_RADIOBOX,OnMethodSel)
     7064            topSizer.Add(methodSel)
     7065            if ISOdata['ISOmethod'] == 4:
     7066                childSizer = wx.BoxSizer(wx.HORIZONTAL)
     7067                childSizer.Add(wx.StaticText(ISODIST,label=' Child cif file:'),0,WACV)
     7068                childCif = wx.Button(ISODIST,label=ISOdata['ChildCIF'],size=(200,24))
     7069                childCif.Bind(wx.EVT_BUTTON,OnChildCif)
     7070                childSizer.Add(childCif,0,WACV)
     7071                if 'Use this phase' not in ISOdata['ChildCIF'] and 'Use this phase' not in ISOdata['ParentCIF']:
     7072                    usePhase2 = wx.Button(ISODIST,label=' Use this phase? ')
     7073                    usePhase2.Bind(wx.EVT_BUTTON,OnUsePhase2)
     7074                    childSizer.Add(usePhase2,0,WACV)
     7075                topSizer.Add(childSizer)
     7076           
     7077            return topSizer
     7078           
     7079        def displaySubset():
     7080           
     7081            def OnLaue(event):
     7082                Obj = event.GetEventObject()
     7083                name = Indx[Obj.GetId()]
     7084                ISOdata['SGselect'][name[:4]] = not ISOdata['SGselect'][name[:4]]
     7085                ISOdata['selection'] = None
     7086                UpdateISODISTORT()
     7087               
     7088            def OnAllBtn(event):
     7089                for item in ISOdata['SGselect']:
     7090                    ISOdata['SGselect'][item] = not ISOdata['SGselect'][item]
     7091                ISOdata['selection'] = None
     7092                UpdateISODISTORT()
     7093               
     7094            topSizer = wx.BoxSizer(wx.VERTICAL)   
     7095            G2G.HorizontalLine(topSizer,ISODIST)
     7096            topSizer.Add(wx.StaticText(ISODIST,label='ISODISTORT Method 1 distortion search results:'))
     7097            topSizer.Add(wx.StaticText(ISODIST,label=' Subset selection if desired:'))
     7098            laueName = ['Cubic','Hexagonal','Trigonal','Tetragonal','Orthorhombic','Monoclinic','Triclinic']
     7099            littleSizer = wx.FlexGridSizer(0,8,5,5)
     7100            Indx = {}
     7101            for name in laueName:
     7102                laueCk = wx.CheckBox(ISODIST,label=name)
     7103                Indx[laueCk.GetId()] = name
     7104                laueCk.SetValue(data['ISODISTORT']['SGselect'][name[:4]])
     7105                laueCk.Bind(wx.EVT_CHECKBOX,OnLaue)
     7106                littleSizer.Add(laueCk,0,WACV)
     7107            allBtn = wx.Button(ISODIST,label='Toggle all')
     7108            allBtn.Bind(wx.EVT_BUTTON,OnAllBtn)
     7109            littleSizer.Add(allBtn)
     7110            topSizer.Add(littleSizer)
     7111            return topSizer
     7112           
     7113        def displayRadio():
     7114           
     7115            def CheckItem(item):
     7116                SGnum = int(item.split()[1].split('*')[0])
     7117                for SGtype in ISOdata['SGselect']:
     7118                    if ISOdata['SGselect'][SGtype] and SGnum in SGrange[SGtype]:
     7119                        return True
     7120                return False
     7121       
     7122            def OnSelect(event):
     7123               r,c = event.GetRow(),event.GetCol()
     7124               if c == 0:
     7125                   ISOdata['selection'] = [r,isoTable.GetValue(r,1)]
     7126                   for row in range(isoGrid.GetNumberRows()):
     7127                       isoTable.SetValue(row,c,False)
     7128                   isoTable.SetValue(r,c,True)
     7129                   isoGrid.ForceRefresh()
    70817130           
    7082         def OnReset(event):
    7083             '''Reset all distortion mode values to zero'''
    7084             data['ISODISTORT']['modeDispl'] = np.zeros(len(data['ISODISTORT']['G2ModeList']))
    7085             err = G2mth.ApplyModeDisp(data)
    7086             if err:
    7087                 G2G.G2MessageBox(G2frame,'Do Draw atoms first')               
    7088             FindBondsDraw(data)               
    7089             G2plt.PlotStructure(G2frame,data)
    7090             UpdateISODISTORT()                                   
    7091        
    7092         Indx = {}     
    7093         G2frame.dataWindow.ISODDataEdit.Enable(G2G.wxID_ISODNEWPHASE,
    7094                                 'rundata' in data['ISODISTORT'])
    7095         G2frame.dataWindow.ISODDataEdit.Enable(G2G.wxID_SHOWISO1,
    7096                     ('G2VarList' in data['ISODISTORT']) or
    7097                     ('G2OccVarList' in data['ISODISTORT']))
    7098         G2frame.dataWindow.ISODDataEdit.Enable(G2G.wxID_SHOWISOMODES,
    7099                     ('G2VarList' in data['ISODISTORT'])
    7100 #                    or ('G2OccVarList' in data['ISODISTORT'])
    7101                                                    )
    7102         if 'radio' not in data['ISODISTORT']:
    7103             if not data['ISODISTORT']:
    7104                 mainSizer = wx.BoxSizer(wx.VERTICAL)
    7105                 mainSizer.Add(wx.StaticText(ISODIST,
    7106                         label='No ISODISTORT information found for this phase\n'
    7107                             +'  (use Operations->Run ISODISTORT to generate)'))
    7108                 SetPhaseWindow(ISODIST,mainSizer,Scroll=Scroll)               
    7109                 return
    7110 #patch
    7111             if 'modeDispl' not in data['ISODISTORT']:
    7112                 data['ISODISTORT']['modeDispl'] = np.zeros(len(data['ISODISTORT']['G2ModeList']))
    7113 #end patch
    7114             if ISODIST.GetSizer():
    7115                 ISODIST.GetSizer().Clear(True)
    7116             mainSizer = wx.BoxSizer(wx.VERTICAL)
    7117             topSizer = wx.BoxSizer(wx.VERTICAL)   
     7131            SGrange = {'Cubi':np.arange(195,231),'Hexa':np.arange(168,195),'Trig':np.arange(143,168),'Tetr':np.arange(75,143),
     7132                       'Orth':np.arange(16,75),'Mono':np.arange(3,16),'Tric':np.arange(1,3)}       
    71187133            bottomSizer = wx.BoxSizer(wx.VERTICAL)
    7119             topSizer.Add(wx.StaticText(ISODIST,
    7120                          label=''' For use of ISODISTORT, please cite:
    7121   H. T. Stokes, D. M. Hatch, and B. J. Campbell, ISODISTORT, ISOTROPY Software Suite, iso.byu.edu.
    7122   B. J. Campbell, H. T. Stokes, D. E. Tanner, and D. M. Hatch, "ISODISPLACE: An Internet Tool for
    7123   Exploring Structural Distortions." J. Appl. Cryst. 39, 607-614 (2006).
    7124   '''))
    7125             topSizer.Add(wx.StaticText(ISODIST,label=' ISODISTORT distortion modes for %s:\n'%data['General']['Name']))
    7126             lineSizer = wx.BoxSizer(wx.HORIZONTAL)           
    7127             lineSizer.Add(wx.StaticText(ISODIST,label=' Adjust magnitude of distortion modes (-0.1 to +0.1):  '),0,WACV)
    7128             reset = wx.Button(ISODIST,label='Reset modes')
    7129             reset.Bind(wx.EVT_BUTTON,OnReset)
    7130             lineSizer.Add(reset,0,WACV)
    7131             topSizer.Add(lineSizer)
    7132             slideSizer = wx.FlexGridSizer(0,3,0,0)
    7133             slideSizer.AddGrowableCol(2,1)
    7134             modeDisp = data['ISODISTORT']['modeDispl']
    7135             for idsp,item in enumerate(data['ISODISTORT']['G2ModeList']):
    7136                 slideSizer.Add(wx.StaticText(ISODIST,label=item.name),0,WACV)
    7137                 dispVal = G2G.ValidatedTxtCtrl(ISODIST,modeDisp,idsp,xmin=-0.1,xmax=0.1,size=(50,20),OnLeave=OnDispVal)
    7138                 slideSizer.Add(dispVal,0,WACV)
    7139                 displ = wx.Slider(ISODIST,style=wx.SL_HORIZONTAL,value=int(modeDisp[idsp]*1000)+100)
    7140                 displ.SetRange(0,200)
    7141                 displ.Bind(wx.EVT_SLIDER, OnDispl)
    7142                 Indx[displ.GetId()] = [idsp,dispVal]
    7143                 Indx[dispVal.GetId()] = [idsp,displ]
    7144                 slideSizer.Add(displ,1,wx.EXPAND|wx.RIGHT)
    7145             slideSizer.SetMinSize(wx.Size(350,10))
    7146             topSizer.Add(slideSizer)
    7147             mainSizer.Add(topSizer)
    7148             SetPhaseWindow(ISODIST,mainSizer,Scroll=Scroll)               
    7149             return
    7150         if ISODIST.GetSizer():
    7151             ISODIST.GetSizer().Clear(True)
    7152         SGrange = {'Cubi':np.arange(195,231),'Hexa':np.arange(168,195),'Trig':np.arange(143,168),'Tetr':np.arange(75,143),
    7153                    'Orth':np.arange(16,75),'Mono':np.arange(3,16),'Tric':np.arange(1,3)}       
    7154         colLabels = ['select',' ISODISTORT order parameter direction description']
    7155         colTypes = [wg.GRID_VALUE_BOOL,wg.GRID_VALUE_STRING,]
    7156         mainSizer = wx.BoxSizer(wx.VERTICAL)
    7157         topSizer = wx.BoxSizer(wx.VERTICAL)   
    7158         bottomSizer = wx.BoxSizer(wx.VERTICAL)
    7159         topSizer.Add(wx.StaticText(ISODIST,label=' ISODISTORT distortion search results:'))
    7160         topSizer.Add(wx.StaticText(ISODIST,label='''
    7161 For use of ISODISTORT, please cite:
    7162   H. T. Stokes, D. M. Hatch, and B. J. Campbell, ISODISTORT, ISOTROPY Software Suite, iso.byu.edu.
    7163   B. J. Campbell, H. T. Stokes, D. E. Tanner, and D. M. Hatch, "ISODISPLACE: An Internet Tool for
    7164   Exploring Structural Distortions." J. Appl. Cryst. 39, 607-614 (2006).
    7165   '''))
    7166         topSizer.Add(wx.StaticText(ISODIST,label=' Subset selection if desired:'))
    7167         laueName = ['Cubic','Hexagonal','Trigonal','Tetragonal','Orthorhombic','Monoclinic','Triclinic']
    7168         littleSizer = wx.FlexGridSizer(0,8,5,5)
    7169         Indx = {}
    7170         for name in laueName:
    7171             laueCk = wx.CheckBox(ISODIST,label=name)
    7172             Indx[laueCk.GetId()] = name
    7173             laueCk.SetValue(data['ISODISTORT']['SGselect'][name[:4]])
    7174             laueCk.Bind(wx.EVT_CHECKBOX,OnLaue)
    7175             littleSizer.Add(laueCk,0,WACV)
    7176         allBtn = wx.Button(ISODIST,label='Toggle all')
    7177         allBtn.Bind(wx.EVT_BUTTON,OnAllBtn)
    7178         littleSizer.Add(allBtn)
    7179         topSizer.Add(littleSizer)
    7180        
    7181         mainSizer.Add(topSizer)
    7182          
    7183         if 'radio' in data['ISODISTORT']:
    7184             Radio = data['ISODISTORT']['radio']
     7134            colLabels = ['select',' ISODISTORT order parameter direction description']
     7135            colTypes = [wg.GRID_VALUE_BOOL,wg.GRID_VALUE_STRING,]
     7136           
     7137            Radio = ISOdata['radio']
    71857138            rowLabels = []
    71867139            table = []
    71877140            for i,item in enumerate(Radio):
    71887141                if CheckItem(Radio[item]):
    7189                     if data['ISODISTORT']['selection'] and data['ISODISTORT']['selection'][0] == i:
     7142                    if ISOdata['selection'] and ISOdata['selection'][0] == i:
    71907143                        table.append([True,Radio[item]])
    71917144                    else:
     
    72037156            isoGrid.SetColAttr(1,attr)
    72047157            isoGrid.Bind(wg.EVT_GRID_CELL_LEFT_CLICK, OnSelect)
    7205         mainSizer.Add(bottomSizer)
     7158            return bottomSizer
     7159               
     7160        def displayModes():
     7161           
     7162            def OnDispl(event):
     7163                '''Respond to movement of distortion mode slider'''
     7164                Obj = event.GetEventObject()
     7165                idsp,dispVal = Indx[Obj.GetId()]
     7166                modeDisp[idsp] = Obj.GetValue()/1000.
     7167                dispVal.SetValue(modeDisp[idsp])
     7168                err = G2mth.ApplyModeDisp(data)
     7169                if err:
     7170                    G2G.G2MessageBox(G2frame,'Do Draw atoms first')     
     7171                FindBondsDraw(data)               
     7172                G2plt.PlotStructure(G2frame,data)
     7173               
     7174            def OnDispVal(invalid,value,tc):
     7175                '''Respond to entry of a value into a distortion mode entry widget'''
     7176                idsp,displ = Indx[tc.GetId()]
     7177                displ.SetValue(int(value*1000))
     7178                err = G2mth.ApplyModeDisp(data)
     7179                if err:
     7180                    G2G.G2MessageBox(G2frame,'Do Draw atoms first')               
     7181                FindBondsDraw(data)               
     7182                G2plt.PlotStructure(G2frame,data)
     7183               
     7184            def OnRefDispl(event):
     7185                Obj = event.GetEventObject()
     7186                idsp = Indx[Obj.GetId()][0]
     7187                ISOdata['modeDisplFlag'][idsp] = not ISOdata['modeDisplFlag'][idsp]
     7188               
     7189            def OnReset(event):
     7190                '''Reset all distortion mode values to zero'''
     7191                ISOdata['modeDispl'] = copy.deepcopy(ISOdata['ISOmodeDispl'])
     7192                err = G2mth.ApplyModeDisp(data)
     7193                if err:
     7194                    G2G.G2MessageBox(G2frame,'Do Draw atoms first')               
     7195                FindBondsDraw(data)               
     7196                G2plt.PlotStructure(G2frame,data)
     7197                UpdateISODISTORT()
     7198           
     7199            mainSizer = wx.BoxSizer(wx.VERTICAL)
     7200            topSizer = wx.BoxSizer(wx.VERTICAL)   
     7201            topSizer.Add(wx.StaticText(ISODIST,label=ISOcite))
     7202            topSizer.Add(wx.StaticText(ISODIST,label=' ISODISTORT distortion modes for %s:'%data['General']['Name']))
     7203            lineSizer = wx.BoxSizer(wx.HORIZONTAL)           
     7204            lineSizer.Add(wx.StaticText(ISODIST,label=' Adjust magnitude of distortion modes (-2 to +2):  '),0,WACV)
     7205            reset = wx.Button(ISODIST,label='Reset modes')
     7206            reset.Bind(wx.EVT_BUTTON,OnReset)
     7207            lineSizer.Add(reset,0,WACV)
     7208            topSizer.Add(lineSizer)
     7209            slideSizer = wx.FlexGridSizer(0,4,0,0)
     7210            slideSizer.AddGrowableCol(2,1)
     7211            modeDisp = ISOdata['modeDispl']
     7212            for idsp,item in enumerate(ISOdata['G2ModeList']):
     7213                slideSizer.Add(wx.StaticText(ISODIST,label=item.name),0,WACV)
     7214                dispVal = G2G.ValidatedTxtCtrl(ISODIST,modeDisp,idsp,xmin=-2.,xmax=2.,size=(50,20),OnLeave=OnDispVal)
     7215                slideSizer.Add(dispVal,0,WACV)
     7216                displ = wx.Slider(ISODIST,style=wx.SL_HORIZONTAL,minValue=-2000,maxValue=2000,value=int(modeDisp[idsp]*1000))
     7217                displ.Bind(wx.EVT_SLIDER, OnDispl)
     7218                Indx[displ.GetId()] = [idsp,dispVal]
     7219                Indx[dispVal.GetId()] = [idsp,displ]
     7220                slideSizer.Add(displ,1,wx.EXPAND|wx.RIGHT)
     7221                refDispl = wx.CheckBox(ISODIST,label=' Refine?')
     7222                refDispl.SetValue(ISOdata['modeDisplFlag'][idsp])
     7223                refDispl.Bind(wx.EVT_CHECKBOX,OnRefDispl)
     7224                Indx[refDispl.GetId()] = [idsp]
     7225                slideSizer.Add(refDispl,0,WACV)
     7226            slideSizer.SetMinSize(wx.Size(350,10))
     7227            topSizer.Add(slideSizer)
     7228            mainSizer.Add(topSizer)
     7229            SetPhaseWindow(ISODIST,mainSizer,Scroll=Scroll)               
     7230       
     7231        Indx = {}     
     7232        ISOdata = data['ISODISTORT']
     7233        G2frame.dataWindow.ISODDataEdit.Enable(G2G.wxID_ISODNEWPHASE,'rundata' in ISOdata)
     7234        G2frame.dataWindow.ISODDataEdit.Enable(G2G.wxID_SHOWISO1,('G2VarList' in ISOdata)
     7235            or ('G2OccVarList' in ISOdata))
     7236        G2frame.dataWindow.ISODDataEdit.Enable(G2G.wxID_SHOWISOMODES,('G2VarList' in ISOdata)
     7237#           or ('G2OccVarList' in data['ISODISTORT'])
     7238                                                   )
     7239        ISOcite = ''' For use of ISODISTORT, please cite:
     7240  H. T. Stokes, D. M. Hatch, and B. J. Campbell, ISODISTORT, ISOTROPY Software Suite, iso.byu.edu.
     7241  B. J. Campbell, H. T. Stokes, D. E. Tanner, and D. M. Hatch, "ISODISPLACE: An Internet Tool for
     7242  Exploring Structural Distortions." J. Appl. Cryst. 39, 607-614 (2006).
     7243  '''
     7244        if ISODIST.GetSizer():
     7245            ISODIST.GetSizer().Clear(True)
     7246           
     7247        if 'G2ModeList' in ISOdata:      #invoked only if phase is from a ISODISTORT cif file & thus contains distortion mode constraints
     7248           
     7249#patch
     7250            if 'modeDispl' not in ISOdata:
     7251                ISOdata['modeDispl'] = np.zeros(len(ISOdata['G2ModeList']))
     7252            if 'modeDisplFlag' not in ISOdata:
     7253                ISOdata['modeDisplFlag'] = [False,]*len(ISOdata['G2ModeList'])
     7254#end patch
     7255           
     7256            displayModes()
     7257            return
     7258       
     7259#initialization
     7260        if 'ParentCIF' not in ISOdata:
     7261            ISOdata.update({'ParentCIF':'Select','ChildCIF':'Select','ISOmethod':4,
     7262                'ChildMatrix':np.eye(3),'ChildSprGp':'P 1','ChildCell':'abc',})         #these last 3 currently unused
     7263#end initialization
     7264 
     7265        mainSizer = wx.BoxSizer(wx.VERTICAL)
     7266        mainSizer.Add(wx.StaticText(ISODIST,label=ISOcite))
     7267       
     7268        mainSizer.Add(displaySetup())
     7269           
     7270        if 'radio' in ISOdata:
     7271            mainSizer.Add(displaySubset())             
     7272            mainSizer.Add(displayRadio())
    72067273        SetPhaseWindow(ISODIST,mainSizer,Scroll=Scroll)
    72077274       
     7275    def OnRunISODISTORT(event):
     7276        ''' this needs to setup for method #3 or #4 in ISODISTORT
     7277        after providing parent cif:
     7278        #3 asks for transformation matrix & space group of child structure
     7279        #4 asks for cif file of child structure
     7280        '''
     7281        radio,rundata = ISO.GetISODISTORT(data)
     7282        if radio:
     7283            data['ISODISTORT']['radio'] = radio
     7284            data['ISODISTORT']['rundata'] = rundata
     7285            data['ISODISTORT']['SGselect'] =  {'Tric':True,'Mono':True,'Orth':True,'Tetr':True,'Trig':True,'Hexa':True,'Cubi':True}
     7286            data['ISODISTORT']['selection'] = None
     7287            print('ISODISTORT run complete')
     7288            wx.CallAfter(UpdateISODISTORT)
     7289        elif data['ISODISTORT']['ISOmethod'] != 4 or radio is None:
     7290            G2G.G2MessageBox(G2frame,'ISODISTORT run failed - see page opened in web browser')
     7291        else:
     7292            G2G.G2MessageBox(G2frame,'ISODISTORT run complete; new cif file %s created.\n To use, import it as a new phase.'%rundata)
     7293            print(' ISODISTORT run complete; new cif file %s created. To use, import it as a new phase.'%rundata)
     7294               
    72087295    def OnNewISOPhase(event):
    72097296        ''' Make CIF file with ISODISTORT
    72107297        '''
    7211         import ISODISTORT as ISO
    7212 
    72137298        if 'rundata' in data['ISODISTORT'] and data['ISODISTORT']['selection'] is not None:
    72147299            CIFfile = ISO.GetISODISTORTcif(data)
     
    94909575        cell = data['General']['Cell'][1:7]
    94919576        drawingData = data['Drawing']
    9492         voidDlg = wx.Dialog(G2frame,wx.ID_ANY,
    9493                     'Void computation parameters',
    9494                     style=wx.DEFAULT_DIALOG_STYLE)
     9577        voidDlg = wx.Dialog(G2frame,wx.ID_ANY,'Void computation parameters',style=wx.DEFAULT_DIALOG_STYLE)
    94959578        mainSizer = wx.BoxSizer(wx.VERTICAL)
    94969579        mainSizer.Add(wx.StaticText(voidDlg,wx.ID_ANY,
     
    95009583        voidPar = {'a':1., 'b':1., 'c':1., 'grid':.25, 'probe':0.5}
    95019584        for i in ('a', 'b', 'c'):
    9502             mainSizer.Add(G2G.G2SliderWidget(voidDlg,voidPar,i,
    9503                 'Max '+i+' value: ',0.,xmax,100))
     9585            mainSizer.Add(G2G.G2SliderWidget(voidDlg,voidPar,i,'Max '+i+' value: ',0.,xmax,100))
    95049586        hSizer = wx.BoxSizer(wx.HORIZONTAL)
    95059587        hSizer.Add(wx.StaticText(voidDlg,wx.ID_ANY,'Grid spacing (A)'))
    9506         hSizer.Add(G2G.ValidatedTxtCtrl(voidDlg,voidPar,'grid',
    9507                 nDig=(5,2), xmin=0.1, xmax=2., typeHint=float))       
     9588        hSizer.Add(G2G.ValidatedTxtCtrl(voidDlg,voidPar,'grid',nDig=(5,2), xmin=0.1, xmax=2., typeHint=float))       
    95089589        mainSizer.Add(hSizer)
    95099590        hSizer = wx.BoxSizer(wx.HORIZONTAL)
    95109591        hSizer.Add(wx.StaticText(voidDlg,wx.ID_ANY,'Probe radius (A)'))
    9511         hSizer.Add(G2G.ValidatedTxtCtrl(voidDlg,voidPar,'probe',
    9512                 nDig=(5,2), xmin=0.1, xmax=2., typeHint=float))       
     9592        hSizer.Add(G2G.ValidatedTxtCtrl(voidDlg,voidPar,'probe',nDig=(5,2), xmin=0.1, xmax=2., typeHint=float))       
    95139593        mainSizer.Add(hSizer)
    95149594
     
    95329612        if res != wx.ID_OK: return
    95339613        drawingData['Voids'] = VoidMap(data, voidPar['a'], voidPar['b'], voidPar['c'],
    9534                           voidPar['grid'],voidPar['probe'])
     9614            voidPar['grid'],voidPar['probe'])
    95359615        drawingData['showVoids'] = True
    95369616        G2plt.PlotStructure(G2frame,data)
     
    96389718            G2frame.phaseDisplay.cameraPosTxt = cameraPosTxt
    96399719            slideSizer.Add(cameraPosTxt,0,WACV)
    9640             cameraPos = wx.Slider(drawOptions,style=wx.SL_HORIZONTAL,value=drawingData['cameraPos'],name='cameraSlider')
    9641             cameraPos.SetRange(10,500)
     9720            cameraPos = wx.Slider(drawOptions,style=wx.SL_HORIZONTAL,value=drawingData['cameraPos'],
     9721                minValue=10,maxValue=500,name='cameraSlider')
    96429722            cameraPos.Bind(wx.EVT_SLIDER, OnCameraPos)
    96439723            G2frame.phaseDisplay.cameraSlider = cameraPos
     
    96509730            G2frame.phaseDisplay.Zval = Zval
    96519731            slideSizer.Add(Zval)
    9652             Zclip = wx.Slider(drawOptions,style=wx.SL_HORIZONTAL,value=drawingData['Zclip'])
     9732            Zclip = wx.Slider(drawOptions,style=wx.SL_HORIZONTAL,value=drawingData['Zclip'],minValue=1,maxValue=99)
    96539733            G2frame.phaseDisplay.Zclip = Zclip
    9654             Zclip.SetRange(1,99)
    96559734            Zclip.Bind(wx.EVT_SLIDER, OnZclip)
    96569735            slideSizer.Add(Zclip,1,wx.EXPAND|wx.RIGHT)
     
    96939772            bondRadiusTxt = G2G.ValidatedTxtCtrl(drawOptions,drawingData,'bondRadius',nDig=(10,2),xmin=0.01,xmax=0.99,size=valSize,OnLeave=OnBondRadiusTxt)
    96949773            slideSizer.Add(bondRadiusTxt,0,WACV)
    9695             bondRadius = wx.Slider(drawOptions,style=wx.SL_HORIZONTAL,value=int(100*drawingData['bondRadius']))
    9696             bondRadius.SetRange(1,25)
     9774            bondRadius = wx.Slider(drawOptions,style=wx.SL_HORIZONTAL,value=int(100*drawingData['bondRadius']),minValue=1,maxValue=25)
    96979775            bondRadius.Bind(wx.EVT_SLIDER, OnBondRadius)
    96989776            slideSizer.Add(bondRadius,1,wx.EXPAND|wx.RIGHT)
     
    97029780                magMultTxt = G2G.ValidatedTxtCtrl(drawOptions,drawingData,'magMult',nDig=(10,2),xmin=0.1,xmax=5.,size=valSize,OnLeave=OnMagMultTxt)
    97039781                slideSizer.Add(magMultTxt,0,WACV)
    9704                 magMult = wx.Slider(drawOptions,style=wx.SL_HORIZONTAL,value=int(100*drawingData['magMult']))
    9705                 magMult.SetRange(10,500)
     9782                magMult = wx.Slider(drawOptions,style=wx.SL_HORIZONTAL,value=int(100*drawingData['magMult']),minValue=10,maxValue=500)
    97069783                magMult.Bind(wx.EVT_SLIDER, OnMagMult)
    97079784                slideSizer.Add(magMult,1,wx.EXPAND|wx.RIGHT)
     
    99069983                contourMaxTxt = wx.StaticText(drawOptions,label=' Max.: '+'%.2f'%(drawingData['contourMax']*generalData['Map']['rhoMax']))
    99079984                line3Sizer.Add(contourMaxTxt,0,WACV)
    9908                 contourMax = wx.Slider(drawOptions,style=wx.SL_HORIZONTAL,size=(150,25),value=int(100*drawingData['contourMax']))
    9909                 contourMax.SetRange(1,100)
     9985                contourMax = wx.Slider(drawOptions,style=wx.SL_HORIZONTAL,size=(150,25),
     9986                    value=int(100*drawingData['contourMax']),minValue=1,maxValue=100)
    99109987                contourMax.Bind(wx.EVT_SLIDER, OnContourMax)
    99119988                line3Sizer.Add(contourMax,1,wx.EXPAND|wx.RIGHT)
     
    1188011957                xmin=0.,xmax=360.,typeHint=float,OnLeave=UpdateOrientation))
    1188111958            OriSizer2.Add(OrientVecSiz[-1],0,WACV)
    11882             azSlide = wx.Slider(RigidBodies,style=wx.SL_HORIZONTAL,size=(200,25))
    11883             azSlide.SetRange(0,3600)
    11884             azSlide.SetValue(int(10*rbObj['OrientVec'][0]))
     11959            azSlide = wx.Slider(RigidBodies,style=wx.SL_HORIZONTAL,size=(200,25),
     11960                minValue=0,maxValue=3600,value=int(10*rbObj['OrientVec'][0]))
    1188511961            azSlide.Bind(wx.EVT_SLIDER, OnAzSlide)
    1188611962            OriSizer2.Add(azSlide,0,WACV)
     
    1192111997                            torName += data['testRBObj']['rbAtTypes'][item]+str(item)+' '
    1192211998                    TorSizer.Add(wx.StaticText(RigidBodies,label='Side chain torsion for rb seq: '+torName),0,WACV)
    11923                     torSlide = wx.Slider(RigidBodies,style=wx.SL_HORIZONTAL)
    11924                     torSlide.SetRange(0,3600)
    11925                     torSlide.SetValue(int(torsion[0]*10.))
     11999                    torSlide = wx.Slider(RigidBodies,style=wx.SL_HORIZONTAL,minValue=0,maxVaue=3600,value=int(torsion[0]*10.))
    1192612000                    torSlide.Bind(wx.EVT_SLIDER, OnTorSlide)
    1192712001                    TorSizer.Add(torSlide,1,wx.EXPAND|wx.RIGHT)
  • trunk/GSASIIplot.py

    r5120 r5130  
    62976297            # write the function values (not peaks) onto a file
    62986298            dlg = wx.FileDialog(G2frame, 'Choose CSV file to write', G2G.GetExportPath(G2frame),
    6299                     wildcard='column-separated file (*.csv)|.csv',
    6300                     style=wx.FD_CHANGE_DIR|wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
     6299                wildcard='column-separated file (*.csv)|.csv',
     6300                style=wx.FD_CHANGE_DIR|wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
    63016301            try:
    63026302                if dlg.ShowModal() == wx.ID_OK:
     
    63096309            fp.write("# Peak widths. Def. are default values from InstParms file, fit are from refined Instrument Parameters\n")
    63106310            if 'C' in Parms['Type'][0]:
    6311                 Write2csv(fp,['Q',
    6312                                 'Gauss-def','Lorenz-def,total-def',
    6313                                 'Gauss-fit','Lorenz-fit,total-fit']
    6314                                   ,header=True)
     6311                Write2csv(fp,['Q','Gauss-def','Lorenz-def,total-def',
     6312                    'Gauss-fit','Lorenz-fit,total-fit'],header=True)
    63156313                for vals in zip(Q,Y,Z,W,Yf,Zf,Wf): Write2csv(fp,vals)
    63166314            else:
    6317                 Write2csv(fp,['Q',
    6318                                 'Gauss-def','Lorenz-def',
    6319                                 'Gauss-fit','Lorenz-fit',]
    6320                                   ,header=True)
     6315                Write2csv(fp,['Q','Gauss-def','Lorenz-def','Gauss-fit','Lorenz-fit',],header=True)
    63216316                for vals in zip(Q,S,G,Sf,Gf): Write2csv(fp,vals)
    63226317            fp.close()
     
    63736368    Z = []
    63746369    W = []
     6370    Plot.set_title('Instrument peak widths')
     6371    Plot.set_xlabel(r'$Q, \AA^{-1}$',fontsize=14)
     6372    Plot.set_ylabel(r'$\Delta Q/Q, \Delta d/d$',fontsize=14)
     6373    negWarn = False
    63756374    if 'T' in Parms['Type'][0]:   #'T'OF
    6376         Plot.set_title('Instrument and sample peak coefficients')
    6377         Plot.set_xlabel(r'$Q, \AA^{-1}$',fontsize=14)
    63786375        Plot.set_ylabel(r'$\alpha, \beta, \Delta Q/Q, \Delta d/d$',fontsize=14)
    63796376        Xmin,Xmax = limits[1]
     
    63836380        ds = T/difC
    63846381        Q = 2.*np.pi/ds
     6382        for did in [4,6,8,10]:
     6383            if np.any(data[did] < 0.):
     6384                negWarn = True
    63856385        A = data[4]
    63866386        B = data[6]
     
    63956395        ds = T/difC
    63966396        Q = 2.*np.pi/ds
     6397        for did in [4,6,8,10]:
     6398            if np.any(fit[did] < 0.):
     6399                negWarn = True
    63976400        Af = fit[4]
    63986401        Bf = fit[6]
     
    64276430    elif 'E' in Parms['Type'][0]:
    64286431        isig = 4
    6429         Plot.set_title('Instrument and sample peak widths')
    6430         Plot.set_xlabel(r'$Q, \AA^{-1}$',fontsize=14)
    6431         Plot.set_ylabel(r'$\Delta Q/Q, \Delta d/d$',fontsize=14)
    64326432        Xmin,Xmax = limits[1]
    64336433        X = np.linspace(Xmin,Xmax,num=101,endpoint=True)
     
    64356435        Z = np.ones_like(X)
    64366436        data = G2mth.setPeakparms(Parms,Parms2,X,Z)
     6437        if np.any(data[isig] < 0.):
     6438            negWarn = True
    64376439        s = np.sqrt(data[isig])   #var -> sig(radians)
    64386440        Y = sq8ln2*s/X
     
    64406442       
    64416443        fit = G2mth.setPeakparms(Parms,Parms2,X,Z,useFit=True)
     6444        if np.any(fit[isig] < 0.):
     6445            negWarn = True
    64426446        sf = np.sqrt(fit[isig])
    64436447        Yf = sq8ln2*sf/X
     
    64666470            igam = 10
    64676471        Plot.figure.suptitle(TreeItemText)
    6468         Plot.set_title('Instrument and sample peak widths')
    6469         Plot.set_xlabel(r'$Q, \AA^{-1}$',fontsize=14)
    6470         Plot.set_ylabel(r'$\Delta Q/Q, \Delta d/d$',fontsize=14)
    64716472        Xmin,Xmax = limits[1]
    64726473        X = np.linspace(Xmin,Xmax,num=101,endpoint=True)
     
    64746475        Z = np.ones_like(X)
    64756476        data = G2mth.setPeakparms(Parms,Parms2,X,Z)
     6477        for did in [isig,igam]:
     6478            if np.any(data[did] < 0.):
     6479                negWarn = True
    64766480        s = np.sqrt(data[isig])*np.pi/18000.   #var -> sig(radians)
    64776481        g = data[igam]*np.pi/18000.    #centideg -> radians
     
    64856489       
    64866490        fit = G2mth.setPeakparms(Parms,Parms2,X,Z,useFit=True)
     6491        for did in [isig,igam]:
     6492            if np.any(fit[did] < 0.):
     6493                negWarn = True
    64876494        sf = np.sqrt(fit[isig])*np.pi/18000.
    64886495        gf = fit[igam]*np.pi/18000.
     
    65176524        SetupLegendPick(legend,new)
    65186525        Page.canvas.draw()
     6526    if negWarn:
     6527        Plot.set_title('WARNING: profile coefficients yield negative peak widths; peaks may be skipped in calcuations')
    65196528       
    65206529    if xylim and not G2frame.G2plotNB.allowZoomReset:
  • trunk/GSASIIpwd.py

    r5124 r5130  
    905905    yb = np.zeros_like(xdata)
    906906    nBak = 0
    907     # cw = np.diff(xdata)
    908     # cw = np.append(cw,cw[-1])
    909907    sumBk = [0.,0.,0]
    910908    while True:
     
    10091007                iFin = np.searchsorted(xdata,pkP+fmax)
    10101008            if 'C' in dataType:
    1011                 # ybi = pkI*getFCJVoigt3(pkP,pkS,pkG,0.002,xdata[iBeg:iFin])[0]
    1012                 # yb[iBeg:iFin] += ybi/cw[iBeg:iFin]
    10131009                ybi = pkI*getFCJVoigt3(pkP,pkS,pkG,0.002,xdata[iBeg:iFin])[0]
    10141010                yb[iBeg:iFin] += ybi
     
    10491045    dydpk = np.zeros(shape=(4*parmDict[hfx+'nPeaks'],len(xdata)))
    10501046    dydfb = []
    1051     # cw = np.diff(xdata)
    1052     # cw = np.append(cw,cw[-1])
    10531047
    10541048    if bakType in ['chebyschev','cosine','chebyschev-1']:
     
    11461140            if 'C' in dataType:
    11471141                Df,dFdp,dFds,dFdg,x = getdFCJVoigt3(pkP,pkS,pkG,.002,xdata[iBeg:iFin])
    1148                 # dydpk[4*iD][iBeg:iFin] += 100.*cw[iBeg:iFin]*pkI*dFdp
    1149                 # dydpk[4*iD+1][iBeg:iFin] += 100.*cw[iBeg:iFin]*Df
    1150                 # dydpk[4*iD+2][iBeg:iFin] += 100.*cw[iBeg:iFin]*pkI*dFds
    1151                 # dydpk[4*iD+3][iBeg:iFin] += 100.*cw[iBeg:iFin]*pkI*dFdg
    1152                 dydpk[4*iD][iBeg:iFin] += pkI*dFdp
    1153                 dydpk[4*iD+1][iBeg:iFin] += Df
    1154                 dydpk[4*iD+2][iBeg:iFin] += pkI*dFds
    1155                 dydpk[4*iD+3][iBeg:iFin] += pkI*dFdg
    11561142            else:   #'T'OF
    11571143                Df,dFdp,x,x,dFds,dFdg = getdEpsVoigt(pkP,1.,1.,pkS,pkG,xdata[iBeg:iFin])
    1158                 dydpk[4*iD][iBeg:iFin] += pkI*dFdp
    1159                 dydpk[4*iD+1][iBeg:iFin] += Df
    1160                 dydpk[4*iD+2][iBeg:iFin] += pkI*dFds
    1161                 dydpk[4*iD+3][iBeg:iFin] += pkI*dFdg
     1144            dydpk[4*iD][iBeg:iFin] += pkI*dFdp
     1145            dydpk[4*iD+1][iBeg:iFin] += Df
     1146            dydpk[4*iD+2][iBeg:iFin] += pkI*dFds
     1147            dydpk[4*iD+3][iBeg:iFin] += pkI*dFdg
    11621148            iD += 1       
    11631149        except KeyError:
  • trunk/ISODISTORT.py

    r5112 r5130  
    1515from __future__ import division, print_function
    1616import subprocess as subp
     17import os
    1718import os.path
    1819import requests
    1920import copy
     21import GSASIIscriptable as G2sc
     22import tempfile
    2023isouploadsite = 'https://stokes.byu.edu/iso/isodistortuploadfile.php'
    2124isoformsite = 'https://iso.byu.edu/iso/isodistortform.php'
     
    3134        except:
    3235            print('Could not open URL')
    33 
    34 def GetISODISTORT(Phase,parentcif,method=1):
     36           
     37def UploadCIF(cifname):
     38       #upload cif file to BYU web site
     39    ciffile = open(cifname,'rb')
     40    up1 = {'toProcess':(cifname,ciffile),}
     41    out1 = requests.post(isouploadsite,files=up1).text
     42    ciffile.close()
     43   
     44    #retrieve BYU temp file name for cif file   
     45   
     46    pos = out1.index('<INPUT')+7
     47    pos1 = out1.index('VALUE=',pos)+7
     48    filename = out1[pos1:out1.index('"',pos1)]
     49   
     50    print('ciffile %s uploaded to ISODISTORT to make %s'%(cifname,filename))
     51    return filename
     52
     53def MakePhaseCif(data):
     54    data['pId'] = data.get('pId',0) # needs a pId
     55    proj = G2sc.G2Project(newgpx='tmp4cif.gpx')
     56    ph = G2sc.G2Phase(data,data['General']['Name'],proj)
     57    tempcif = 'ISOin.cif'
     58    ph.export_CIF(tempcif)
     59    return tempcif
     60
     61def GetISODISTORT(Phase):
    3562    '''Run Stokes & Campbell ISODISTORT.
    3663    This requires doing a post to the BYU upload site with a cif file, which returns a BYU local
     
    4269
    4370    :params dict Phase: GSAS-II phase data
    44     :params str parentcif: parent cif file name - should be local to working directory
    4571
    4672    :returns: radio: dict of possible distortion structures
     
    5581    ''')
    5682                   
    57    
    58     #upload cif file to BYU web site
    59      
    60     up1 = {'toProcess':(parentcif,open(parentcif,'rb')),}
    61     out1 = requests.post(isouploadsite,files=up1).text
    62    
    63     #retrieve BYU temp file name for cif file   
    64    
    65     pos = out1.index('<INPUT')+7
    66     pos1 = out1.index('VALUE=',pos)+7
    67     filename = out1[pos1:out1.index('"',pos1)]
    68    
    69     print('filename=',filename)
     83    ISOdata = Phase['ISODISTORT']
     84    parentcif = ISOdata['ParentCIF']
     85    childcif = None
     86    if 'Use this phase' in parentcif:
     87        parentcif = MakePhaseCif(Phase)
     88    print(' Run ISODISTORT with %s as parent cif'%parentcif)
     89    ISOparentcif = UploadCIF(parentcif)
    7090   
    7191    #submit cif for processing by ISODISTORT
    7292   
    73     up2 = {'filename':filename,'input':'uploadparentcif'}
     93    up2 = {'filename':ISOparentcif,'input':'uploadparentcif'}
    7494    out2 = requests.post(isoformsite,up2).text
    7595   
    76     ISOdata = Phase['ISODISTORT']
    7796    #recover required info for the distortion search; includes info from cif file (no longer needed)
    78     if method == 1:
    79         try:
    80             pos = out2.index('<p><FORM')
    81         except ValueError:
    82             HandleError(out2)
    83             return [],[]
    84         data = {}
    85         while True:
    86             try:
    87                 posB = out2[pos:].index('INPUT TYPE')+pos
    88                 posF = out2[posB:].index('>')+posB
    89                 items = out2[posB:posF].split('=',3)
    90                 name = items[2].split()[0].replace('"','')
    91                 if 'isosystem' in name:
    92                     break
    93                 vals = items[3].replace('"','')
    94                 data[name] = vals
    95                 pos = posF
    96             except ValueError:
     97    try:
     98        pos = out2.index('<p><FORM')
     99    except ValueError:
     100        HandleError(out2)
     101        return [],[]
     102    data = {}
     103    while True:
     104        try:
     105            posB = out2[pos:].index('INPUT TYPE')+pos
     106            posF = out2[posB:].index('>')+posB
     107            items = out2[posB:posF].split('=',3)
     108            name = items[2].split()[0].replace('"','')
     109            if 'isosystem' in name:
    97110                break
    98         #save copy for future use
    99         data2 = copy.deepcopy(data)
    100                
    101         #no limits on space group or lattice
    102        
     111            vals = items[3].replace('"','')
     112            data[name] = vals
     113            pos = posF
     114        except ValueError:
     115            break
     116    #save copy for future use
     117    data2 = copy.deepcopy(data)
     118           
     119    #no limits on space group or lattice
     120       
     121    if ISOdata['ISOmethod'] == 1:
    103122        data['isosubgroup'] = 'no choice'
    104123        data['isolattice'] = 'no choice'
    105124        data['isoplattice'] = 'no choice'
    106    
     125       
     126    elif ISOdata['ISOmethod'] == 3:
     127        print('method  3 TBD')
     128        return [],[]
     129    elif ISOdata['ISOmethod'] == 4:
     130        childcif = ISOdata['ChildCIF']
     131        if 'Use this phase' in childcif:
     132            childcif = MakePhaseCif(Phase)
     133        print(' Run ISODISTORT with %s as child cif'%childcif)
     134        ISOchildcif = UploadCIF(childcif)
     135        data['input'] = 'uploadsubgroupcif'
     136        data['filename'] = ISOchildcif
     137        out24 = requests.post(isoformsite,data=data).text
     138        posB = out24.index('OPTION VALUE=')
     139        posF = out24[posB:].index('>')+posB
     140        value = out24[posB+13:posF]
     141        data['input'] = 'distort'
     142        data['origintype'] = 'method4'
     143        data['inputbasis'] = 'list'
     144        data['basisselect'] = value[1:-1]
     145        data['chooseorigin'] = False
     146        data['trynearest'] = True
     147        data['dmax'] = '1'
     148        out25 = requests.post(isoformsite,data=data).text
     149        cifout = GetISOcif(out25,4)
     150        if cifout is None:
     151            return None,None
     152        cifFile = '%s_%s.cif'%(Phase['General']['Name'],'child')
     153        fl = open(cifFile,'wb')
     154        fl.write(cifout.encode("utf-8"))
     155        fl.close()
     156        return [],cifFile
     157       
    107158    #do the distortion search - result is radio button list of choices
    108159   
     
    124175            num += 1
    125176            items = out3[pos:posF].split('=',2)[2].split('>')[0]
    126             radio['orderparam%d'%num] = items.replace('"','')
     177            radio['orderparam%d'%num] = items.replace('"','').replace('CHECKED','')
    127178            pos = out3[posF:].index('RADIO')+posF
    128179        except ValueError:
    129180            break
     181       
     182    if parentcif == 'ISOin.cif' or childcif == 'ISOin.cif':
     183        os.remove('ISOin.cif')
    130184   
    131185    return radio,data2
    132186
    133 def GetISODISTORTcif(Phase):
    134     '''Run Stokes & Campbell ISODISTORT.
    135     Selection of one of the order parameter disrections is returned to the BYU
    136     form site which returns the text of a cif file to be used to create the new phase
    137     which can apply the distortion mode constraints
    138      
    139     :params dict Phase: GSAS-II phase data; contains result of GetISODISTORT above & selection
    140    
    141     :returns: CIFfile str: name of cif file created by this in local directory
    142     '''
    143    
    144     ISOdata = Phase['ISODISTORT']
    145     data2 = ISOdata['rundata']
    146     #choose one & resubmit
    147     data2['origintype'] = 'method1'
    148     data2['orderparam'] = ISOdata['selection'][1]
    149     data2['input'] = 'distort'
    150     # for item in data2:
    151     #     print(item,data2[item])
    152     out4 = requests.post(isoformsite,data=data2).text
    153     #print(out4)
    154     #open('pyout4.html','wb').write(out4.encode("utf-8"))
    155      
    156     #retrieve data needed for next(last) step
    157 
     187def GetISOcif(out4,method):
     188   
    158189    try:
    159190        pos = out4.index('<FORM ACTION')
    160191    except ValueError:
    161192        HandleError(out4)
     193        return None
    162194    data3 = {}
    163195    while True:
     
    178210            data3[name] = vals
    179211            pos = posF
    180             if 'lattparamsub' in name:
     212            if 'origintype' in name:
    181213                break
    182214        except ValueError:
    183215            break
     216    if method == 4:
     217        try:
     218            pos = out4[posF:].index('Enter mode')+posF
     219            pos = out4[pos:].index('<p>')+pos
     220        except ValueError:
     221            HandleError(out4)
     222        while True:
     223            try:
     224                posB = out4[pos:].index('name')+pos
     225                posF = out4[posB:].index('>')+posB
     226                items = out4[posB:posF].split('=')
     227                name = items[1].split()[0].replace('"','')
     228                if name == 'atomicradius':
     229                    break
     230                vals = items[2].split()[0].replace('"','')
     231                data3[name] = vals
     232                pos = posF
     233            except ValueError:
     234                break
     235        data3['zeromodes'] = False
    184236       
    185237   #request a cif file   
     
    196248    out5 = k.text   #this is output cif!
    197249    #print(out5)
     250    return out5
     251   
     252
     253def GetISODISTORTcif(Phase):
     254    '''Run Stokes & Campbell ISODISTORT.
     255    Selection of one of the order parameter disrections is returned to the BYU
     256    form site which returns the text of a cif file to be used to create the new phase
     257    which can apply the distortion mode constraints
     258     
     259    :params dict Phase: GSAS-II phase data; contains result of GetISODISTORT above & selection
     260   
     261    :returns: CIFfile str: name of cif file created by this in local directory
     262    '''
     263   
     264    ISOdata = Phase['ISODISTORT']
     265    data2 = ISOdata['rundata']
     266    #choose one & resubmit
     267    data2['origintype'] = 'method1'
     268    data2['orderparam'] = ISOdata['selection'][1]
     269    data2['input'] = 'distort'
     270    # for item in data2:
     271    #     print(item,data2[item])
     272    out4 = requests.post(isoformsite,data=data2).text
     273    #print(out4)
     274    #open('pyout4.html','wb').write(out4.encode("utf-8"))
     275     
     276    #retrieve data needed for next(last) step
     277   
     278    out5 = GetISOcif(out4,1)
    198279    names = ISOdata['selection'][1].split()
    199280    cifFile = '%s_%s%s%s.cif'%(Phase['General']['Name'],names[1],names[2].replace('*','_'),names[3])
     
    201282    fl.write(out5.encode("utf-8"))
    202283    fl.close()
     284
    203285    return cifFile
  • trunk/imports/G2phase_CIF.py

    r5112 r5130  
    697697            modelist = []
    698698            shortmodelist = []
     699            modedispl = []
    699700            idlist = []
    700             for id,lbl in zip(
     701            for id,lbl,val in zip(
    701702                blk.get('_iso_displacivemode_ID'),
    702                 blk.get('_iso_displacivemode_label')):
     703                blk.get('_iso_displacivemode_label'),
     704                blk.get('_iso_displacivemode_value')):
    703705                idlist.append(int(id))
    704706                modelist.append(lbl)
     707                modedispl.append(float(val))
    705708                ISODISTORT_shortLbl(lbl,shortmodelist) # shorten & make unique
    706709            # just in case the items are not ordered increasing by id, sort them here
     
    750753                blk.get('_iso_deltacoordinate_ID'),
    751754                blk.get('_iso_deltacoordinate_label'),
    752                 blk.get('_iso_deltacoordinate_value')
    753                 ):
     755                blk.get('_iso_deltacoordinate_value') ):
    754756                idlist.append(int(id))
    755757                coordVarLbl.append(lbl)
     
    807809            # create the constraints
    808810            modeVarList = []
    809             modeDispl = []
    810811            for i,(row,norm) in enumerate(zip(Var2ModeMatrix,normlist)):
    811812                constraint = []
     
    818819                constraint += [modeVar,False,'f']
    819820                self.Constraints.append(constraint)
    820                 modeDispl.append(0.0)
    821821            #----------------------------------------------------------------------
    822822            # save the ISODISTORT info for "mode analysis"
     
    826826                'IsoVarList' : coordVarLbl,
    827827                'G2VarList' : G2varObj,
    828                 'G2coordOffset' : G2coordOffset,
     828                'G2coordOffset' : G2coordOffset,
     829                'G2parentCoords' : [ParentCoordinates[item] for item in ParentCoordinates], #Assumes python 3.7 dict ordering!
    829830                # mode items
    830831                'IsoModeList' : modelist,
    831832                'G2ModeList' : modeVarList,
    832833                'NormList' : normlist,
     834                'modeDispl' : modedispl,
     835                'ISOmodeDispl' : copy.deepcopy(modedispl),
    833836                # transform matrices
    834837                'Var2ModeMatrix' : Var2ModeMatrix,
    835838                'Mode2VarMatrix' : displacivemodematrix,
    836                 'modeDispl' : modeDispl
    837839                })
    838840            # make explaination dictionary
Note: See TracChangeset for help on using the changeset viewer.