source: trunk/GSASIIscriptable.py @ 2835

Last change on this file since 2835 was 2835, checked in by vondreele, 5 years ago

add self.scriptable=False to ImportBaseClass?
set it True in various PWDR readers
when selecting points for image calibration, shift key forces selection at cursor
Status bar text changes to reflect this

File size: 6.2 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2017-04-12 15:12:45 -0500 (Wed, 12 Apr 2017) $
4# $Author: vondreele $
5# $Revision: 2777 $
6# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIIscriptable.py $
7# $Id: GSASIIIO.py 2777 2017-04-12 20:12:45Z vondreele $
8########### SVN repository information ###################
9"""
10
11"""
12import os.path as ospath
13import sys
14import cPickle
15import imp
16import copy
17import GSASIIpath
18import GSASIIobj as G2obj
19
20def LoadDictFromProjFile(ProjFile):
21    ''''Read a GSAS-II project file and load items to dictionary
22    :param: str ProjFile: GSAS-II project (name.gpx) full file name
23    :returns: dict Project: representation of gpx file following the GSAS-II tree struture
24        for each item: key = tree name (e.g. 'Controls','Restraints',etc.), data is dict
25        data dict = {'data':item data whch may be list, dict or None,'subitems':subdata (if any)}
26    :returns: list nameList: names of main tree entries & subentries used to reconstruct project file
27    Example for fap.gpx:
28    Project = {                 #NB:dict order is not tree order
29        u'Phases':{'data':None,'fap':{phase dict}},
30        u'PWDR FAP.XRA Bank 1':{'data':[histogram data list],'Comments':comments,'Limits':limits, etc},
31        u'Rigid bodies':{'data': {rigid body dict}},
32        u'Covariance':{'data':{covariance data dict}},
33        u'Controls':{'data':{controls data dict}},
34        u'Notebook':{'data':[notebook list]},
35        u'Restraints':{'data':{restraint data dict}},
36        u'Constraints':{'data':{constraint data dict}}]}
37    nameList = [                #NB: reproduces tree order
38        [u'Notebook',],
39        [u'Controls',],
40        [u'Covariance',],
41        [u'Constraints',],
42        [u'Restraints',],
43        [u'Rigid bodies',],
44        [u'PWDR FAP.XRA Bank 1',
45             u'Comments',
46             u'Limits',
47             u'Background',
48             u'Instrument Parameters',
49             u'Sample Parameters',
50             u'Peak List',
51             u'Index Peak List',
52             u'Unit Cells List',
53             u'Reflection Lists'],
54        [u'Phases',
55             u'fap']]
56    '''
57    if not ospath.exists(ProjFile):
58        print ('\n*** Error attempt to open project file that does not exist:\n   '+
59            str(ProjFile))
60        return
61    file = open(ProjFile,'rb')
62    print 'loading from file: ',ProjFile
63    Project = {}
64    nameList = []
65    try:
66        while True:
67            try:
68                data = cPickle.load(file)
69            except EOFError:
70                break
71            datum = data[0]
72            Project[datum[0]] = {'data':datum[1]}
73            nameList.append([datum[0],])
74            for datus in data[1:]:
75                Project[datum[0]][datus[0]] = datus[1]
76                nameList[-1].append(datus[0])
77        file.close()
78        print('project load successful')
79    except:
80        print("Error reading file "+str(ProjFile)+". This is not a GSAS-II .gpx file")
81        return None
82    return Project,nameList
83   
84def SaveDictToProjFile(Project,nameList,ProjFile):
85    '''Save a GSAS-II project file from dictionary/nameList created by LoadDictFromProjFile
86    param: dict Project: representation of gpx file following the GSAS-II
87        tree struture as described for LoadDictFromProjFile
88    param: list nameList: names of main tree entries & subentries used to reconstruct project file
89    param: str ProjFile: full file name for output project.gpx file (including extension)
90    '''
91    file = open(ProjFile,'wb')
92    print 'save to file: ',ProjFile
93    for name in nameList:
94        data = []
95        item = Project[name[0]]
96        data.append([name[0],item['data']])
97        for item2 in name[1:]:
98            data.append([item2,item[item2]])
99        cPickle.dump(data,file,1)
100    file.close()
101    print('project save successful')
102   
103def ImportPowder(reader,filename):
104    '''Use a reader to import a powder diffraction data file
105    param: str reader: one of 'G2pwd_fxye','G2pwd_xye','G2pwd_BrukerRAW','G2pwd_csv','G2pwd_FP',
106        'G2pwd_Panalytical','G2pwd_rigaku'
107    param: str filename: full name of powder data file; can be "multi-Bank" data
108    returns: list rdlist: list of rrader objects containing powder data, one for each
109        "Bank" of data encountered in file
110        items in reader object of interest are:
111            rd.comments: list of str: comments found on powder file
112            rd.dnames: list of str: data nammes suitable for use in GSASII data tree
113                NB: duplicated in all rd entries in rdlist
114            rd.powderdata: list of numpy arrays: pos,int,wt,zeros,zeros,zeros as needed
115                for a PWDR entry in  GSASII data tree.       
116    '''
117    if not reader.scriptable:
118        print '**** ERROR: not a scriptable reader ',reader
119        return None
120    rdfile,rdpath,descr = imp.find_module(reader)
121    rdclass = imp.load_module(reader,rdfile,rdpath,descr)
122    rd = rdclass.GSAS_ReaderClass()   
123    fl = open(filename,'rb')
124    rdlist = []
125    if rd.ContentsValidator(fl):
126        fl.seek(0)
127        repeat = True
128        rdbuffer = {} # create temporary storage for file reader
129        block = 0
130        while repeat: # loop if the reader asks for another pass on the file
131            block += 1
132            repeat = False
133            rd.objname = ospath.basename(filename)
134            flag = rd.Reader(filename,fl,None,buffer=rdbuffer,blocknum=block,)
135            if flag:
136                rdlist.append(copy.deepcopy(rd)) # save the result before it is written over
137                if rd.repeat:
138                    repeat = True
139        return rdlist
140    print rd.errors
141    return None
142   
143
144def main():
145    'Needs a doc string'
146    arg = sys.argv
147    print arg
148    if len(arg) > 1:
149        GPXfile = arg[1]
150        if not ospath.exists(GPXfile):
151            print 'ERROR - ',GPXfile," doesn't exist!"
152            exit()
153        Project,nameList = LoadDictFromProjFile(GPXfile)
154        SaveDictToProjFile(Project,nameList,'testout.gpx')
155    else:
156        print 'ERROR - missing filename'
157        exit()
158    print "Done"
159         
160if __name__ == '__main__':
161    main()
Note: See TracBrowser for help on using the repository browser.