source: trunk/GSASIIIO.py @ 2026

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

autoint minimal, but ready for testing; fixes to Exports

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 114.9 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2015-10-28 22:32:01 +0000 (Wed, 28 Oct 2015) $
4# $Author: toby $
5# $Revision: 2026 $
6# $URL: trunk/GSASIIIO.py $
7# $Id: GSASIIIO.py 2026 2015-10-28 22:32:01Z toby $
8########### SVN repository information ###################
9'''
10*GSASIIIO: Misc I/O routines*
11=============================
12
13Module with miscellaneous routines for input and output. Many
14are GUI routines to interact with user.
15
16Includes support for image reading.
17
18Also includes base classes for data import routines.
19
20'''
21"""GSASIIIO: functions for IO of data
22   Copyright: 2008, Robert B. Von Dreele (Argonne National Laboratory)
23"""
24import wx
25import math
26import numpy as np
27import cPickle
28import sys
29import re
30import random as ran
31import GSASIIpath
32GSASIIpath.SetVersionNumber("$Revision: 2026 $")
33import GSASIIgrid as G2gd
34import GSASIIspc as G2spc
35import GSASIIobj as G2obj
36import GSASIIlattice as G2lat
37import GSASIIpwdGUI as G2pdG
38import GSASIIimage as G2img
39import GSASIIElem as G2el
40import GSASIIstrIO as G2stIO
41import GSASIImapvars as G2mv
42import GSASIIctrls as G2G
43import os
44import os.path as ospath
45
46DEBUG = False       #=True for various prints
47TRANSP = False      #=true to transpose images for testing
48if GSASIIpath.GetConfigValue('Transpose'): TRANSP = True
49npsind = lambda x: np.sin(x*np.pi/180.)
50
51def sfloat(S):
52    'Convert a string to float. An empty field or a unconvertable value is treated as zero'
53    if S.strip():
54        try:
55            return float(S)
56        except ValueError:
57            pass
58    return 0.0
59
60def sint(S):
61    'Convert a string to int. An empty field is treated as zero'
62    if S.strip():
63        return int(S)
64    else:
65        return 0
66
67def trim(val):
68    '''Simplify a string containing leading and trailing spaces
69    as well as newlines, tabs, repeated spaces etc. into a shorter and
70    more simple string, by replacing all ranges of whitespace
71    characters with a single space.
72
73    :param str val: the string to be simplified
74
75    :returns: the (usually) shortened version of the string
76    '''
77    return re.sub('\s+', ' ', val).strip()
78
79def makeInstDict(names,data,codes):
80    inst = dict(zip(names,zip(data,data,codes)))
81    for item in inst:
82        inst[item] = list(inst[item])
83    return inst
84
85def FileDlgFixExt(dlg,file):
86    'this is needed to fix a problem in linux wx.FileDialog'
87    ext = dlg.GetWildcard().split('|')[2*dlg.GetFilterIndex()+1].strip('*')
88    if ext not in file:
89        file += ext
90    return file
91       
92def GetPowderPeaks(fileName):
93    'Read powder peaks from a file'
94    sind = lambda x: math.sin(x*math.pi/180.)
95    asind = lambda x: 180.*math.asin(x)/math.pi
96    Cuka = 1.54052
97    File = open(fileName,'Ur')
98    Comments = []
99    peaks = []
100    S = File.readline()
101    while S:
102        if S[:1] == '#':
103            Comments.append(S[:-1])
104        else:
105            item = S.split()
106            if len(item) == 1:
107                peaks.append([float(item[0]),1.0])
108            elif len(item) > 1:
109                peaks.append([float(item[0]),float(item[0])])
110        S = File.readline()
111    File.close()
112    if Comments:
113       print 'Comments on file:'
114       for Comment in Comments: print Comment
115    Peaks = []
116    if peaks[0][0] > peaks[-1][0]:          # d-spacings - assume CuKa
117        for peak in peaks:
118            dsp = peak[0]
119            sth = Cuka/(2.0*dsp)
120            if sth < 1.0:
121                tth = 2.0*asind(sth)
122            else:
123                break
124            Peaks.append([tth,peak[1],True,False,0,0,0,dsp,0.0])
125    else:                                   #2-thetas - assume Cuka (for now)
126        for peak in peaks:
127            tth = peak[0]
128            dsp = Cuka/(2.0*sind(tth/2.0))
129            Peaks.append([tth,peak[1],True,False,0,0,0,dsp,0.0])
130    return Comments,Peaks
131
132def CheckImageFile(G2frame,imagefile):
133    '''Try to locate an image file if the project and image have been moved
134    together. If the image file cannot be found, request the location from
135    the user.
136
137    :param wx.Frame G2frame: main GSAS-II Frame and data object
138    :param str imagefile: name of image file
139    :returns: imagefile, if it exists, or the name of a file
140      that does exist or False if the user presses Cancel
141
142    '''
143    if not os.path.exists(imagefile):
144        print 'Image file '+imagefile+' not found'
145        fil = imagefile.replace('\\','/') # windows?!
146        # see if we can find a file with same name or in a similarly named sub-dir
147        pth,fil = os.path.split(fil)
148        prevpth = None
149        while pth and pth != prevpth:
150            prevpth = pth
151            if os.path.exists(os.path.join(G2frame.dirname,fil)):
152                print 'found image file '+os.path.join(G2frame.dirname,fil)
153                return os.path.join(G2frame.dirname,fil)
154            pth,enddir = os.path.split(pth)
155            fil = os.path.join(enddir,fil)
156        # not found as a subdirectory, drop common parts of path for last saved & image file names
157        #    if image was .../A/B/C/imgs/ima.ge
158        #      & GPX was  .../A/B/C/refs/fil.gpx but is now .../NEW/TEST/TEST1
159        #    will look for .../NEW/TEST/TEST1/imgs/ima.ge, .../NEW/TEST/imgs/ima.ge, .../NEW/imgs/ima.ge and so on
160        Controls = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,G2frame.root, 'Controls'))
161        gpxPath = Controls.get('LastSavedAs','').replace('\\','/').split('/') # blank in older .GPX files
162        imgPath = imagefile.replace('\\','/').split('/')
163        for p1,p2 in zip(gpxPath,imgPath):
164            if p1 == p2:
165                gpxPath.pop(0),imgPath.pop(0)
166            else:
167                break
168        fil = os.path.join(*imgPath) # file with non-common prefix elements
169        prevpth = None
170        pth = os.path.abspath(G2frame.dirname)
171        while pth and pth != prevpth:
172            prevpth = pth
173            if os.path.exists(os.path.join(pth,fil)):
174                print 'found image file '+os.path.join(pth,fil)
175                return os.path.join(pth,fil)
176            pth,enddir = os.path.split(pth)
177        #GSASIIpath.IPyBreak()
178
179    if not os.path.exists(imagefile):
180        dlg = wx.FileDialog(G2frame, 'Previous image file not found; open here', '.', '',\
181        'Any image file (*.edf;*.tif;*.tiff;*.mar*;*.ge*;*.avg;*.sum;*.img;*.cor;*.stl)\
182        |*.edf;*.tif;*.tiff;*.mar*;*.ge*;*.avg;*.sum;*.img;*.cor;*.stl|\
183        European detector file (*.edf)|*.edf|\
184        Any detector tif (*.tif;*.tiff)|*.tif;*.tiff|\
185        MAR file (*.mar*)|*.mar*|\
186        GE Image (*.ge*;*.avg;*.sum;*.cor)|*.ge*;*.avg;*.sum;*.cor|\
187        ADSC Image (*.img)|*.img|\
188        Rigaku-Axis4 (*.stl)|*.stl|\
189        All files (*.*)|*.*',wx.OPEN|wx.CHANGE_DIR)
190        try:
191            dlg.SetFilename(''+ospath.split(imagefile)[1])
192            if dlg.ShowModal() == wx.ID_OK:
193                imagefile = dlg.GetPath()
194            else:
195                imagefile = False
196        finally:
197            dlg.Destroy()
198    return imagefile
199
200def EditImageParms(parent,Data,Comments,Image,filename):
201    dlg = wx.Dialog(parent, wx.ID_ANY, 'Edit image parameters',
202                    style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
203    def onClose(event):
204        dlg.EndModal(wx.ID_OK)
205    mainsizer = wx.BoxSizer(wx.VERTICAL)
206    h,w = Image.shape[:2]
207    mainsizer.Add(wx.StaticText(dlg,wx.ID_ANY,
208                                'File '+str(filename)+'\nImage size: '+str(h)+' x '+str(w)),
209                  0,wx.ALIGN_LEFT|wx.ALL, 2)
210   
211    vsizer = wx.BoxSizer(wx.HORIZONTAL)
212    vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'Wavelength (\xC5) '),
213               0,wx.ALIGN_LEFT|wx.ALL, 2)
214    wdgt = G2G.ValidatedTxtCtrl(dlg,Data,'wavelength')
215    vsizer.Add(wdgt)
216    mainsizer.Add(vsizer,0,wx.ALIGN_LEFT|wx.ALL, 2)
217
218    vsizer = wx.BoxSizer(wx.HORIZONTAL)
219    vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'Pixel size (\xb5m). Width '),
220               0,wx.ALIGN_LEFT|wx.ALL, 2)
221    wdgt = G2G.ValidatedTxtCtrl(dlg,Data['pixelSize'],0,
222                                 size=(50,-1))
223    vsizer.Add(wdgt)
224    vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'  Height '),
225               wx.ALIGN_LEFT|wx.ALL, 2)
226    wdgt = G2G.ValidatedTxtCtrl(dlg,Data['pixelSize'],1,
227                                 size=(50,-1))
228    vsizer.Add(wdgt)
229    mainsizer.Add(vsizer,0,wx.ALIGN_LEFT|wx.ALL, 2)
230
231    vsizer = wx.BoxSizer(wx.HORIZONTAL)
232    vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'Sample to detector (mm) '),
233               0,wx.ALIGN_LEFT|wx.ALL, 2)
234    wdgt = G2G.ValidatedTxtCtrl(dlg,Data,'distance')
235    vsizer.Add(wdgt)
236    mainsizer.Add(vsizer,0,wx.ALIGN_LEFT|wx.ALL, 2)
237
238    vsizer = wx.BoxSizer(wx.HORIZONTAL)
239    vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'Beam center (pixels). X = '),
240               0,wx.ALIGN_LEFT|wx.ALL, 2)
241    wdgt = G2G.ValidatedTxtCtrl(dlg,Data['center'],0,
242                                 size=(75,-1))
243    vsizer.Add(wdgt)
244    vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'  Y = '),
245               wx.ALIGN_LEFT|wx.ALL, 2)
246    wdgt = G2G.ValidatedTxtCtrl(dlg,Data['center'],1,
247                                 size=(75,-1))
248    vsizer.Add(wdgt)
249    mainsizer.Add(vsizer,0,wx.ALIGN_LEFT|wx.ALL, 2)
250
251    vsizer = wx.BoxSizer(wx.HORIZONTAL)
252    vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'Comments '),
253               0,wx.ALIGN_LEFT|wx.ALL, 2)
254    wdgt = G2G.ValidatedTxtCtrl(dlg,Comments,0,size=(250,-1))
255    vsizer.Add(wdgt)
256    mainsizer.Add(vsizer,0,wx.ALIGN_LEFT|wx.ALL, 2)
257
258    btnsizer = wx.StdDialogButtonSizer()
259    OKbtn = wx.Button(dlg, wx.ID_OK, 'Continue')
260    OKbtn.SetDefault()
261    OKbtn.Bind(wx.EVT_BUTTON,onClose)
262    btnsizer.AddButton(OKbtn) # not sure why this is needed
263    btnsizer.Realize()
264    mainsizer.Add(btnsizer, 1, wx.ALIGN_CENTER|wx.ALL|wx.EXPAND, 5)
265    dlg.SetSizer(mainsizer)
266    dlg.CenterOnParent()
267    dlg.ShowModal()
268   
269def ReadLoadImage(imagefile,G2frame):
270    '''Read a GSAS-II image file and load it into the data tree
271    '''
272    # if a zip file, open and extract
273    if os.path.splitext(imagefile)[1].lower() == '.zip':
274        extractedfile = ExtractFileFromZip(imagefile,parent=G2frame)
275        if extractedfile is not None and extractedfile != imagefile:
276            imagefile = extractedfile
277    Comments,Data,Npix,Image = GetImageData(G2frame,imagefile)
278    if Comments:
279        LoadImage2Tree(imagefile,G2frame,Comments,Data,Npix,Image)
280   
281def LoadImage2Tree(imagefile,G2frame,Comments,Data,Npix,Image):
282    '''Load an image into the tree
283    '''
284   
285    ImgNames = []
286    if G2frame.PatternTree.GetCount(): # get a list of existing Image entries
287        item, cookie = G2frame.PatternTree.GetFirstChild(G2frame.root)
288        while item:
289            name = G2frame.PatternTree.GetItemText(item)
290            if name.startswith('IMG'): ImgNames.append(name)       
291            item, cookie = G2frame.PatternTree.GetNextChild(G2frame.root, cookie)
292    TreeName = G2obj.MakeUniqueLabel('IMG '+os.path.basename(imagefile),ImgNames)
293    Id = G2frame.PatternTree.AppendItem(parent=G2frame.root,text=TreeName)
294    G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Comments'),Comments)
295    Imax = np.amax(Image)
296    Imin = max(0.0,np.amin(Image))          #force positive
297    if G2frame.imageDefault:
298        Data = copy.copy(G2frame.imageDefault)
299        Data['showLines'] = True
300        Data['ring'] = []
301        Data['rings'] = []
302        Data['cutoff'] = 10
303        Data['pixLimit'] = 20
304        Data['edgemin'] = 100000000
305        Data['calibdmin'] = 0.5
306        Data['calibskip'] = 0
307        Data['ellipses'] = []
308        Data['calibrant'] = ''
309        Data['GonioAngles'] = [0.,0.,0.]
310        Data['DetDepthRef'] = False
311    else:
312        Data['type'] = 'PWDR'
313        Data['color'] = 'Paired'
314        Data['tilt'] = 0.0
315        Data['rotation'] = 0.0
316        Data['showLines'] = False
317        Data['ring'] = []
318        Data['rings'] = []
319        Data['cutoff'] = 10
320        Data['pixLimit'] = 20
321        Data['calibdmin'] = 0.5
322        Data['calibskip'] = 0
323        Data['edgemin'] = 100000000
324        Data['ellipses'] = []
325        Data['GonioAngles'] = [0.,0.,0.]
326        Data['DetDepth'] = 0.
327        Data['DetDepthRef'] = False
328        Data['calibrant'] = ''
329        Data['IOtth'] = [2.0,5.0]
330        Data['LRazimuth'] = [135,225]
331        Data['azmthOff'] = 0.0
332        Data['outChannels'] = 2500
333        Data['outAzimuths'] = 1
334        Data['centerAzm'] = False
335        Data['fullIntegrate'] = False
336        Data['setRings'] = False
337        Data['background image'] = ['',-1.0]                           
338        Data['dark image'] = ['',-1.0]
339        Data['Flat Bkg'] = 0.0
340    Data['setDefault'] = False
341    Data['range'] = [(Imin,Imax),[Imin,Imax]]
342    G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Image Controls'),Data)
343    Masks = {'Points':[],'Rings':[],'Arcs':[],'Polygons':[],'Frames':[],'Thresholds':[(Imin,Imax),[Imin,Imax]]}
344    G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Masks'),Masks)
345    G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Stress/Strain'),
346        {'Type':'True','d-zero':[],'Sample phi':0.0,'Sample z':0.0,'Sample load':0.0})
347    G2frame.PatternTree.SetItemPyData(Id,[Npix,imagefile])
348    G2frame.PickId = Id
349    G2frame.PickIdText = G2frame.GetTreeItemsList(G2frame.PickId)
350    G2frame.Image = Id
351   
352def ReadImageData(G2frame,imagefile,imageOnly=False):
353    '''Read a single image with an image importer. Replacement for GetImageData
354
355    :param wx.Frame G2frame: main GSAS-II Frame and data object.
356    :param str imagefile: name of image file
357    :param bool imageOnly: If True return only the image,
358      otherwise  (default) return more (see below)
359
360    :returns: an image as a numpy array or a list of four items:
361      Comments, Data, Npix and the Image, as selected by imageOnly
362
363    '''
364    # determine which formats are compatible with this file
365    print 'Debug: using ReadImageData'
366    primaryReaders = []
367    secondaryReaders = []
368    for rd in G2frame.ImportImageReaderlist:
369        flag = rd.ExtensionValidator(imagefile)
370        if flag is None: 
371            secondaryReaders.append(rd)
372        elif flag:
373            primaryReaders.append(rd)
374    if len(secondaryReaders) + len(primaryReaders) == 0:
375        print('Error: No matching format for file '+filename)
376        raise Exception('No image read')
377    fp = None
378    errorReport = ''
379    fp = open(imagefile,'Ur')
380    for rd in primaryReaders+secondaryReaders:
381        rd.ReInitialize() # purge anything from a previous read
382        fp.seek(0)  # rewind
383        rd.errors = "" # clear out any old errors
384        if not rd.ContentsValidator(fp): # rejected on cursory check
385            errorReport += "\n  "+rd.formatName + ' validator error'
386            if rd.errors: 
387                errorReport += ': '+rd.errors
388                continue 
389        rdbuffer = {} # create temporary storage for file reader
390        if imageOnly:
391            ParentFrame = None # prevent GUI access on reread
392        else:
393            ParentFrame = G2frame
394        if GSASIIpath.GetConfigValue('debug'):
395            flag = rd.Reader(imagefile,fp,ParentFrame)
396        else:
397            flag = False
398            try:
399                flag = rd.Reader(imagefile,fp,ParentFrame)
400            except rd.ImportException as detail:
401                rd.errors += "\n  Read exception: "+str(detail)
402            except Exception as detail:
403                import traceback
404                rd.errors += "\n  Unhandled read exception: "+str(detail)
405                rd.errors += "\n  Traceback info:\n"+str(traceback.format_exc())
406        if flag: # this read succeeded
407            if rd.Image is None:
408                raise Exception('No image read. Strange!')
409            if GSASIIpath.GetConfigValue('Transpose'):
410                print 'Transposing Image!'
411                rd.Image = rd.Image.T
412            #rd.readfilename = imagefile
413            if imageOnly:
414                return rd.Image
415            else:
416                return rd.Comments,rd.Data,rd.Npix,rd.Image
417    else:
418        print('Error reading file '+filename)
419        print('Error messages(s)\n'+errorReport)
420        raise Exception('No image read')
421   
422def GetImageData(G2frame,imagefile,imageOnly=False):
423    '''Read an image with the file reader keyed by the
424    file extension.
425
426    This routine will be replaced by ReadImageData, which will be renamed to this.
427
428    :param wx.Frame G2frame: main GSAS-II Frame and data object.
429
430    :param str imagefile: name of image file
431
432    :param bool imageOnly: If True return only the image,
433      otherwise  (default) return more (see below)
434
435    :returns: an image as a numpy array or a list of four items:
436      Comments, Data, Npix and the Image, as selected by imageOnly
437
438    '''
439    if GSASIIpath.GetConfigValue('debug'):  # test out using replacement routine
440        return ReadImageData(G2frame,imagefile,imageOnly)
441   
442    ext = ospath.splitext(imagefile)[1]
443    Comments = []
444    Image = None
445    if ext == '.tif' or ext == '.tiff':
446        Comments,Data,Npix,Image = GetTifData(imagefile)
447        if Npix == 0:
448            print("GetTifData failed to read "+str(imagefile)+" Trying PIL")
449            import scipy.misc
450            Image = scipy.misc.imread(imagefile,flatten=True)
451            Npix = Image.size
452            Comments = ['no metadata']
453            Data = {'wavelength': 0.1, 'pixelSize': [200, 200], 'distance': 100.0}
454            Data['size'] = list(Image.shape)
455            Data['center'] = [int(i/2) for i in Image.shape]
456            if not imageOnly:
457                EditImageParms(G2frame,Data,Comments,Image,imagefile)
458    elif ext == '.edf':
459        Comments,Data,Npix,Image = GetEdfData(imagefile)
460    elif ext == '.img':
461        Comments,Data,Npix,Image = GetImgData(imagefile)
462        Image[0][0] = 0
463    elif ext in ['.mar3450','.mar2300','.mar2560']:
464        Comments,Data,Npix,Image = GetMAR345Data(imagefile)
465    elif ext in ['.sum','.avg','.cor'] or 'ge' in ext:
466        Comments,Data,Npix,Image = GetGEsumData(imagefile)
467    elif ext == '.G2img':
468        Comments,Data,Npix,Image = GetG2Image(imagefile)
469    elif ext == '.png':
470        Comments,Data,Npix,Image = GetPNGData(imagefile)
471        if not imageOnly:
472            EditImageParms(G2frame,Data,Comments,Image,imagefile)
473    elif ext == '.stl':
474        Comments,Data,Npix,Image = GetRigaku(imagefile)
475#        if not imageOnly:
476#            EditImageParms(G2frame,Data,Comments,Image,imagefile)
477    else:
478        print 'Extension for file '+imagefile+' not recognized'
479    if Image is None:
480        raise Exception('No image read')
481    if imageOnly:
482        if TRANSP:
483            print 'Transposing Image!'
484            return Image.T
485        else:
486            return Image
487    else:
488        if TRANSP:
489            print 'Transposing Image!'
490            return Comments,Data,Npix,Image.T
491        else:
492            return Comments,Data,Npix,Image
493       
494def PutG2Image(filename,Comments,Data,Npix,image):
495    'Write an image as a python pickle - might be better as an .edf file?'
496    File = open(filename,'wb')
497    cPickle.dump([Comments,Data,Npix,image],File,1)
498    File.close()
499    return
500   
501def GetG2Image(filename):
502    'Read an image as a python pickle'
503    File = open(filename,'rb')
504    Comments,Data,Npix,image = cPickle.load(File)
505    File.close()
506    return Comments,Data,Npix,image
507   
508def GetEdfData(filename,imageOnly=False):   
509    'Read European detector data edf file'
510    import struct as st
511    import array as ar
512    if not imageOnly:
513        print 'Read European detector data edf file: ',filename
514    File = open(filename,'rb')
515    fileSize = os.stat(filename).st_size
516    head = File.read(3072)
517    lines = head.split('\n')
518    sizexy = [0,0]
519    pixSize = [154,154]     #Pixium4700?
520    cent = [0,0]
521    wave = 1.54187  #default <CuKa>
522    dist = 1000.
523    head = ['European detector data',]
524    for line in lines:
525        line = line.replace(';',' ').strip()
526        fields = line.split()
527        if 'Dim_1' in line:
528            sizexy[0] = int(fields[2])
529        elif 'Dim_2' in line:
530            sizexy[1] = int(fields[2])
531        elif 'DataType' in line:
532            dType = fields[2]
533        elif 'wavelength' in line:
534            wave = float(fields[2])
535        elif 'Size' in line:
536            imSize = int(fields[2])
537#        elif 'DataType' in lines:
538#            dType = fields[2]
539        elif 'pixel_size_x' in line:
540            pixSize[0] = float(fields[2])
541        elif 'pixel_size_y' in line:
542            pixSize[1] = float(fields[2])
543        elif 'beam_center_x' in line:
544            cent[0] = float(fields[2])
545        elif 'beam_center_y' in line:
546            cent[1] = float(fields[2])
547        elif 'refined_distance' in line:
548            dist = float(fields[2])
549        if line:
550            head.append(line)
551        else:   #blank line at end of header
552            break 
553    File.seek(fileSize-imSize)
554    if dType == 'UnsignedShort':       
555        image = np.array(ar.array('H',File.read(imSize)),dtype=np.int32)
556    elif dType == 'UnsignedInt':
557        image = np.array(ar.array('L',File.read(imSize)),dtype=np.int32)
558    elif dType == 'UnsignedLong':
559        image = np.array(ar.array('L',File.read(imSize)),dtype=np.int32)
560    elif dType == 'SignedInteger':
561        image = np.array(ar.array('l',File.read(imSize)),dtype=np.int32)
562    image = np.reshape(image,(sizexy[1],sizexy[0]))
563    data = {'pixelSize':pixSize,'wavelength':wave,'distance':dist,'center':cent,'size':sizexy}
564    Npix = sizexy[0]*sizexy[1]
565    File.close()   
566    if imageOnly:
567        return image
568    else:
569        return head,data,Npix,image
570       
571def GetRigaku(filename,imageOnly=False):
572    'Read Rigaku R-Axis IV image file'
573    import struct as st
574    import array as ar
575    if not imageOnly:
576        print 'Read Rigaku R-Axis IV file: ',filename   
577    File = open(filename,'rb')
578    fileSize = os.stat(filename).st_size
579    Npix = (fileSize-6000)/2
580    Head = File.read(6000)
581    head = ['Rigaku R-Axis IV detector data',]
582    image = np.array(ar.array('H',File.read(fileSize-6000)),dtype=np.int32)
583    print fileSize,image.shape
584    print head
585    if Npix == 9000000:
586        sizexy = [3000,3000]
587        pixSize = [100.,100.]       
588    elif Npix == 2250000:
589        sizexy = [1500,1500]
590        pixSize = [200.,200.]
591    else:
592        sizexy = [6000,6000]
593        pixSize = [50.,50.] 
594    image = np.reshape(image,(sizexy[1],sizexy[0]))       
595    data = {'pixelSize':pixSize,'wavelength':1.5428,'distance':250.0,'center':[150.,150.],'size':sizexy} 
596    File.close()   
597    if imageOnly:
598        return image
599    else:
600        return head,data,Npix,image
601   
602def GetGEsumData(filename,imageOnly=False):
603    'Read SUM file as produced at 1-ID from G.E. images'
604    import struct as st
605    import array as ar
606    if not imageOnly:
607        print 'Read GE sum file: ',filename   
608    File = open(filename,'rb')
609    if '.sum' in filename or '.cor' in filename:
610        head = ['GE detector sum or cor data from APS 1-ID',]
611        sizexy = [2048,2048]
612    elif '.avg' in filename or '.ge' in filename:
613        head = ['GE detector avg or ge* data from APS 1-ID',]
614        sizexy = [2048,2048]
615    else:
616        head = ['GE detector raw data from APS 1-ID',]
617        File.seek(18)
618        size,nframes = st.unpack('<ih',File.read(6))
619        sizexy = [2048,2048]
620        pos = 8192
621        File.seek(pos)
622    Npix = sizexy[0]*sizexy[1]
623    if '.sum' in filename or '.cor' in filename:
624        image = np.array(ar.array('f',File.read(4*Npix)),dtype=np.int32)
625    elif '.avg' in filename or '.ge' in filename:
626        image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
627    else:
628        image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
629        while nframes > 1:
630            image += np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
631            nframes -= 1
632    image = np.reshape(image,(sizexy[1],sizexy[0]))
633    data = {'pixelSize':[200,200],'wavelength':0.15,'distance':250.0,'center':[204.8,204.8],'size':sizexy} 
634    File.close()   
635    if imageOnly:
636        return image
637    else:
638        return head,data,Npix,image
639       
640def GetImgData(filename,imageOnly=False):
641    'Read an ADSC image file'
642    import struct as st
643    import array as ar
644    if not imageOnly:
645        print 'Read ADSC img file: ',filename
646    File = open(filename,'rb')
647    head = File.read(511)
648    lines = head.split('\n')
649    head = []
650    center = [0,0]
651    for line in lines[1:-2]:
652        line = line.strip()[:-1]
653        if line:
654            if 'SIZE1' in line:
655                size = int(line.split('=')[1])
656                Npix = size*size
657            elif 'WAVELENGTH' in line:
658                wave = float(line.split('=')[1])
659            elif 'BIN' in line:
660                if line.split('=')[1] == '2x2':
661                    pixel=(102,102)
662                else:
663                    pixel = (51,51)
664            elif 'DISTANCE' in line:
665                distance = float(line.split('=')[1])
666            elif 'CENTER_X' in line:
667                center[0] = float(line.split('=')[1])
668            elif 'CENTER_Y' in line:
669                center[1] = float(line.split('=')[1])
670            head.append(line)
671    data = {'pixelSize':pixel,'wavelength':wave,'distance':distance,'center':center,'size':[size,size]}
672    image = []
673    row = 0
674    pos = 512
675    File.seek(pos)
676    image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
677    image = np.reshape(image,(sizexy[1],sizexy[0]))
678#    image = np.zeros(shape=(size,size),dtype=np.int32)   
679#    while row < size:
680#        File.seek(pos)
681#        line = ar.array('H',File.read(2*size))
682#        image[row] = np.asarray(line)
683#        row += 1
684#        pos += 2*size
685    File.close()
686    if imageOnly:
687        return image
688    else:
689        return lines[1:-2],data,Npix,image
690       
691def GetMAR345Data(filename,imageOnly=False):
692    'Read a MAR-345 image plate image'
693    import array as ar
694    import struct as st
695    try:
696        import pack_f as pf
697    except:
698        msg = wx.MessageDialog(None, message="Unable to load the GSAS MAR image decompression, pack_f",
699                               caption="Import Error",
700                               style=wx.ICON_ERROR | wx.OK | wx.STAY_ON_TOP)
701        msg.ShowModal()
702        return None,None,None,None
703
704    if not imageOnly:
705        print 'Read Mar345 file: ',filename
706    File = open(filename,'rb')
707    head = File.read(4095)
708    numbers = st.unpack('<iiiiiiiiii',head[:40])
709    lines = head[128:].split('\n')
710    head = []
711    for line in lines:
712        line = line.strip()
713        if 'PIXEL' in line:
714            values = line.split()
715            pixel = (int(values[2]),int(values[4]))     #in microns
716        elif 'WAVELENGTH' in line:
717            wave = float(line.split()[1])
718        elif 'DISTANCE' in line:
719            distance = float(line.split()[1])           #in mm
720        elif 'CENTER' in line:
721            values = line.split()
722            center = [float(values[2])/10.,float(values[4])/10.]    #make in mm from pixels
723        if line: 
724            head.append(line)
725    data = {'pixelSize':pixel,'wavelength':wave,'distance':distance,'center':center}
726    for line in head:
727        if 'FORMAT' in line[0:6]:
728            items = line.split()
729            sizex = int(items[1])
730            Npix = int(items[3])
731            sizey = int(Npix/sizex)
732    pos = 4096
733    data['size'] = [sizex,sizey]
734    File.seek(pos)
735    line = File.read(8)
736    while 'CCP4' not in line:       #get past overflow list for now
737        line = File.read(8)
738        pos += 8
739    pos += 37
740    File.seek(pos)
741    raw = File.read()
742    File.close()
743    image = np.zeros(shape=(sizex,sizey),dtype=np.int32)
744   
745    image = np.flipud(pf.pack_f(len(raw),raw,sizex,sizey,image).T)  #transpose to get it right way around & flip
746    if imageOnly:
747        return image
748    else:
749        return head,data,Npix,image
750       
751def GetPNGData(filename,imageOnly=False):
752    '''Read an image in a png format, assumes image is converted from CheMin tif file
753    so default parameters are that machine.
754    '''
755    import scipy.misc
756    Image = scipy.misc.imread(filename,flatten=True)
757    Npix = Image.size
758    Comments = ['no metadata']
759    pixy = list(Image.shape)
760    sizexy = [40,40]
761    Data = {'wavelength': 1.78892, 'pixelSize': sizexy, 'distance': 18.0,'size':pixy}
762    Data['center'] = [pixy[0]*sizexy[0]/1000,pixy[1]*sizexy[1]/2000]
763    if imageOnly:
764        return Image.T
765    else:
766        return Comments,Data,Npix,Image.T
767
768def GetTifData(filename,imageOnly=False):
769    '''Read an image in a pseudo-tif format,
770    as produced by a wide variety of software, almost always
771    incorrectly in some way.
772    '''
773    import struct as st
774    try:
775        import Image as Im
776    except ImportError:
777        try:
778            from PIL import Image as Im
779        except ImportError:
780            print "PIL/pillow Image module not present. TIFs cannot be read without this"
781            raise Exception("PIL/pillow Image module not found")
782    import array as ar
783    import ReadMarCCDFrame as rmf
784    File = open(filename,'rb')
785    dataType = 5
786    center = [None,None]
787    wavelength = None
788    distance = None
789    try:
790        Meta = open(filename+'.metadata','Ur')
791        head = Meta.readlines()
792        for line in head:
793            line = line.strip()
794            if 'dataType=' in line:
795                dataType = int(line.split('=')[1])
796        Meta.close()
797    except IOError:
798        print 'no metadata file found - will try to read file anyway'
799        head = ['no metadata file found',]
800       
801    tag = File.read(2)
802    byteOrd = '<'
803    if tag == 'II' and int(st.unpack('<h',File.read(2))[0]) == 42:     #little endian
804        IFD = int(st.unpack(byteOrd+'i',File.read(4))[0])
805    elif tag == 'MM' and int(st.unpack('>h',File.read(2))[0]) == 42:   #big endian
806        byteOrd = '>'
807        IFD = int(st.unpack(byteOrd+'i',File.read(4))[0])       
808    else:
809        lines = ['not a detector tiff file',]
810        return lines,0,0,0
811    File.seek(IFD)                                                  #get number of directory entries
812    NED = int(st.unpack(byteOrd+'h',File.read(2))[0])
813    IFD = {}
814    nSlice = 1
815    for ied in range(NED):
816        Tag,Type = st.unpack(byteOrd+'Hh',File.read(4))
817        nVal = st.unpack(byteOrd+'i',File.read(4))[0]
818        if DEBUG: print 'Try:',Tag,Type,nVal
819        if Type == 1:
820            Value = st.unpack(byteOrd+nVal*'b',File.read(nVal))
821        elif Type == 2:
822            Value = st.unpack(byteOrd+'i',File.read(4))
823        elif Type == 3:
824            Value = st.unpack(byteOrd+nVal*'h',File.read(nVal*2))
825            x = st.unpack(byteOrd+nVal*'h',File.read(nVal*2))
826        elif Type == 4:
827            if Tag in [273,279]:
828                nSlice = nVal
829                nVal = 1
830            Value = st.unpack(byteOrd+nVal*'i',File.read(nVal*4))
831        elif Type == 5:
832            Value = st.unpack(byteOrd+nVal*'i',File.read(nVal*4))
833        elif Type == 11:
834            Value = st.unpack(byteOrd+nVal*'f',File.read(nVal*4))
835        IFD[Tag] = [Type,nVal,Value]
836        if DEBUG: print Tag,IFD[Tag]
837    sizexy = [IFD[256][2][0],IFD[257][2][0]]
838    [nx,ny] = sizexy
839    Npix = nx*ny
840    if 34710 in IFD:
841        if not imageOnly:
842            print 'Read MAR CCD tiff file: ',filename
843        marFrame = rmf.marFrame(File,byteOrd,IFD)
844        image = np.flipud(np.array(np.asarray(marFrame.image),dtype=np.int32))
845        tifType = marFrame.filetitle
846        pixy = [marFrame.pixelsizeX/1000.0,marFrame.pixelsizeY/1000.0]
847        head = marFrame.outputHead()
848# extract resonable wavelength from header
849        wavelength = marFrame.sourceWavelength*1e-5
850        wavelength = (marFrame.opticsWavelength > 0) and marFrame.opticsWavelength*1e-5 or wavelength
851        wavelength = (wavelength <= 0) and None or wavelength
852# extract resonable distance from header
853        distance = (marFrame.startXtalToDetector+marFrame.endXtalToDetector)*5e-4
854        distance = (distance <= 0) and marFrame.xtalToDetector*1e-3 or distance
855        distance = (distance <= 0) and None or distance
856# extract resonable center from header
857        center = [marFrame.beamX*marFrame.pixelsizeX*1e-9,marFrame.beamY*marFrame.pixelsizeY*1e-9]
858        center = (center[0] != 0 and center[1] != 0) and center or [None,None]
859#print head,tifType,pixy
860    elif nSlice > 1:    #CheMin multislice tif file!
861        tifType = 'CheMin'
862        pixy = [40,40]
863        image = np.flipud(np.array(Im.open(filename)))*10.
864        distance = 18.0
865        center = [pixy[0]*sizexy[0]/2000,0]     #the CheMin beam stop is here
866        wavelength = 1.78892
867    elif 272 in IFD:
868        ifd = IFD[272]
869        File.seek(ifd[2][0])
870        S = File.read(ifd[1])
871        if 'PILATUS' in S:
872            tifType = 'Pilatus'
873            dataType = 0
874            pixy = [172,172]
875            File.seek(4096)
876            if not imageOnly:
877                print 'Read Pilatus tiff file: ',filename
878            image = ar.array('L',File.read(4*Npix))
879            image = np.array(np.asarray(image),dtype=np.int32)
880        else:
881            if IFD[258][2][0] == 16:
882                tifType = 'GE'
883                pixy = [200,200]
884                File.seek(8)
885                if not imageOnly:
886                    print 'Read GE-detector tiff file: ',filename
887                image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
888            elif IFD[258][2][0] == 32:
889                tifType = 'CHESS'
890                pixy = [200,200]
891                File.seek(8)
892                if not imageOnly:
893                    print 'Read CHESS-detector tiff file: ',filename
894                image = np.array(ar.array('L',File.read(4*Npix)),dtype=np.int32)
895           
896    elif 262 in IFD and IFD[262][2][0] > 4:
897        tifType = 'DND'
898        pixy = [158,158]
899        File.seek(512)
900        if not imageOnly:
901            print 'Read DND SAX/WAX-detector tiff file: ',filename
902        image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
903    elif sizexy == [1536,1536]:
904        tifType = 'APS Gold'
905        pixy = [150,150]
906        File.seek(64)
907        if not imageOnly:
908            print 'Read Gold tiff file:',filename
909        image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
910    elif sizexy == [2048,2048] or sizexy == [1024,1024] or sizexy == [3072,3072]:
911        if IFD[273][2][0] == 8:
912            if IFD[258][2][0] == 32:
913                tifType = 'PE'
914                pixy = [200,200]
915                File.seek(8)
916                if not imageOnly:
917                    print 'Read APS PE-detector tiff file: ',filename
918                if dataType == 5:
919                    image = np.array(ar.array('f',File.read(4*Npix)),dtype=np.float32)
920                else:
921                    image = np.array(ar.array('I',File.read(4*Npix)),dtype=np.int32)
922            elif IFD[258][2][0] == 16: 
923                tifType = 'MedOptics D1'
924                pixy = [46.9,46.9]
925                File.seek(8)
926                if not imageOnly:
927                    print 'Read MedOptics D1 tiff file: ',filename
928                image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
929                 
930        elif IFD[273][2][0] == 4096:
931            if sizexy[0] == 3072:
932                pixy =  [73,73]
933                tifType = 'MAR225'           
934            else:
935                pixy = [158,158]
936                tifType = 'MAR325'           
937            File.seek(4096)
938            if not imageOnly:
939                print 'Read MAR CCD tiff file: ',filename
940            image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
941        elif IFD[273][2][0] == 512:
942            tiftype = '11-ID-C'
943            pixy = [200,200]
944            File.seek(512)
945            if not imageOnly:
946                print 'Read 11-ID-C tiff file: ',filename
947            image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)           
948    elif sizexy == [4096,4096]:
949        if IFD[273][2][0] == 8:
950            if IFD[258][2][0] == 16:
951                tifType = 'scanCCD'
952                pixy = [9,9]
953                File.seek(8)
954                if not imageOnly:
955                    print 'Read APS scanCCD tiff file: ',filename
956                image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
957        elif IFD[273][2][0] == 4096:
958            tifType = 'Rayonix'
959            pixy = [73.242,73.242]
960            File.seek(4096)
961            if not imageOnly:
962                print 'Read Rayonix MX300HE tiff file: ',filename
963            image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
964#    elif sizexy == [960,960]:
965#        tiftype = 'PE-BE'
966#        pixy = (200,200)
967#        File.seek(8)
968#        if not imageOnly:
969#            print 'Read Gold tiff file:',filename
970#        image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
971           
972    else:
973        lines = ['not a known detector tiff file',]
974        return lines,0,0,0
975
976    if sizexy[1]*sizexy[0] != image.size: # test is resize is allowed
977        lines = ['not a known detector tiff file',]
978        return lines,0,0,0
979       
980    image = np.reshape(image,(sizexy[1],sizexy[0]))
981    center = (not center[0]) and [pixy[0]*sizexy[0]/2000,pixy[1]*sizexy[1]/2000] or center
982    wavelength = (not wavelength) and 0.10 or wavelength
983    distance = (not distance) and 100.0 or distance
984    data = {'pixelSize':pixy,'wavelength':wavelength,'distance':distance,'center':center,'size':sizexy}
985    File.close()   
986    if imageOnly:
987        return image
988    else:
989        return head,data,Npix,image
990   
991#def GetTifData(filename,imageOnly=False):
992#    import struct as st
993#    import array as ar
994#    File = open(filename,'rb')
995#    dataType = 5
996#    try:
997#        Meta = open(filename+'.metadata','Ur')
998#        head = Meta.readlines()
999#        for line in head:
1000#            line = line.strip()
1001#            if 'dataType=' in line:
1002#                dataType = int(line.split('=')[1])
1003#        Meta.close()
1004#    except IOError:
1005#        print 'no metadata file found - will try to read file anyway'
1006#        head = ['no metadata file found',]
1007#       
1008#    tag = File.read(2)
1009#    byteOrd = '<'
1010#    if tag == 'II' and int(st.unpack('<h',File.read(2))[0]) == 42:     #little endian
1011#        IFD = int(st.unpack(byteOrd+'i',File.read(4))[0])
1012#    elif tag == 'MM' and int(st.unpack('>h',File.read(2))[0]) == 42:   #big endian
1013#        byteOrd = '>'
1014#        IFD = int(st.unpack(byteOrd+'i',File.read(4))[0])       
1015#    else:
1016#        lines = ['not a detector tiff file',]
1017#        return lines,0,0,0
1018#    File.seek(IFD)                                                  #get number of directory entries
1019#    NED = int(st.unpack(byteOrd+'h',File.read(2))[0])
1020#    IFD = {}
1021#    for ied in range(NED):
1022#        Tag,Type = st.unpack(byteOrd+'Hh',File.read(4))
1023#        nVal = st.unpack(byteOrd+'i',File.read(4))[0]
1024#        if Type == 1:
1025#            Value = st.unpack(byteOrd+nVal*'b',File.read(nVal))
1026#        elif Type == 2:
1027#            Value = st.unpack(byteOrd+'i',File.read(4))
1028#        elif Type == 3:
1029#            Value = st.unpack(byteOrd+nVal*'h',File.read(nVal*2))
1030#            x = st.unpack(byteOrd+nVal*'h',File.read(nVal*2))
1031#        elif Type == 4:
1032#            Value = st.unpack(byteOrd+nVal*'i',File.read(nVal*4))
1033#        elif Type == 5:
1034#            Value = st.unpack(byteOrd+nVal*'i',File.read(nVal*4))
1035#        elif Type == 11:
1036#            Value = st.unpack(byteOrd+nVal*'f',File.read(nVal*4))
1037#        IFD[Tag] = [Type,nVal,Value]
1038##        print Tag,IFD[Tag]
1039#    sizexy = [IFD[256][2][0],IFD[257][2][0]]
1040#    [nx,ny] = sizexy
1041#    Npix = nx*ny
1042#    if 272 in IFD:
1043#        ifd = IFD[272]
1044#        File.seek(ifd[2][0])
1045#        S = File.read(ifd[1])
1046#        if 'PILATUS' in S:
1047#            tifType = 'Pilatus'
1048#            dataType = 0
1049#            pixy = (172,172)
1050#            File.seek(4096)
1051#            if not imageOnly:
1052#                print 'Read Pilatus tiff file: ',filename
1053#            image = ar.array('L',File.read(4*Npix))
1054#            image = np.array(np.asarray(image),dtype=np.int32)
1055#    elif 262 in IFD and IFD[262][2][0] > 4:
1056#        tifType = 'DND'
1057#        pixy = (158,158)
1058#        File.seek(512)
1059#        if not imageOnly:
1060#            print 'Read DND SAX/WAX-detector tiff file: ',filename
1061#        image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
1062#    elif sizexy == [1536,1536]:
1063#        tifType = 'APS Gold'
1064#        pixy = (150,150)
1065#        File.seek(64)
1066#        if not imageOnly:
1067#            print 'Read Gold tiff file:',filename
1068#        image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
1069#    elif sizexy == [2048,2048] or sizexy == [1024,1024] or sizexy == [3072,3072]:
1070#        if IFD[273][2][0] == 8:
1071#            if IFD[258][2][0] == 32:
1072#                tifType = 'PE'
1073#                pixy = (200,200)
1074#                File.seek(8)
1075#                if not imageOnly:
1076#                    print 'Read APS PE-detector tiff file: ',filename
1077#                if dataType == 5:
1078#                    image = np.array(ar.array('f',File.read(4*Npix)),dtype=np.float32)
1079#                else:
1080#                    image = np.array(ar.array('I',File.read(4*Npix)),dtype=np.int32)
1081#        elif IFD[273][2][0] == 4096:
1082#            if sizexy[0] == 3072:
1083#                pixy =  (73,73)
1084#                tifType = 'MAR225'           
1085#            else:
1086#                pixy = (158,158)
1087#                tifType = 'MAR325'           
1088#            File.seek(4096)
1089#            if not imageOnly:
1090#                print 'Read MAR CCD tiff file: ',filename
1091#            image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
1092#        elif IFD[273][2][0] == 512:
1093#            tiftype = '11-ID-C'
1094#            pixy = [200,200]
1095#            File.seek(512)
1096#            if not imageOnly:
1097#                print 'Read 11-ID-C tiff file: ',filename
1098#            image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)           
1099#    elif sizexy == [4096,4096]:
1100#        if IFD[273][2][0] == 8:
1101#            if IFD[258][2][0] == 16:
1102#                tifType = 'scanCCD'
1103#                pixy = (9,9)
1104#                File.seek(8)
1105#                if not imageOnly:
1106#                    print 'Read APS scanCCD tiff file: ',filename
1107#                image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
1108#        elif IFD[273][2][0] == 4096:
1109#            tifType = 'Rayonix'
1110#            pixy = (73.242,73.242)
1111#            File.seek(4096)
1112#            if not imageOnly:
1113#                print 'Read Rayonix MX300HE tiff file: ',filename
1114#            image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
1115##    elif sizexy == [960,960]:
1116##        tiftype = 'PE-BE'
1117##        pixy = (200,200)
1118##        File.seek(8)
1119##        if not imageOnly:
1120##            print 'Read Gold tiff file:',filename
1121##        image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
1122#           
1123#    else:
1124#        lines = ['not a known detector tiff file',]
1125#        return lines,0,0,0
1126#       
1127#    image = np.reshape(image,(sizexy[1],sizexy[0]))
1128#    center = [pixy[0]*sizexy[0]/2000,pixy[1]*sizexy[1]/2000]
1129#    data = {'pixelSize':pixy,'wavelength':0.10,'distance':100.0,'center':center,'size':sizexy}
1130#    File.close()   
1131#    if imageOnly:
1132#        return image
1133#    else:
1134#        return head,data,Npix,image
1135#   
1136def ProjFileOpen(G2frame):
1137    'Read a GSAS-II project file and load into the G2 data tree'
1138    if not os.path.exists(G2frame.GSASprojectfile):
1139        print ('\n*** Error attempt to open project file that does not exist:\n   '+
1140               str(G2frame.GSASprojectfile))
1141        return
1142    LastSavedUsing = None
1143    file = open(G2frame.GSASprojectfile,'rb')
1144    print 'load from file: ',G2frame.GSASprojectfile
1145    G2frame.SetTitle("GSAS-II data tree: "+
1146                     os.path.split(G2frame.GSASprojectfile)[1])
1147    wx.BeginBusyCursor()
1148    try:
1149        while True:
1150            try:
1151                data = cPickle.load(file)
1152            except EOFError:
1153                break
1154            datum = data[0]
1155           
1156            Id = G2frame.PatternTree.AppendItem(parent=G2frame.root,text=datum[0])
1157            if 'PWDR' in datum[0]:               
1158                if 'ranId' not in datum[1][0]: # patch: add random Id if not present
1159                    datum[1][0]['ranId'] = ran.randint(0,sys.maxint)
1160                G2frame.PatternTree.SetItemPyData(Id,datum[1][:3])  #temp. trim off junk (patch?)
1161            elif datum[0].startswith('HKLF'): 
1162                if 'ranId' not in datum[1][0]: # patch: add random Id if not present
1163                    datum[1][0]['ranId'] = ran.randint(0,sys.maxint)
1164                G2frame.PatternTree.SetItemPyData(Id,datum[1])
1165            else:
1166                G2frame.PatternTree.SetItemPyData(Id,datum[1])             
1167                if datum[0] == 'Controls' and 'LastSavedUsing' in datum[1]:
1168                    LastSavedUsing = datum[1]['LastSavedUsing']
1169                if datum[0] == 'Controls' and 'PythonVersions' in datum[1] and GSASIIpath.GetConfigValue('debug'):
1170                    print('Packages used to create .GPX file:')
1171                    if 'dict' in str(type(datum[1]['PythonVersions'])):  #patch
1172                        for p in sorted(datum[1]['PythonVersions'],key=lambda s: s.lower()):
1173                            print("{:>14s}: {:s}".format(p[0],p[1]))
1174                    else:
1175                        for p in datum[1]['PythonVersions']:
1176                            print("{:<12s} {:s}".format(p[0]+':',p[1]))
1177            for datus in data[1:]:
1178                sub = G2frame.PatternTree.AppendItem(Id,datus[0])
1179#patch
1180                if datus[0] == 'Instrument Parameters' and len(datus[1]) == 1:
1181                    if 'PWDR' in datum[0]:
1182                        datus[1] = [dict(zip(datus[1][3],zip(datus[1][0],datus[1][1],datus[1][2]))),{}]
1183                    else:
1184                        datus[1] = [dict(zip(datus[1][2],zip(datus[1][0],datus[1][1]))),{}]
1185                    for item in datus[1][0]:               #zip makes tuples - now make lists!
1186                        datus[1][0][item] = list(datus[1][0][item])
1187#end patch
1188                G2frame.PatternTree.SetItemPyData(sub,datus[1])
1189            if 'IMG' in datum[0]:                   #retrieve image default flag & data if set
1190                Data = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,Id,'Image Controls'))
1191                if Data['setDefault']:
1192                    G2frame.imageDefault = Data               
1193        file.close()
1194        if LastSavedUsing:
1195            print('GPX load successful. Last saved with GSAS-II version '+LastSavedUsing)
1196        else:
1197            print('project load successful')
1198        G2frame.NewPlot = True
1199    except:
1200        msg = wx.MessageDialog(G2frame,message="Error reading file "+
1201            str(G2frame.GSASprojectfile)+". This is not a GSAS-II .gpx file",
1202            caption="Load Error",style=wx.ICON_ERROR | wx.OK | wx.STAY_ON_TOP)
1203        msg.ShowModal()
1204    finally:
1205        wx.EndBusyCursor()
1206        G2frame.Status.SetStatusText('To reorder tree items, use mouse RB to drag/drop them')
1207   
1208def ProjFileSave(G2frame):
1209    'Save a GSAS-II project file'
1210    if not G2frame.PatternTree.IsEmpty():
1211        file = open(G2frame.GSASprojectfile,'wb')
1212        print 'save to file: ',G2frame.GSASprojectfile
1213        # stick the file name into the tree and version info into tree so they are saved.
1214        # (Controls should always be created at this point)
1215        try:
1216            Controls = G2frame.PatternTree.GetItemPyData(
1217                G2gd.GetPatternTreeItemId(G2frame,G2frame.root, 'Controls'))
1218            Controls['LastSavedAs'] = os.path.abspath(G2frame.GSASprojectfile)
1219            Controls['LastSavedUsing'] = str(GSASIIpath.GetVersionNumber())
1220            Controls['PythonVersions'] = G2frame.PackageVersions
1221        except:
1222            pass
1223        wx.BeginBusyCursor()
1224        try:
1225            item, cookie = G2frame.PatternTree.GetFirstChild(G2frame.root)
1226            while item:
1227                data = []
1228                name = G2frame.PatternTree.GetItemText(item)
1229                data.append([name,G2frame.PatternTree.GetItemPyData(item)])
1230                item2, cookie2 = G2frame.PatternTree.GetFirstChild(item)
1231                while item2:
1232                    name = G2frame.PatternTree.GetItemText(item2)
1233                    data.append([name,G2frame.PatternTree.GetItemPyData(item2)])
1234                    item2, cookie2 = G2frame.PatternTree.GetNextChild(item, cookie2)                           
1235                item, cookie = G2frame.PatternTree.GetNextChild(G2frame.root, cookie)                           
1236                cPickle.dump(data,file,1)
1237            file.close()
1238        finally:
1239            wx.EndBusyCursor()
1240        print('project save successful')
1241
1242def SaveIntegration(G2frame,PickId,data):
1243    'Save image integration results as powder pattern(s)'
1244    azms = G2frame.Integrate[1]
1245    X = G2frame.Integrate[2][:-1]
1246    N = len(X)
1247    Id = G2frame.PatternTree.GetItemParent(PickId)
1248    name = G2frame.PatternTree.GetItemText(Id)
1249    name = name.replace('IMG ',data['type']+' ')
1250    Comments = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,Id, 'Comments'))
1251    if 'PWDR' in name:
1252        names = ['Type','Lam','Zero','Polariz.','U','V','W','X','Y','SH/L','Azimuth'] 
1253        codes = [0 for i in range(11)]
1254    elif 'SASD' in name:
1255        names = ['Type','Lam','Zero','Azimuth'] 
1256        codes = [0 for i in range(4)]
1257        X = 4.*np.pi*npsind(X/2.)/data['wavelength']    #convert to q
1258    Xminmax = [X[0],X[-1]]
1259    LRazm = data['LRazimuth']
1260    Azms = []
1261    dazm = 0.
1262    if data['fullIntegrate'] and data['outAzimuths'] == 1:
1263        Azms = [45.0,]                              #a poor man's average?
1264    else:
1265        for i,azm in enumerate(azms[:-1]):
1266            if azm > 360. and azms[i+1] > 360.:
1267                Azms.append(G2img.meanAzm(azm%360.,azms[i+1]%360.))
1268            else:   
1269                Azms.append(G2img.meanAzm(azm,azms[i+1]))
1270        dazm = np.min(np.abs(np.diff(azms)))/2.
1271    G2frame.IntgOutList = []
1272    for i,azm in enumerate(azms[:-1]):
1273        Aname = name+" Azm= %.2f"%((azm+dazm)%360.)
1274        item, cookie = G2frame.PatternTree.GetFirstChild(G2frame.root)
1275        nOcc = 0
1276        while item:
1277            Name = G2frame.PatternTree.GetItemText(item)
1278            if Aname in Name:
1279                nOcc += 1
1280            item, cookie = G2frame.PatternTree.GetNextChild(G2frame.root, cookie)
1281        if nOcc:
1282            Aname += '(%d)'%(nOcc)
1283        Sample = G2pdG.SetDefaultSample()
1284        Sample['Gonio. radius'] = data['distance']
1285        Sample['Omega'] = data['GonioAngles'][0]
1286        Sample['Chi'] = data['GonioAngles'][1]
1287        Sample['Phi'] = data['GonioAngles'][2]
1288        Sample['Azimuth'] = (azm+dazm)%360.    #put here as bin center
1289        if 'PWDR' in Aname:
1290            parms = ['PXC',data['wavelength'],0.0,0.99,1.0,-0.10,0.4,0.30,1.0,0.0001,Azms[i]]    #set polarization for synchrotron radiation!
1291        elif 'SASD' in Aname:
1292            Sample['Trans'] = data['SampleAbs'][0]
1293            parms = ['LXC',data['wavelength'],0.0,Azms[i]]
1294        Y = G2frame.Integrate[0][i]
1295        W = np.where(Y>0.,1./Y,1.e-6)                    #probably not true
1296        Id = G2frame.PatternTree.AppendItem(parent=G2frame.root,text=Aname)
1297        G2frame.IntgOutList.append(Id)
1298        G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Comments'),Comments)                   
1299        G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Limits'),[tuple(Xminmax),Xminmax])
1300        if 'PWDR' in Aname:
1301            G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Background'),[['chebyschev',1,3,1.0,0.0,0.0],
1302                {'nDebye':0,'debyeTerms':[],'nPeaks':0,'peaksList':[]}])
1303        inst = [dict(zip(names,zip(parms,parms,codes))),{}]
1304        for item in inst[0]:
1305            inst[0][item] = list(inst[0][item])
1306        G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Instrument Parameters'),inst)
1307        if 'PWDR' in Aname:
1308            G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Sample Parameters'),Sample)
1309            G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Peak List'),{'sigDict':{},'peaks':[]})
1310            G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Index Peak List'),[[],[]])
1311            G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Unit Cells List'),[])
1312            G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Reflection Lists'),{})
1313        elif 'SASD' in Aname:             
1314            G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Substances'),G2pdG.SetDefaultSubstances())
1315            G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Sample Parameters'),Sample)
1316            G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Models'),G2pdG.SetDefaultSASDModel())
1317        valuesdict = {
1318            'wtFactor':1.0,
1319            'Dummy':False,
1320            'ranId':ran.randint(0,sys.maxint),
1321            'Offset':[0.0,0.0],'delOffset':0.02,'refOffset':-1.0,'refDelt':0.01,
1322            'qPlot':False,'dPlot':False,'sqrtPlot':False
1323            }
1324        G2frame.PatternTree.SetItemPyData(
1325            Id,[valuesdict,
1326                [np.array(X),np.array(Y),np.array(W),np.zeros(N),np.zeros(N),np.zeros(N)]])
1327    return Id       #last powder pattern generated
1328           
1329# def powderFxyeSave(G2frame,exports,powderfile):
1330#     'Save a powder histogram as a GSAS FXYE file'
1331#     head,tail = ospath.split(powderfile)
1332#     name,ext = tail.split('.')
1333#     for i,export in enumerate(exports):
1334#         filename = ospath.join(head,name+'-%03d.'%(i)+ext)
1335#         prmname = filename.strip(ext)+'prm'
1336#         prm = open(prmname,'w')      #old style GSAS parm file
1337#         PickId = G2gd.GetPatternTreeItemId(G2frame, G2frame.root, export)
1338#         Inst = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame, \
1339#             PickId, 'Instrument Parameters'))[0]
1340#         prm.write( '            123456789012345678901234567890123456789012345678901234567890        '+'\n')
1341#         prm.write( 'INS   BANK      1                                                               '+'\n')
1342#         prm.write(('INS   HTYPE   %sR                                                              '+'\n')%(Inst['Type'][0]))
1343#         if 'Lam1' in Inst:              #Ka1 & Ka2
1344#             prm.write(('INS  1 ICONS%10.7f%10.7f    0.0000               0.990    0     0.500   '+'\n')%(Inst['Lam1'][0],Inst['Lam2'][0]))
1345#         elif 'Lam' in Inst:             #single wavelength
1346#             prm.write(('INS  1 ICONS%10.7f%10.7f    0.0000               0.990    0     0.500   '+'\n')%(Inst['Lam'][1],0.0))
1347#         prm.write( 'INS  1 IRAD     0                                                               '+'\n')
1348#         prm.write( 'INS  1I HEAD                                                                    '+'\n')
1349#         prm.write( 'INS  1I ITYP    0    0.0000  180.0000         1                                 '+'\n')
1350#         prm.write(('INS  1DETAZM%10.3f                                                          '+'\n')%(Inst['Azimuth'][0]))
1351#         prm.write( 'INS  1PRCF1     3    8   0.00100                                                '+'\n')
1352#         prm.write(('INS  1PRCF11     %15.6g%15.6g%15.6g%15.6g   '+'\n')%(Inst['U'][1],Inst['V'][1],Inst['W'][1],0.0))
1353#         prm.write(('INS  1PRCF12     %15.6g%15.6g%15.6g%15.6g   '+'\n')%(Inst['X'][1],Inst['Y'][1],Inst['SH/L'][1]/2.,Inst['SH/L'][1]/2.))
1354#         prm.close()
1355#         file = open(filename,'w')
1356#         print 'save powder pattern to file: ',filename
1357#         x,y,w,yc,yb,yd = G2frame.PatternTree.GetItemPyData(PickId)[1]
1358#         file.write(powderfile+'\n')
1359#         file.write('Instrument parameter file:'+ospath.split(prmname)[1]+'\n')
1360#         file.write('BANK 1 %d %d CONS %.2f %.2f 0 0 FXYE\n'%(len(x),len(x),\
1361#             100.*x[0],100.*(x[1]-x[0])))
1362#         s = list(np.sqrt(1./np.array(w)))       
1363#         XYW = zip(x,y,s)
1364#         for X,Y,S in XYW:
1365#             file.write("%15.6g %15.6g %15.6g\n" % (100.*X,Y,max(S,1.0)))
1366#         file.close()
1367#         print 'powder pattern file '+filename+' written'
1368       
1369# def powderXyeSave(G2frame,exports,powderfile):
1370#     'Save a powder histogram as a Topas XYE file'
1371#     head,tail = ospath.split(powderfile)
1372#     name,ext = tail.split('.')
1373#     for i,export in enumerate(exports):
1374#         filename = ospath.join(head,name+'-%03d.'%(i)+ext)
1375#         PickId = G2gd.GetPatternTreeItemId(G2frame, G2frame.root, export)
1376#         file = open(filename,'w')
1377#         file.write('#%s\n'%(export))
1378#         print 'save powder pattern to file: ',filename
1379#         x,y,w,yc,yb,yd = G2frame.PatternTree.GetItemPyData(PickId)[1]
1380#         s = list(np.sqrt(1./np.array(w)))       
1381#         XYW = zip(x,y,s)
1382#         for X,Y,W in XYW:
1383#             file.write("%15.6g %15.6g %15.6g\n" % (X,Y,W))
1384#         file.close()
1385#         print 'powder pattern file '+filename+' written'
1386       
1387def PDFSave(G2frame,exports):
1388    'Save a PDF G(r) and S(Q) in column formats'
1389    for export in exports:
1390        PickId = G2gd.GetPatternTreeItemId(G2frame, G2frame.root, export)
1391        SQname = 'S(Q)'+export[4:]
1392        GRname = 'G(R)'+export[4:]
1393        sqfilename = ospath.join(G2frame.dirname,export.replace(' ','_')[5:]+'.sq')
1394        grfilename = ospath.join(G2frame.dirname,export.replace(' ','_')[5:]+'.gr')
1395        sqId = G2gd.GetPatternTreeItemId(G2frame, PickId, SQname)
1396        grId = G2gd.GetPatternTreeItemId(G2frame, PickId, GRname)
1397        sqdata = np.array(G2frame.PatternTree.GetItemPyData(sqId)[1][:2]).T
1398        grdata = np.array(G2frame.PatternTree.GetItemPyData(grId)[1][:2]).T
1399        sqfile = open(sqfilename,'w')
1400        grfile = open(grfilename,'w')
1401        sqfile.write('#T S(Q) %s\n'%(export))
1402        grfile.write('#T G(R) %s\n'%(export))
1403        sqfile.write('#L Q     S(Q)\n')
1404        grfile.write('#L R     G(R)\n')
1405        for q,sq in sqdata:
1406            sqfile.write("%15.6g %15.6g\n" % (q,sq))
1407        sqfile.close()
1408        for r,gr in grdata:
1409            grfile.write("%15.6g %15.6g\n" % (r,gr))
1410        grfile.close()
1411   
1412def PeakListSave(G2frame,file,peaks):
1413    'Save powder peaks to a data file'
1414    print 'save peak list to file: ',G2frame.peaklistfile
1415    if not peaks:
1416        dlg = wx.MessageDialog(G2frame, 'No peaks!', 'Nothing to save!', wx.OK)
1417        try:
1418            result = dlg.ShowModal()
1419        finally:
1420            dlg.Destroy()
1421        return
1422    for peak in peaks:
1423        file.write("%10.4f %12.2f %10.3f %10.3f \n" % \
1424            (peak[0],peak[2],peak[4],peak[6]))
1425    print 'peak list saved'
1426             
1427def IndexPeakListSave(G2frame,peaks):
1428    'Save powder peaks from the indexing list'
1429    file = open(G2frame.peaklistfile,'wa')
1430    print 'save index peak list to file: ',G2frame.peaklistfile
1431    wx.BeginBusyCursor()
1432    try:
1433        if not peaks:
1434            dlg = wx.MessageDialog(G2frame, 'No peaks!', 'Nothing to save!', wx.OK)
1435            try:
1436                result = dlg.ShowModal()
1437            finally:
1438                dlg.Destroy()
1439            return
1440        for peak in peaks:
1441            file.write("%12.6f\n" % (peak[7]))
1442        file.close()
1443    finally:
1444        wx.EndBusyCursor()
1445    print 'index peak list saved'
1446   
1447def SetNewPhase(Name='New Phase',SGData=None,cell=None,Super=None):
1448    '''Create a new phase dict with default values for various parameters
1449
1450    :param str Name: Name for new Phase
1451
1452    :param dict SGData: space group data from :func:`GSASIIspc:SpcGroup`;
1453      defaults to data for P 1
1454
1455    :param list cell: unit cell parameter list; defaults to
1456      [1.0,1.0,1.0,90.,90,90.,1.]
1457
1458    '''
1459    if SGData is None: SGData = G2spc.SpcGroup('P 1')[1]
1460    if cell is None: cell=[1.0,1.0,1.0,90.,90,90.,1.]
1461    phaseData = {
1462        'ranId':ran.randint(0,sys.maxint),
1463        'General':{
1464            'Name':Name,
1465            'Type':'nuclear',
1466            'AtomPtrs':[3,1,7,9],
1467            'SGData':SGData,
1468            'Cell':[False,]+cell,
1469            'Pawley dmin':1.0,
1470            'Data plot type':'None',
1471            'SH Texture':{
1472                'Order':0,
1473                'Model':'cylindrical',
1474                'Sample omega':[False,0.0],
1475                'Sample chi':[False,0.0],
1476                'Sample phi':[False,0.0],
1477                'SH Coeff':[False,{}],
1478                'SHShow':False,
1479                'PFhkl':[0,0,1],
1480                'PFxyz':[0,0,1],
1481                'PlotType':'Pole figure',
1482                'Penalty':[['',],0.1,False,1.0]}},
1483        'Atoms':[],
1484        'Drawing':{},
1485        'Histograms':{},
1486        'Pawley ref':[],
1487        'RBModels':{},
1488        }
1489    if Super and Super.get('Use',False):
1490        phaseData['General'].update({'Type':'modulated','Super':True,'SuperSg':Super['ssSymb']})
1491        phaseData['General']['SSGData'] = G2spc.SSpcGroup(SGData,Super['ssSymb'])
1492        phaseData['General']['SuperVec'] = [Super['ModVec'],False,Super['maxH']]
1493
1494    return phaseData
1495       
1496class MultipleChoicesDialog(wx.Dialog):
1497    '''A dialog that offers a series of choices, each with a
1498    title and a wx.Choice widget. Intended to be used Modally.
1499    typical input:
1500
1501        *  choicelist=[ ('a','b','c'), ('test1','test2'),('no choice',)]
1502        *  headinglist = [ 'select a, b or c', 'select 1 of 2', 'No option here']
1503       
1504    selections are placed in self.chosen when OK is pressed
1505    '''
1506    def __init__(self,choicelist,headinglist,
1507                 head='Select options',
1508                 title='Please select from options below',
1509                 parent=None):
1510        self.chosen = []
1511        wx.Dialog.__init__(
1512            self,parent,wx.ID_ANY,head, 
1513            pos=wx.DefaultPosition,style=wx.DEFAULT_DIALOG_STYLE)
1514        panel = wx.Panel(self)
1515        mainSizer = wx.BoxSizer(wx.VERTICAL)
1516        mainSizer.Add((10,10),1)
1517        topLabl = wx.StaticText(panel,wx.ID_ANY,title)
1518        mainSizer.Add(topLabl,0,wx.ALIGN_CENTER_VERTICAL|wx.CENTER,10)
1519        self.ChItems = []
1520        for choice,lbl in zip(choicelist,headinglist):
1521            mainSizer.Add((10,10),1)
1522            self.chosen.append(0)
1523            topLabl = wx.StaticText(panel,wx.ID_ANY,' '+lbl)
1524            mainSizer.Add(topLabl,0,wx.ALIGN_LEFT,10)
1525            self.ChItems.append(wx.Choice(self, wx.ID_ANY, (100, 50), choices = choice))
1526            mainSizer.Add(self.ChItems[-1],0,wx.ALIGN_CENTER,10)
1527
1528        OkBtn = wx.Button(panel,-1,"Ok")
1529        OkBtn.Bind(wx.EVT_BUTTON, self.OnOk)
1530        cancelBtn = wx.Button(panel,-1,"Cancel")
1531        cancelBtn.Bind(wx.EVT_BUTTON, self.OnCancel)
1532        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
1533        btnSizer.Add((20,20),1)
1534        btnSizer.Add(OkBtn)
1535        btnSizer.Add((20,20),1)
1536        btnSizer.Add(cancelBtn)
1537        btnSizer.Add((20,20),1)
1538        mainSizer.Add(btnSizer,0,wx.EXPAND|wx.BOTTOM|wx.TOP, 10)
1539        panel.SetSizer(mainSizer)
1540        panel.Fit()
1541        self.Fit()
1542       
1543    def OnOk(self,event):
1544        parent = self.GetParent()
1545        if parent is not None: parent.Raise()
1546        # save the results from the choice widgets
1547        self.chosen = []
1548        for w in self.ChItems:
1549            self.chosen.append(w.GetSelection())
1550        self.EndModal(wx.ID_OK)             
1551           
1552    def OnCancel(self,event):
1553        parent = self.GetParent()
1554        if parent is not None: parent.Raise()
1555        self.chosen = []
1556        self.EndModal(wx.ID_CANCEL)             
1557           
1558def ExtractFileFromZip(filename, selection=None, confirmread=True,
1559                       confirmoverwrite=True, parent=None,
1560                       multipleselect=False):
1561    '''If the filename is a zip file, extract a file from that
1562    archive.
1563
1564    :param list Selection: used to predefine the name of the file
1565      to be extracted. Filename case and zip directory name are
1566      ignored in selection; the first matching file is used.
1567
1568    :param bool confirmread: if True asks the user to confirm before expanding
1569      the only file in a zip
1570
1571    :param bool confirmoverwrite: if True asks the user to confirm
1572      before overwriting if the extracted file already exists
1573
1574    :param bool multipleselect: if True allows more than one zip
1575      file to be extracted, a list of file(s) is returned.
1576      If only one file is present, do not ask which one, otherwise
1577      offer a list of choices (unless selection is used).
1578   
1579    :returns: the name of the file that has been created or a
1580      list of files (see multipleselect)
1581
1582    If the file is not a zipfile, return the name of the input file.
1583    If the zipfile is empty or no file has been selected, return None
1584    '''
1585    import zipfile # do this now, since we can save startup time by doing this only on need
1586    import shutil
1587    zloc = os.path.split(filename)[0]
1588    if not zipfile.is_zipfile(filename):
1589        #print("not zip")
1590        return filename
1591
1592    z = zipfile.ZipFile(filename,'r')
1593    zinfo = z.infolist()
1594
1595    if len(zinfo) == 0:
1596        #print('Zip has no files!')
1597        zlist = [-1]
1598    if selection:
1599        choices = [os.path.split(i.filename)[1].lower() for i in zinfo]
1600        if selection.lower() in choices:
1601            zlist = [choices.index(selection.lower())]
1602        else:
1603            print('debug: file '+str(selection)+' was not found in '+str(filename))
1604            zlist = [-1]
1605    elif len(zinfo) == 1 and confirmread:
1606        result = wx.ID_NO
1607        dlg = wx.MessageDialog(
1608            parent,
1609            'Is file '+str(zinfo[0].filename)+
1610            ' what you want to extract from '+
1611            str(os.path.split(filename)[1])+'?',
1612            'Confirm file', 
1613            wx.YES_NO | wx.ICON_QUESTION)
1614        try:
1615            result = dlg.ShowModal()
1616        finally:
1617            dlg.Destroy()
1618        if result == wx.ID_NO:
1619            zlist = [-1]
1620        else:
1621            zlist = [0]
1622    elif len(zinfo) == 1:
1623        zlist = [0]
1624    elif multipleselect:
1625        # select one or more from a from list
1626        choices = [i.filename for i in zinfo]
1627        dlg = G2G.G2MultiChoiceDialog(parent,'Select file(s) to extract from zip file '+str(filename),
1628            'Choose file(s)',choices)
1629        if dlg.ShowModal() == wx.ID_OK:
1630            zlist = dlg.GetSelections()
1631        else:
1632            zlist = []
1633        dlg.Destroy()
1634    else:
1635        # select one from a from list
1636        choices = [i.filename for i in zinfo]
1637        dlg = wx.SingleChoiceDialog(parent,
1638            'Select file to extract from zip file'+str(filename),'Choose file',
1639            choices,)
1640        if dlg.ShowModal() == wx.ID_OK:
1641            zlist = [dlg.GetSelection()]
1642        else:
1643            zlist = [-1]
1644        dlg.Destroy()
1645       
1646    outlist = []
1647    for zindex in zlist:
1648        if zindex >= 0:
1649            efil = os.path.join(zloc, os.path.split(zinfo[zindex].filename)[1])
1650            if os.path.exists(efil) and confirmoverwrite:
1651                result = wx.ID_NO
1652                dlg = wx.MessageDialog(parent,
1653                    'File '+str(efil)+' already exists. OK to overwrite it?',
1654                    'Confirm overwrite',wx.YES_NO | wx.ICON_QUESTION)
1655                try:
1656                    result = dlg.ShowModal()
1657                finally:
1658                    dlg.Destroy()
1659                if result == wx.ID_NO:
1660                    zindex = -1
1661        if zindex >= 0:
1662            # extract the file to the current directory, regardless of it's original path
1663            #z.extract(zinfo[zindex],zloc)
1664            eloc,efil = os.path.split(zinfo[zindex].filename)
1665            outfile = os.path.join(zloc, efil)
1666            fpin = z.open(zinfo[zindex])
1667            fpout = file(outfile, "wb")
1668            shutil.copyfileobj(fpin, fpout)
1669            fpin.close()
1670            fpout.close()
1671            outlist.append(outfile)
1672    z.close()
1673    if multipleselect and len(outlist) >= 1:
1674        return outlist
1675    elif len(outlist) == 1:
1676        return outlist[0]
1677    else:
1678        return None
1679
1680######################################################################
1681# base classes for reading various types of data files
1682#   not used directly, only by subclassing
1683######################################################################
1684E,SGData = G2spc.SpcGroup('P 1') # data structure for default space group
1685P1SGData = SGData
1686class ImportBaseclass(object):
1687    '''Defines a base class for the reading of input files (diffraction
1688    data, coordinates,...). See :ref:`Writing a Import Routine<Import_routines>`
1689    for an explanation on how to use a subclass of this class.
1690    '''
1691    class ImportException(Exception):
1692        '''Defines an Exception that is used when an import routine hits an expected error,
1693        usually in .Reader.
1694
1695        Good practice is that the Reader should define a value in self.errors that
1696        tells the user some information about what is wrong with their file.         
1697        '''
1698        pass
1699
1700    def __init__(self,
1701                 formatName,
1702                 longFormatName=None,
1703                 extensionlist=[],
1704                 strictExtension=False,
1705                 ):
1706        self.formatName = formatName # short string naming file type
1707        if longFormatName: # longer string naming file type
1708            self.longFormatName = longFormatName
1709        else:
1710            self.longFormatName = formatName
1711        # define extensions that are allowed for the file type
1712        # for windows, remove any extensions that are duplicate, as case is ignored
1713        if sys.platform == 'windows' and extensionlist:
1714            extensionlist = list(set([s.lower() for s in extensionlist]))
1715        self.extensionlist = extensionlist
1716        # If strictExtension is True, the file will not be read, unless
1717        # the extension matches one in the extensionlist
1718        self.strictExtension = strictExtension
1719        self.errors = ''
1720        self.warnings = ''
1721        # used for readers that will use multiple passes to read
1722        # more than one data block
1723        self.repeat = False
1724        self.selections = []
1725        self.repeatcount = 0
1726        self.readfilename = '?'
1727        #print 'created',self.__class__
1728
1729    def ReInitialize(self):
1730        'Reinitialize the Reader to initial settings'
1731        self.errors = ''
1732        self.warnings = ''
1733        self.repeat = False
1734        self.repeatcount = 0
1735        self.readfilename = '?'
1736
1737    def BlockSelector(self, ChoiceList, ParentFrame=None,
1738                      title='Select a block',
1739                      size=None, header='Block Selector',
1740                      useCancel=True):
1741        ''' Provide a wx dialog to select a block if the file contains more
1742        than one set of data and one must be selected
1743        '''
1744        if useCancel:
1745            dlg = wx.SingleChoiceDialog(
1746                ParentFrame,title, header,ChoiceList)
1747        else:
1748            dlg = wx.SingleChoiceDialog(
1749                ParentFrame,title, header,ChoiceList,
1750                style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.OK|wx.CENTRE)
1751        if size: dlg.SetSize(size)
1752        dlg.CenterOnParent()
1753        if dlg.ShowModal() == wx.ID_OK:
1754            sel = dlg.GetSelection()
1755            return sel
1756        else:
1757            return None
1758        dlg.Destroy()
1759
1760    def MultipleBlockSelector(self, ChoiceList, ParentFrame=None,
1761        title='Select a block',size=None, header='Block Selector'):
1762        '''Provide a wx dialog to select a block of data if the
1763        file contains more than one set of data and one must be
1764        selected.
1765
1766        :returns: a list of the selected blocks
1767        '''
1768        dlg = wx.MultiChoiceDialog(ParentFrame,title, header,ChoiceList+['Select all'],
1769            wx.CHOICEDLG_STYLE)
1770        dlg.CenterOnParent()
1771        if size: dlg.SetSize(size)
1772        if dlg.ShowModal() == wx.ID_OK:
1773            sel = dlg.GetSelections()
1774        else:
1775            return []
1776        dlg.Destroy()
1777        selected = []
1778        if len(ChoiceList) in sel:
1779            return range(len(ChoiceList))
1780        else:
1781            return sel
1782        return selected
1783
1784    def MultipleChoicesDialog(self, choicelist, headinglist, ParentFrame=None, **kwargs):
1785        '''A modal dialog that offers a series of choices, each with a title and a wx.Choice
1786        widget. Typical input:
1787       
1788           * choicelist=[ ('a','b','c'), ('test1','test2'),('no choice',)]
1789           
1790           * headinglist = [ 'select a, b or c', 'select 1 of 2', 'No option here']
1791           
1792        optional keyword parameters are: head (window title) and title
1793        returns a list of selected indicies for each choice (or None)
1794        '''
1795        result = None
1796        dlg = MultipleChoicesDialog(choicelist,headinglist,
1797            parent=ParentFrame, **kwargs)         
1798        dlg.CenterOnParent()
1799        if dlg.ShowModal() == wx.ID_OK:
1800            result = dlg.chosen
1801        dlg.Destroy()
1802        return result
1803
1804    def ShowBusy(self):
1805        wx.BeginBusyCursor()
1806#        wx.Yield() # make it happen now!
1807
1808    def DoneBusy(self):
1809        wx.EndBusyCursor()
1810        wx.Yield() # make it happen now!
1811       
1812#    def Reader(self, filename, filepointer, ParentFrame=None, **unused):
1813#        '''This method must be supplied in the child class to read the file.
1814#        if the read fails either return False or raise an Exception
1815#        preferably of type ImportException.
1816#        '''
1817#        #start reading
1818#        raise ImportException("Error occurred while...")
1819#        self.errors += "Hint for user on why the error occur
1820#        return False # if an error occurs
1821#        return True # if read OK
1822
1823    def ExtensionValidator(self, filename):
1824        '''This methods checks if the file has the correct extension
1825        Return False if this filename will not be supported by this reader
1826        Return True if the extension matches the list supplied by the reader
1827        Return None if the reader allows un-registered extensions
1828        '''
1829        if filename:
1830            ext = os.path.splitext(filename)[1]
1831            if sys.platform == 'windows': ext = ext.lower()
1832            if ext in self.extensionlist: return True
1833            if self.strictExtension: return False
1834        return None
1835
1836    def ContentsValidator(self, filepointer):
1837        '''This routine will attempt to determine if the file can be read
1838        with the current format.
1839        This will typically be overridden with a method that
1840        takes a quick scan of [some of]
1841        the file contents to do a "sanity" check if the file
1842        appears to match the selected format.
1843        Expected to be called via self.Validator()
1844        '''
1845        #filepointer.seek(0) # rewind the file pointer
1846        return True
1847
1848    def CIFValidator(self, filepointer):
1849        '''A :meth:`ContentsValidator` for use to validate CIF files.
1850        '''
1851        for i,l in enumerate(filepointer):
1852            if i >= 1000: return True
1853            '''Encountered only blank lines or comments in first 1000
1854            lines. This is unlikely, but assume it is CIF anyway, since we are
1855            even less likely to find a file with nothing but hashes and
1856            blank lines'''
1857            line = l.strip()
1858            if len(line) == 0: # ignore blank lines
1859                continue 
1860            elif line.startswith('#'): # ignore comments
1861                continue 
1862            elif line.startswith('data_'): # on the right track, accept this file
1863                return True
1864            else: # found something invalid
1865                self.errors = 'line '+str(i+1)+' contains unexpected data:\n'
1866                self.errors += '  '+str(l)
1867                self.errors += '  Note: a CIF should only have blank lines or comments before'
1868                self.errors += '        a data_ statement begins a block.'
1869                return False 
1870
1871class ImportPhase(ImportBaseclass):
1872    '''Defines a base class for the reading of files with coordinates
1873
1874    Objects constructed that subclass this (in import/G2phase_*.py etc.) will be used
1875    in :meth:`GSASII.GSASII.OnImportPhase`.
1876    See :ref:`Writing a Import Routine<Import_Routines>`
1877    for an explanation on how to use this class.
1878
1879    '''
1880    def __init__(self,formatName,longFormatName=None,extensionlist=[],
1881        strictExtension=False,):
1882        # call parent __init__
1883        ImportBaseclass.__init__(self,formatName,longFormatName,
1884            extensionlist,strictExtension)
1885        self.Phase = None # a phase must be created with G2IO.SetNewPhase in the Reader
1886        self.Constraints = None
1887
1888    def PhaseSelector(self, ChoiceList, ParentFrame=None,
1889        title='Select a phase', size=None,header='Phase Selector'):
1890        ''' Provide a wx dialog to select a phase if the file contains more
1891        than one phase
1892        '''
1893        return self.BlockSelector(ChoiceList,ParentFrame,title,
1894            size,header)
1895
1896class ImportStructFactor(ImportBaseclass):
1897    '''Defines a base class for the reading of files with tables
1898    of structure factors.
1899
1900    Structure factors are read with a call to :meth:`GSASII.GSASII.OnImportSfact`
1901    which in turn calls :meth:`GSASII.GSASII.OnImportGeneric`, which calls
1902    methods :meth:`ExtensionValidator`, :meth:`ContentsValidator` and
1903    :meth:`Reader`.
1904
1905    See :ref:`Writing a Import Routine<Import_Routines>`
1906    for an explanation on how to use import classes in general. The specifics
1907    for reading a structure factor histogram require that
1908    the ``Reader()`` routine in the import
1909    class need to do only a few things: It
1910    should load :attr:`RefDict` item ``'RefList'`` with the reflection list,
1911    and set :attr:`Parameters` with the instrument parameters
1912    (initialized with :meth:`InitParameters` and set with :meth:`UpdateParameters`).
1913    '''
1914    def __init__(self,formatName,longFormatName=None,extensionlist=[],
1915        strictExtension=False,):
1916        ImportBaseclass.__init__(self,formatName,longFormatName,
1917            extensionlist,strictExtension)
1918
1919        # define contents of Structure Factor entry
1920        self.Parameters = []
1921        'self.Parameters is a list with two dicts for data parameter settings'
1922        self.InitParameters()
1923        self.RefDict = {'RefList':[],'FF':{},'Super':0}
1924        self.Banks = []             #for multi bank data (usually TOF)
1925        '''self.RefDict is a dict containing the reflection information, as read from the file.
1926        Item 'RefList' contains the reflection information. See the
1927        :ref:`Single Crystal Reflection Data Structure<XtalRefl_table>`
1928        for the contents of each row. Dict element 'FF'
1929        contains the form factor values for each element type; if this entry
1930        is left as initialized (an empty list) it will be initialized as needed later.
1931        '''
1932    def ReInitialize(self):
1933        'Reinitialize the Reader to initial settings'
1934        ImportBaseclass.ReInitialize(self)
1935        self.InitParameters()
1936        self.Banks = []             #for multi bank data (usually TOF)
1937        self.RefDict = {'RefList':[],'FF':{},'Super':0}
1938       
1939    def InitParameters(self):
1940        'initialize the instrument parameters structure'
1941        Lambda = 0.70926
1942        HistType = 'SXC'
1943        self.Parameters = [{'Type':[HistType,HistType], # create the structure
1944                            'Lam':[Lambda,Lambda]
1945                            }, {}]
1946        'Parameters is a list with two dicts for data parameter settings'
1947
1948    def UpdateParameters(self,Type=None,Wave=None):
1949        'Revise the instrument parameters'
1950        if Type is not None:
1951            self.Parameters[0]['Type'] = [Type,Type]
1952        if Wave is not None:
1953            self.Parameters[0]['Lam'] = [Wave,Wave]           
1954                       
1955######################################################################
1956class ImportPowderData(ImportBaseclass):
1957    '''Defines a base class for the reading of files with powder data.
1958
1959    Objects constructed that subclass this (in import/G2pwd_*.py etc.) will be used
1960    in :meth:`GSASII.GSASII.OnImportPowder`.
1961    See :ref:`Writing a Import Routine<Import_Routines>`
1962    for an explanation on how to use this class.
1963    '''
1964    def __init__(self,
1965                 formatName,
1966                 longFormatName=None,
1967                 extensionlist=[],
1968                 strictExtension=False,
1969                 ):
1970        ImportBaseclass.__init__(self,formatName,
1971                                            longFormatName,
1972                                            extensionlist,
1973                                            strictExtension)
1974        self.clockWd = None  # used in TOF
1975        self.ReInitialize()
1976       
1977    def ReInitialize(self):
1978        'Reinitialize the Reader to initial settings'
1979        ImportBaseclass.ReInitialize(self)
1980        self.powderentry = ['',None,None] #  (filename,Pos,Bank)
1981        self.powderdata = [] # Powder dataset
1982        '''A powder data set is a list with items [x,y,w,yc,yb,yd]:
1983                np.array(x), # x-axis values
1984                np.array(y), # powder pattern intensities
1985                np.array(w), # 1/sig(intensity)^2 values (weights)
1986                np.array(yc), # calc. intensities (zero)
1987                np.array(yb), # calc. background (zero)
1988                np.array(yd), # obs-calc profiles
1989        '''                           
1990        self.comments = []
1991        self.idstring = ''
1992        self.Sample = G2pdG.SetDefaultSample() # default sample parameters
1993        self.Controls = {}  # items to be placed in top-level Controls
1994        self.GSAS = None     # used in TOF
1995        self.repeat_instparm = True # Should a parm file be
1996        #                             used for multiple histograms?
1997        self.instparm = None # name hint from file of instparm to use
1998        self.instfile = '' # full path name to instrument parameter file
1999        self.instbank = '' # inst parm bank number
2000        self.instmsg = ''  # a label that gets printed to show
2001                           # where instrument parameters are from
2002        self.numbanks = 1
2003        self.instdict = {} # place items here that will be transferred to the instrument parameters
2004        self.pwdparms = {} # place parameters that are transferred directly to the tree
2005                           # here (typically from an existing GPX file)
2006######################################################################
2007class ImportSmallAngleData(ImportBaseclass):
2008    '''Defines a base class for the reading of files with small angle data.
2009    See :ref:`Writing a Import Routine<Import_Routines>`
2010    for an explanation on how to use this class.
2011    '''
2012    def __init__(self,formatName,longFormatName=None,extensionlist=[],
2013        strictExtension=False,):
2014           
2015        ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist,
2016            strictExtension)
2017        self.ReInitialize()
2018       
2019    def ReInitialize(self):
2020        'Reinitialize the Reader to initial settings'
2021        ImportBaseclass.ReInitialize(self)
2022        self.smallangleentry = ['',None,None] #  (filename,Pos,Bank)
2023        self.smallangledata = [] # SASD dataset
2024        '''A small angle data set is a list with items [x,y,w,yc,yd]:
2025                np.array(x), # x-axis values
2026                np.array(y), # powder pattern intensities
2027                np.array(w), # 1/sig(intensity)^2 values (weights)
2028                np.array(yc), # calc. intensities (zero)
2029                np.array(yd), # obs-calc profiles
2030                np.array(yb), # preset bkg
2031        '''                           
2032        self.comments = []
2033        self.idstring = ''
2034        self.Sample = G2pdG.SetDefaultSample()
2035        self.GSAS = None     # used in TOF
2036        self.clockWd = None  # used in TOF
2037        self.numbanks = 1
2038        self.instdict = {} # place items here that will be transferred to the instrument parameters
2039
2040######################################################################
2041class ImportImage(ImportBaseclass):
2042    '''Defines a base class for the reading of images
2043
2044    Structure factors are read with a call to :meth:`GSASII.GSASII.OnImportImage`
2045    which in turn calls :meth:`GSASII.GSASII.OnImportGeneric`, which calls
2046    methods :meth:`ExtensionValidator`, :meth:`ContentsValidator` and
2047    :meth:`Reader`.
2048
2049    See :ref:`Writing a Import Routine<Import_Routines>`
2050    for an explanation on how to use import classes in general. The specifics
2051    for reading an image requires that the ``Reader()`` routine in the import
2052    class need to do only a few things:...
2053   
2054    (should load :attr:`RefDict` item ``'RefList'`` with the reflection list,
2055    (and set :attr:`Parameters` with the instrument parameters
2056    (initialized with :meth:`InitParameters` and set with :meth:`UpdateParameters`).
2057    '''
2058    def __init__(self,formatName,longFormatName=None,extensionlist=[],
2059        strictExtension=False,):
2060        ImportBaseclass.__init__(self,formatName,longFormatName,
2061            extensionlist,strictExtension)
2062        self.InitParameters()
2063       
2064    def ReInitialize(self):
2065        'Reinitialize the Reader to initial settings -- not used at present'
2066        ImportBaseclass.ReInitialize(self)
2067        self.InitParameters()
2068       
2069    def InitParameters(self):
2070        'initialize the instrument parameters structure'
2071        self.Comments = ['No comments']
2072        self.Data = {}
2073        self.Npix = 0
2074        self.Image = None
2075
2076    def LoadImage(self,ParentFrame,imagefile):
2077        '''Optionally, call this after reading in an image to load it into the tree.
2078        This does saves time by preventing a reread of the same information.
2079        '''
2080        if ParentFrame:
2081            ParentFrame.ImageZ = self.Image   # store the image for plotting
2082            ParentFrame.oldImagefile = imagefile # save the name of the last image file read
2083           
2084
2085######################################################################
2086class ExportBaseclass(object):
2087    '''Defines a base class for the exporting of GSAS-II results.
2088
2089    This class is subclassed in the various exports/G2export_*.py files. Those files
2090    are imported in :meth:`GSASII.GSASII._init_Exports` which defines the
2091    appropriate menu items for each one and the .Exporter method is called
2092    directly from the menu item.
2093
2094    Routines may also define a .Writer method, which is used to write a single
2095    file without invoking any GUI objects.
2096    '''
2097    def __init__(self,
2098                 G2frame,
2099                 formatName,
2100                 extension,
2101                 longFormatName=None,
2102                 ):
2103        self.G2frame = G2frame
2104        self.formatName = formatName # short string naming file type
2105        self.extension = extension
2106        if longFormatName: # longer string naming file type
2107            self.longFormatName = longFormatName
2108        else:
2109            self.longFormatName = formatName
2110        self.OverallParms = {}
2111        self.Phases = {}
2112        self.Histograms = {}
2113        self.powderDict = {}
2114        self.xtalDict = {}
2115        self.parmDict = {}
2116        self.sigDict = {}
2117        # updated in InitExport:
2118        self.currentExportType = None # type of export that has been requested
2119        # updated in ExportSelect (when used):
2120        self.phasenam = None # a list of selected phases
2121        self.histnam = None # a list of selected histograms
2122        self.filename = None # name of file to be written (single export) or template (multiple files)
2123        self.dirname = '' # name of directory where file(s) will be written
2124        self.fullpath = '' # name of file being written -- full path
2125       
2126        # items that should be defined in a subclass of this class
2127        self.exporttype = []  # defines the type(s) of exports that the class can handle.
2128        # The following types are defined: 'project', "phase", "powder", "single"
2129        self.multiple = False # set as True if the class can export multiple phases or histograms
2130        # self.multiple is ignored for "project" exports
2131
2132    def InitExport(self,event):
2133        '''Determines the type of menu that called the Exporter and
2134        misc initialization.
2135        '''
2136        self.filename = None # name of file to be written (single export)
2137        self.dirname = '' # name of file to be written (multiple export)
2138        if event:
2139            self.currentExportType = self.G2frame.ExportLookup.get(event.Id)
2140
2141    def MakePWDRfilename(self,hist):
2142        '''Make a filename root (no extension) from a PWDR histogram name
2143
2144        :param str hist: the histogram name in data tree (starts with "PWDR ")
2145        '''
2146        file0 = ''
2147        file1 = hist[5:]
2148        # replace repeated blanks
2149        while file1 != file0:
2150            file0 = file1
2151            file1 = file0.replace('  ',' ').strip()
2152        file0 = file1.replace('Azm= ','A')
2153        # if angle has unneeded decimal places on aziumuth, remove them
2154        if file0[-3:] == '.00': file0 = file0[:-3]
2155        file0 = file0.replace('.','_')
2156        file0 = file0.replace(' ','_')
2157        return file0
2158
2159    def ExportSelect(self,AskFile='ask'):
2160        '''Selects histograms or phases when needed. Sets a default file name when
2161        requested in self.filename; always sets a default directory in self.dirname.
2162
2163        :param bool AskFile: Determines how this routine processes getting a
2164          location to store the current export(s).
2165         
2166          * if AskFile is 'ask' (default option), get the name of the file to be written;
2167            self.filename and self.dirname are always set. In the case where
2168            multiple files must be generated, the export routine should do this
2169            based on self.filename as a template.
2170          * if AskFile is 'dir', get the name of the directory to be used;
2171            self.filename is not used, but self.dirname is always set. The export routine
2172            will always generate the file name.
2173          * if AskFile is 'single', get only the name of the directory to be used when
2174            multiple items will be written (as multiple files) are used
2175            *or* a complete file name is requested when a single file
2176            name is selected. self.dirname is always set and self.filename used
2177            only when a single file is selected.
2178          * if AskFile is 'default', creates a name of the file to be used from
2179            the name of the project (.gpx) file. If the project has not been saved,
2180            then the name of file is requested.
2181            self.filename and self.dirname are always set. In the case where
2182            multiple file names must be generated, the export routine should do this
2183            based on self.filename.
2184          * if AskFile is 'default-dir', sets self.dirname from the project (.gpx)
2185            file. If the project has not been saved, then a directory is requested.
2186            self.filename is not used.
2187
2188        :returns: True in case of an error
2189        '''
2190       
2191        numselected = 1
2192        if self.currentExportType == 'phase':
2193            if len(self.Phases) == 0:
2194                self.G2frame.ErrorDialog(
2195                    'Empty project',
2196                    'Project does not contain any phases.')
2197                return True
2198            elif len(self.Phases) == 1:
2199                self.phasenam = self.Phases.keys()
2200            elif self.multiple: 
2201                choices = sorted(self.Phases.keys())
2202                phasenum = G2G.ItemSelector(choices,self.G2frame,multiple=True)
2203                if phasenum is None: return True
2204                self.phasenam = [choices[i] for i in phasenum]
2205                if not self.phasenam: return True
2206                numselected = len(self.phasenam)
2207            else:
2208                choices = sorted(self.Phases.keys())
2209                phasenum = G2G.ItemSelector(choices,self.G2frame)
2210                if phasenum is None: return True
2211                self.phasenam = [choices[phasenum]]
2212                numselected = len(self.phasenam)
2213        elif self.currentExportType == 'single':
2214            if len(self.xtalDict) == 0:
2215                self.G2frame.ErrorDialog(
2216                    'Empty project',
2217                    'Project does not contain any single crystal data.')
2218                return True
2219            elif len(self.xtalDict) == 1:
2220                self.histnam = self.xtalDict.values()
2221            elif self.multiple:
2222                choices = sorted(self.xtalDict.values())
2223                hnum = G2G.ItemSelector(choices,self.G2frame,multiple=True)
2224                if not hnum: return True
2225                self.histnam = [choices[i] for i in hnum]
2226                numselected = len(self.histnam)
2227            else:
2228                choices = sorted(self.xtalDict.values())
2229                hnum = G2G.ItemSelector(choices,self.G2frame)
2230                if hnum is None: return True
2231                self.histnam = [choices[hnum]]
2232                numselected = len(self.histnam)
2233        elif self.currentExportType == 'powder':
2234            if len(self.powderDict) == 0:
2235                self.G2frame.ErrorDialog(
2236                    'Empty project',
2237                    'Project does not contain any powder data.')
2238                return True
2239            elif len(self.powderDict) == 1:
2240                self.histnam = self.powderDict.values()
2241            elif self.multiple:
2242                choices = sorted(self.powderDict.values())
2243                hnum = G2G.ItemSelector(choices,self.G2frame,multiple=True)
2244                if not hnum: return True
2245                self.histnam = [choices[i] for i in hnum]
2246                numselected = len(self.histnam)
2247            else:
2248                choices = sorted(self.powderDict.values())
2249                hnum = G2G.ItemSelector(choices,self.G2frame)
2250                if hnum is None: return True
2251                self.histnam = [choices[hnum]]
2252                numselected = len(self.histnam)
2253        elif self.currentExportType == 'image':
2254            if len(self.Histograms) == 0:
2255                self.G2frame.ErrorDialog(
2256                    'Empty project',
2257                    'Project does not contain any images.')
2258                return True
2259            elif len(self.Histograms) == 1:
2260                self.histnam = self.Histograms.keys()
2261            else:
2262                choices = sorted(self.Histograms.keys())
2263                hnum = G2G.ItemSelector(choices,self.G2frame,multiple=self.multiple)
2264                if self.multiple:
2265                    if not hnum: return True
2266                    self.histnam = [choices[i] for i in hnum]
2267                else:
2268                    if hnum is None: return True
2269                    self.histnam = [choices[hnum]]
2270                numselected = len(self.histnam)
2271        if self.currentExportType == 'map':
2272            # search for phases with maps
2273            mapPhases = []
2274            choices = []
2275            for phasenam in sorted(self.Phases):
2276                phasedict = self.Phases[phasenam] # pointer to current phase info           
2277                if len(phasedict['General']['Map'].get('rho',[])):
2278                    mapPhases.append(phasenam)
2279                    if phasedict['General']['Map'].get('Flip'):
2280                        choices.append('Charge flip map: '+str(phasenam))
2281                    elif phasedict['General']['Map'].get('MapType'):
2282                        choices.append(
2283                            str(phasedict['General']['Map'].get('MapType'))
2284                            + ' map: ' + str(phasenam))
2285                    else:
2286                        choices.append('unknown map: '+str(phasenam))
2287            # select a map if needed
2288            if len(mapPhases) == 0:
2289                self.G2frame.ErrorDialog(
2290                    'Empty project',
2291                    'Project does not contain any maps.')
2292                return True
2293            elif len(mapPhases) == 1:
2294                self.phasenam = mapPhases
2295            else: 
2296                phasenum = G2G.ItemSelector(choices,self.G2frame,multiple=self.multiple)
2297                if self.multiple:
2298                    if not phasenum: return True
2299                    self.phasenam = [mapPhases[i] for i in phasenum]
2300                else:
2301                    if phasenum is None: return True
2302                    self.phasenam = [mapPhases[phasenum]]
2303            numselected = len(self.phasenam)
2304
2305        # items selected, now set self.dirname and usually self.filename
2306        if AskFile == 'ask' or (AskFile == 'single' and numselected == 1) or (
2307            AskFile == 'default' and not self.G2frame.GSASprojectfile
2308            ):
2309            filename = self.askSaveFile()
2310            if not filename: return True
2311            self.dirname,self.filename = os.path.split(filename)
2312        elif AskFile == 'dir' or AskFile == 'single' or (
2313            AskFile == 'default-dir' and not self.G2frame.GSASprojectfile
2314            ):
2315            self.dirname = self.askSaveDirectory()
2316            if not self.dirname: return True
2317        elif AskFile == 'default-dir' or AskFile == 'default':
2318            self.dirname,self.filename = os.path.split(
2319                os.path.splitext(self.G2frame.GSASprojectfile)[0] + self.extension
2320                )
2321        else:
2322            raise Exception('This should not happen!')
2323       
2324    def loadParmDict(self):
2325        '''Load the GSAS-II refinable parameters from the tree into a dict (self.parmDict). Update
2326        refined values to those from the last cycle and set the uncertainties for the
2327        refined parameters in another dict (self.sigDict).
2328
2329        Expands the parm & sig dicts to include values derived from constraints.
2330        '''
2331        self.parmDict = {}
2332        self.sigDict = {}
2333        rigidbodyDict = {}
2334        covDict = {}
2335        consDict = {}
2336        Histograms,Phases = self.G2frame.GetUsedHistogramsAndPhasesfromTree()
2337        if self.G2frame.PatternTree.IsEmpty(): return # nothing to do
2338        item, cookie = self.G2frame.PatternTree.GetFirstChild(self.G2frame.root)
2339        while item:
2340            name = self.G2frame.PatternTree.GetItemText(item)
2341            if name == 'Rigid bodies':
2342                 rigidbodyDict = self.G2frame.PatternTree.GetItemPyData(item)
2343            elif name == 'Covariance':
2344                 covDict = self.G2frame.PatternTree.GetItemPyData(item)
2345            elif name == 'Constraints':
2346                 consDict = self.G2frame.PatternTree.GetItemPyData(item)
2347            item, cookie = self.G2frame.PatternTree.GetNextChild(self.G2frame.root, cookie)
2348        rbVary,rbDict =  G2stIO.GetRigidBodyModels(rigidbodyDict,Print=False)
2349        self.parmDict.update(rbDict)
2350        rbIds = rigidbodyDict.get('RBIds',{'Vector':[],'Residue':[]})
2351        Natoms,atomIndx,phaseVary,phaseDict,pawleyLookup,FFtables,BLtables,maxSSwave =  G2stIO.GetPhaseData(
2352            Phases,RestraintDict=None,rbIds=rbIds,Print=False)
2353        self.parmDict.update(phaseDict)
2354        hapVary,hapDict,controlDict =  G2stIO.GetHistogramPhaseData(
2355            Phases,Histograms,Print=False,resetRefList=False)
2356        self.parmDict.update(hapDict)
2357        histVary,histDict,controlDict =  G2stIO.GetHistogramData(Histograms,Print=False)
2358        self.parmDict.update(histDict)
2359        self.parmDict.update(zip(
2360            covDict.get('varyList',[]),
2361            covDict.get('variables',[])))
2362        self.sigDict = dict(zip(
2363            covDict.get('varyList',[]),
2364            covDict.get('sig',[])))
2365        # expand to include constraints: first compile a list of constraints
2366        constList = []
2367        for item in consDict:
2368            if item.startswith('_'): continue
2369            constList += consDict[item]
2370        # now process the constraints
2371        G2mv.InitVars()
2372        constDict,fixedList,ignored = G2stIO.ProcessConstraints(constList)
2373        varyList = covDict.get('varyListStart')
2374        if varyList is None and len(constDict) == 0:
2375            # no constraints can use varyList
2376            varyList = covDict.get('varyList')
2377        elif varyList is None:
2378            # old GPX file from before pre-constraint varyList is saved
2379            print ' *** Old refinement: Please use Calculate/Refine to redo  ***'
2380            raise Exception(' *** Export aborted ***')
2381        else:
2382            varyList = list(varyList)
2383        try:
2384            groups,parmlist = G2mv.GroupConstraints(constDict)
2385            G2mv.GenerateConstraints(groups,parmlist,varyList,constDict,fixedList,self.parmDict)
2386        except:
2387            # this really should not happen
2388            print ' *** ERROR - constraints are internally inconsistent ***'
2389            errmsg, warnmsg = G2mv.CheckConstraints(varyList,constDict,fixedList)
2390            print 'Errors',errmsg
2391            if warnmsg: print 'Warnings',warnmsg
2392            raise Exception(' *** CIF creation aborted ***')
2393        # add the constrained values to the parameter dictionary
2394        G2mv.Dict2Map(self.parmDict,varyList)
2395        # and add their uncertainties into the esd dictionary (sigDict)
2396        if covDict.get('covMatrix') is not None:
2397            self.sigDict.update(G2mv.ComputeDepESD(covDict['covMatrix'],covDict['varyList'],self.parmDict))
2398
2399    def loadTree(self):
2400        '''Load the contents of the data tree into a set of dicts
2401        (self.OverallParms, self.Phases and self.Histogram as well as self.powderDict
2402        & self.xtalDict)
2403       
2404        * The childrenless data tree items are overall parameters/controls for the
2405          entire project and are placed in self.OverallParms
2406        * Phase items are placed in self.Phases
2407        * Data items are placed in self.Histogram. The key for these data items
2408          begin with a keyword, such as PWDR, IMG, HKLF,... that identifies the data type.
2409        '''
2410        self.OverallParms = {}
2411        self.powderDict = {}
2412        self.xtalDict = {}
2413        self.Phases = {}
2414        self.Histograms = {}
2415        if self.G2frame.PatternTree.IsEmpty(): return # nothing to do
2416        histType = None       
2417        if self.currentExportType == 'phase':
2418            # if exporting phases load them here
2419            sub = G2gd.GetPatternTreeItemId(self.G2frame,self.G2frame.root,'Phases')
2420            if not sub:
2421                print 'no phases found'
2422                return True
2423            item, cookie = self.G2frame.PatternTree.GetFirstChild(sub)
2424            while item:
2425                phaseName = self.G2frame.PatternTree.GetItemText(item)
2426                self.Phases[phaseName] =  self.G2frame.PatternTree.GetItemPyData(item)
2427                item, cookie = self.G2frame.PatternTree.GetNextChild(sub, cookie)
2428            return
2429        elif self.currentExportType == 'single':
2430            histType = 'HKLF'
2431        elif self.currentExportType == 'powder':
2432            histType = 'PWDR'
2433        elif self.currentExportType == 'image':
2434            histType = 'IMG'
2435
2436        if histType: # Loading just one kind of tree entry
2437            item, cookie = self.G2frame.PatternTree.GetFirstChild(self.G2frame.root)
2438            while item:
2439                name = self.G2frame.PatternTree.GetItemText(item)
2440                if name.startswith(histType):
2441                    if self.Histograms.get(name): # there is already an item with this name
2442                        print('Histogram name '+str(name)+' is repeated. Renaming')
2443                        if name[-1] == '9':
2444                            name = name[:-1] + '10'
2445                        elif name[-1] in '012345678':
2446                            name = name[:-1] + str(int(name[-1])+1)
2447                        else:                           
2448                            name += '-1'
2449                    self.Histograms[name] = {}
2450                    # the main info goes into Data, but the 0th
2451                    # element contains refinement results, carry
2452                    # that over too now.
2453                    self.Histograms[name]['Data'] = self.G2frame.PatternTree.GetItemPyData(item)[1]
2454                    self.Histograms[name][0] = self.G2frame.PatternTree.GetItemPyData(item)[0]
2455                    item2, cookie2 = self.G2frame.PatternTree.GetFirstChild(item)
2456                    while item2: 
2457                        child = self.G2frame.PatternTree.GetItemText(item2)
2458                        self.Histograms[name][child] = self.G2frame.PatternTree.GetItemPyData(item2)
2459                        item2, cookie2 = self.G2frame.PatternTree.GetNextChild(item, cookie2)
2460                item, cookie = self.G2frame.PatternTree.GetNextChild(self.G2frame.root, cookie)
2461            # index powder and single crystal histograms by number
2462            for hist in self.Histograms:
2463                if hist.startswith("PWDR"): 
2464                    d = self.powderDict
2465                elif hist.startswith("HKLF"): 
2466                    d = self.xtalDict
2467                else:
2468                    return                   
2469                i = self.Histograms[hist].get('hId')
2470                if i is None and not d.keys():
2471                    i = 0
2472                elif i is None or i in d.keys():
2473                    i = max(d.keys())+1
2474                d[i] = hist
2475            return
2476        # else standard load: using all interlinked phases and histograms
2477        self.Histograms,self.Phases = self.G2frame.GetUsedHistogramsAndPhasesfromTree()
2478        item, cookie = self.G2frame.PatternTree.GetFirstChild(self.G2frame.root)
2479        while item:
2480            name = self.G2frame.PatternTree.GetItemText(item)
2481            item2, cookie2 = self.G2frame.PatternTree.GetFirstChild(item)
2482            if not item2: 
2483                self.OverallParms[name] = self.G2frame.PatternTree.GetItemPyData(item)
2484            item, cookie = self.G2frame.PatternTree.GetNextChild(self.G2frame.root, cookie)
2485        # index powder and single crystal histograms
2486        for hist in self.Histograms:
2487            i = self.Histograms[hist]['hId']
2488            if hist.startswith("PWDR"): 
2489                self.powderDict[i] = hist
2490            elif hist.startswith("HKLF"): 
2491                self.xtalDict[i] = hist
2492
2493    def dumpTree(self,mode='type'):
2494        '''Print out information on the data tree dicts loaded in loadTree
2495        '''
2496        print '\nOverall'
2497        if mode == 'type':
2498            def Show(arg): return type(arg)
2499        else:
2500            def Show(arg): return arg
2501        for key in self.OverallParms:
2502            print '  ',key,Show(self.OverallParms[key])
2503        print 'Phases'
2504        for key1 in self.Phases:
2505            print '    ',key1,Show(self.Phases[key1])
2506        print 'Histogram'
2507        for key1 in self.Histograms:
2508            print '    ',key1,Show(self.Histograms[key1])
2509            for key2 in self.Histograms[key1]:
2510                print '      ',key2,Show(self.Histograms[key1][key2])
2511
2512    def defaultSaveFile(self):
2513        return os.path.abspath(
2514            os.path.splitext(self.G2frame.GSASprojectfile
2515                             )[0]+self.extension)
2516       
2517    def askSaveFile(self):
2518        '''Ask the user to supply a file name
2519
2520        :returns: a file name (str) or None if Cancel is pressed
2521        '''
2522        defnam = os.path.splitext(
2523            os.path.split(self.G2frame.GSASprojectfile)[1]
2524            )[0]+self.extension
2525        dlg = wx.FileDialog(
2526            self.G2frame, 'Input name for file to write', '.', defnam,
2527            self.longFormatName+' (*'+self.extension+')|*'+self.extension,
2528            wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT|wx.CHANGE_DIR)
2529        dlg.CenterOnParent()
2530        try:
2531            if dlg.ShowModal() == wx.ID_OK:
2532                filename = dlg.GetPath()
2533                # make sure extension is correct
2534                filename = os.path.splitext(filename)[0]+self.extension
2535            else:
2536                filename = None
2537        finally:
2538            dlg.Destroy()
2539        return filename
2540
2541    def askSaveDirectory(self):
2542        '''Ask the user to supply a directory name. Path name is used as the
2543        starting point for the next export path search.
2544
2545        :returns: a directory name (str) or None if Cancel is pressed
2546        '''
2547        if self.G2frame.exportDir:
2548            startdir = self.G2frame.exportDir
2549        elif self.G2frame.GSASprojectfile:
2550            startdir = os.path.split(self.G2frame.GSASprojectfile)[0]
2551        elif self.G2frame.dirname:
2552            startdir = self.G2frame.dirname
2553        else:
2554            startdir = ''
2555        dlg = wx.DirDialog(
2556            self.G2frame, 'Input directory where file(s) will be written', startdir,
2557            wx.DD_DEFAULT_STYLE)
2558        dlg.CenterOnParent()
2559        try:
2560            if dlg.ShowModal() == wx.ID_OK:
2561                filename = dlg.GetPath()
2562                self.G2frame.exportDir = filename
2563            else:
2564                filename = None
2565        finally:
2566            dlg.Destroy()
2567        return filename
2568
2569    # Tools for file writing.
2570    def OpenFile(self,fil=None,mode='w'):
2571        '''Open the output file
2572
2573        :param str fil: The name of the file to open. If None (default)
2574          the name defaults to self.dirname + self.filename.
2575          If an extension is supplied, it is not overridded,
2576          but if not, the default extension is used.
2577        :returns: the file object opened by the routine which is also
2578          saved as self.fp
2579        '''
2580        if not fil:
2581            if not os.path.splitext(self.filename)[1]:
2582                self.filename += self.extension
2583            fil = os.path.join(self.dirname,self.filename)
2584        self.fullpath = os.path.abspath(fil)
2585        self.fp = open(self.fullpath,mode)
2586        return self.fp
2587
2588    def Write(self,line):
2589        '''write a line of output, attaching a line-end character
2590
2591        :param str line: the text to be written.
2592        '''
2593        self.fp.write(line+'\n')
2594    def CloseFile(self,fp=None):
2595        '''Close a file opened in OpenFile
2596
2597        :param file fp: the file object to be closed. If None (default)
2598          file object self.fp is closed.
2599        '''
2600        if fp is None:
2601            fp = self.fp
2602            self.fp = None
2603        fp.close()
2604    # Tools to pull information out of the data arrays
2605    def GetCell(self,phasenam):
2606        """Gets the unit cell parameters and their s.u.'s for a selected phase
2607
2608        :param str phasenam: the name for the selected phase
2609        :returns: `cellList,cellSig` where each is a 7 element list corresponding
2610          to a, b, c, alpha, beta, gamma, volume where `cellList` has the
2611          cell values and `cellSig` has their uncertainties.
2612        """
2613        phasedict = self.Phases[phasenam] # pointer to current phase info
2614        try:
2615            pfx = str(phasedict['pId'])+'::'
2616            A,sigA = G2stIO.cellFill(pfx,phasedict['General']['SGData'],self.parmDict,self.sigDict)
2617            cellSig = G2stIO.getCellEsd(pfx,phasedict['General']['SGData'],A,
2618                self.OverallParms['Covariance'])  # returns 7 vals, includes sigVol
2619            cellList = G2lat.A2cell(A) + (G2lat.calc_V(A),)
2620            return cellList,cellSig
2621        except KeyError:
2622            cell = phasedict['General']['Cell'][1:]
2623            return cell,7*[0]
2624   
2625    def GetAtoms(self,phasenam):
2626        """Gets the atoms associated with a phase. Can be used with standard
2627        or macromolecular phases
2628
2629        :param str phasenam: the name for the selected phase
2630        :returns: a list of items for eac atom where each item is a list containing:
2631          label, typ, mult, xyz, and td, where
2632
2633          * label and typ are the atom label and the scattering factor type (str)
2634          * mult is the site multiplicity (int)
2635          * xyz is contains a list with four pairs of numbers:
2636            x, y, z and fractional occupancy and
2637            their standard uncertainty (or a negative value)
2638          * td is contains a list with either one or six pairs of numbers:
2639            if one number it is U\ :sub:`iso` and with six numbers it is
2640            U\ :sub:`11`, U\ :sub:`22`, U\ :sub:`33`, U\ :sub:`12`, U\ :sub:`13` & U\ :sub:`23`
2641            paired with their standard uncertainty (or a negative value)
2642        """
2643        phasedict = self.Phases[phasenam] # pointer to current phase info           
2644        cx,ct,cs,cia = phasedict['General']['AtomPtrs']
2645        cfrac = cx+3
2646        fpfx = str(phasedict['pId'])+'::Afrac:'       
2647        atomslist = []
2648        for i,at in enumerate(phasedict['Atoms']):
2649            if phasedict['General']['Type'] == 'macromolecular':
2650                label = '%s_%s_%s_%s'%(at[ct-1],at[ct-3],at[ct-4],at[ct-2])
2651            else:
2652                label = at[ct-1]
2653            fval = self.parmDict.get(fpfx+str(i),at[cfrac])
2654            fsig = self.sigDict.get(fpfx+str(i),-0.009)
2655            mult = at[cs+1]
2656            typ = at[ct]
2657            xyz = []
2658            for j,v in enumerate(('x','y','z')):
2659                val = at[cx+j]
2660                pfx = str(phasedict['pId'])+'::dA'+v+':'+str(i)
2661                sig = self.sigDict.get(pfx,-0.000009)
2662                xyz.append((val,sig))
2663            xyz.append((fval,fsig))
2664            td = []
2665            if at[cia] == 'I':
2666                pfx = str(phasedict['pId'])+'::AUiso:'+str(i)
2667                val = self.parmDict.get(pfx,at[cia+1])
2668                sig = self.sigDict.get(pfx,-0.0009)
2669                td.append((val,sig))
2670            else:
2671                for i,var in enumerate(('AU11','AU22','AU33','AU12','AU13','AU23')):
2672                    pfx = str(phasedict['pId'])+'::'+var+':'+str(i)
2673                    val = self.parmDict.get(pfx,at[cia+2+i])
2674                    sig = self.sigDict.get(pfx,-0.0009)
2675                    td.append((val,sig))
2676            atomslist.append((label,typ,mult,xyz,td))
2677        return atomslist
2678######################################################################
2679def ExportPowderList(G2frame):
2680    '''Returns a list of extensions supported by :func:`GSASIIIO:ExportPowder`
2681   
2682    :param wx.Frame G2frame: the GSAS-II main data tree window
2683    '''
2684    extList = []
2685    for obj in G2frame.exporterlist:
2686        if 'powder' in obj.exporttype:
2687            try:
2688                obj.Writer
2689                extList.append(obj.extension)
2690            except AttributeError:
2691                pass
2692    return extList
2693
2694def ExportPowder(G2frame,TreeName,fileroot,extension):
2695    '''Writes a single powder histogram using the Export routines
2696
2697    :param wx.Frame G2frame: the GSAS-II main data tree window
2698    :param str TreeName: the name of the histogram (PWDR ...) in the data tree
2699    :param str fileroot: name for file to be written, extension ignored
2700    :param str extension: extension for file to be written (start with '.'). Must
2701      match a powder export routine that has a Writer object.
2702    '''
2703    filename = os.path.abspath(os.path.splitext(fileroot)[0]+extension)
2704    for obj in G2frame.exporterlist:
2705        if obj.extension == extension and 'powder' in obj.exporttype:
2706            obj.currentExportType = 'powder'
2707            obj.InitExport(None)
2708            obj.loadTree() # load all histograms in tree into dicts
2709            if TreeName not in obj.Histograms:
2710                raise Exception('Histogram not found: '+str(TreeName))
2711            try:
2712                obj.Writer
2713            except AttributeError:
2714                continue
2715            try:
2716                obj.Writer(TreeName,filename)
2717                return
2718            except Exception,err:
2719                print('Export Routine for '+extension+' failed.')
2720                print err
2721    else:
2722        print('No Export routine supports extension '+extension)
2723
2724def ReadCIF(URLorFile):
2725    '''Open a CIF, which may be specified as a file name or as a URL using PyCifRW
2726    (from James Hester).
2727    The open routine gets confused with DOS names that begin with a letter and colon
2728    "C:\dir\" so this routine will try to open the passed name as a file and if that
2729    fails, try it as a URL
2730
2731    :param str URLorFile: string containing a URL or a file name. Code will try first
2732      to open it as a file and then as a URL.
2733
2734    :returns: a PyCifRW CIF object.
2735    '''
2736    import CifFile as cif # PyCifRW from James Hester
2737
2738    # alternate approach:
2739    #import urllib
2740    #ciffile = 'file:'+urllib.pathname2url(filename)
2741   
2742    try:
2743        fp = open(URLorFile,'r')
2744        cf = cif.ReadCif(fp)
2745        fp.close()
2746        return cf
2747    except IOError:
2748        return cif.ReadCif(URLorFile)
2749
2750if __name__ == '__main__':
2751    app = wx.PySimpleApp()
2752    frm = wx.Frame(None) # create a frame
2753    frm.Show(True)
2754    filename = '/tmp/notzip.zip'
2755    filename = '/tmp/all.zip'
2756    #filename = '/tmp/11bmb_7652.zip'
2757   
2758    #selection=None, confirmoverwrite=True, parent=None
2759    #print ExtractFileFromZip(filename, selection='11bmb_7652.fxye',parent=frm)
2760    print ExtractFileFromZip(filename,multipleselect=True)
2761                             #confirmread=False, confirmoverwrite=False)
2762
2763    # choicelist=[ ('a','b','c'),
2764    #              ('test1','test2'),('no choice',)]
2765    # titles = [ 'a, b or c', 'tests', 'No option here']
2766    # dlg = MultipleChoicesDialog(
2767    #     choicelist,titles,
2768    #     parent=frm)
2769    # if dlg.ShowModal() == wx.ID_OK:
2770    #     print 'Got OK'
Note: See TracBrowser for help on using the repository browser.