source: trunk/GSASIIscriptable.py @ 2836

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

fixes to scripts & fxye importer

File size: 6.1 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: a scriptable reader
106    param: str filename: full name of powder data file; can be "multi-Bank" data
107    returns: list rdlist: list of rrader objects containing powder data, one for each
108        "Bank" of data encountered in file
109        items in reader object of interest are:
110            rd.comments: list of str: comments found on powder file
111            rd.dnames: list of str: data nammes suitable for use in GSASII data tree
112                NB: duplicated in all rd entries in rdlist
113            rd.powderdata: list of numpy arrays: pos,int,wt,zeros,zeros,zeros as needed
114                for a PWDR entry in  GSASII data tree.       
115    '''
116    rdfile,rdpath,descr = imp.find_module(reader)
117    rdclass = imp.load_module(reader,rdfile,rdpath,descr)
118    rd = rdclass.GSAS_ReaderClass()   
119    if not rd.scriptable:
120        print '**** ERROR: ',reader,' is not a scriptable reader'
121        return None
122    fl = open(filename,'rb')
123    rdlist = []
124    if rd.ContentsValidator(fl):
125        fl.seek(0)
126        repeat = True
127        rdbuffer = {} # create temporary storage for file reader
128        block = 0
129        while repeat: # loop if the reader asks for another pass on the file
130            block += 1
131            repeat = False
132            rd.objname = ospath.basename(filename)
133            flag = rd.Reader(filename,fl,None,buffer=rdbuffer,blocknum=block,)
134            if flag:
135                rdlist.append(copy.deepcopy(rd)) # save the result before it is written over
136                if rd.repeat:
137                    repeat = True
138        return rdlist
139    print rd.errors
140    return None
141   
142
143def main():
144    'Needs a doc string'
145    arg = sys.argv
146    print arg
147    if len(arg) > 1:
148        GPXfile = arg[1]
149        if not ospath.exists(GPXfile):
150            print 'ERROR - ',GPXfile," doesn't exist!"
151            exit()
152        Project,nameList = LoadDictFromProjFile(GPXfile)
153        SaveDictToProjFile(Project,nameList,'testout.gpx')
154    else:
155        print 'ERROR - missing filename'
156        exit()
157    print "Done"
158         
159if __name__ == '__main__':
160    main()
Note: See TracBrowser for help on using the repository browser.