source: trunk/GSASIIscriptable.py @ 2825

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

remove two prints from GSASIIscriptable.py
fix seq results bug for unused image in strain ring fits

File size: 6.4 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    readerlist = ['G2pwd_fxye','G2pwd_xye','G2pwd_BrukerRAW','G2pwd_csv','G2pwd_FP',
118        'G2pwd_Panalytical','G2pwd_rigaku']
119    if reader not in readerlist:
120        print '**** ERROR: unrecognized reader ',reader
121        return None
122    rdfile,rdpath,descr = imp.find_module(reader)
123    rdclass = imp.load_module(reader,rdfile,rdpath,descr)
124    rd = rdclass.GSAS_ReaderClass()   
125    fl = open(filename,'rb')
126    rdlist = []
127    if rd.ContentsValidator(fl):
128        fl.seek(0)
129        repeat = True
130        rdbuffer = {} # create temporary storage for file reader
131        block = 0
132        while repeat: # loop if the reader asks for another pass on the file
133            block += 1
134            repeat = False
135            rd.objname = ospath.basename(filename)
136            flag = rd.Reader(filename,fl,None,buffer=rdbuffer,blocknum=block,)
137            if flag:
138                rdlist.append(copy.deepcopy(rd)) # save the result before it is written over
139                if rd.repeat:
140                    repeat = True
141        return rdlist
142    print rd.errors
143    return None
144   
145
146def main():
147    'Needs a doc string'
148    arg = sys.argv
149    print arg
150    if len(arg) > 1:
151        GPXfile = arg[1]
152        if not ospath.exists(GPXfile):
153            print 'ERROR - ',GPXfile," doesn't exist!"
154            exit()
155        Project,nameList = LoadDictFromProjFile(GPXfile)
156        SaveDictToProjFile(Project,nameList,'testout.gpx')
157    else:
158        print 'ERROR - missing filename'
159        exit()
160    print "Done"
161         
162if __name__ == '__main__':
163    main()
Note: See TracBrowser for help on using the repository browser.