source: trunk/imports/G2pwd_rigaku.py @ 3136

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

make GSAS-II python 3.6 compliant & preserve python 2.7 use;changes:
do from future import division, print_function for all GSAS-II py sources
all menu items revised to be py 2.7/3.6 compliant
all wx.OPEN --> wx.FD_OPEN in file dialogs
all integer divides (typically for image pixel math) made explicit with ; ambiguous ones made floats as appropriate
all print "stuff" --> print (stuff)
all print >> pFile,'stuff' --> pFile.writeCIFtemplate('stuff')
all read file opens made explicit 'r' or 'rb'
all cPickle imports made for py2.7 or 3.6 as cPickle or _pickle; test for '2' platform.version_tuple[0] for py 2.7
define cPickleload to select load(fp) or load(fp,encoding='latin-1') for loading gpx files; provides cross compatibility between py 2.7/3.6 gpx files
make dict.keys() as explicit list(dict.keys()) as needed (NB: possible source of remaining py3.6 bugs)
make zip(a,b) as explicit list(zip(a,b)) as needed (NB: possible source of remaining py3.6 bugs)
select unichr/chr according test for '2' platform.version_tuple[0] for py 2.7 (G2pwdGUI * G2plot) for special characters
select wg.EVT_GRID_CELL_CHANGE (classic) or wg.EVT_GRID_CELL_CHANGED (phoenix) in grid Bind
maxint --> maxsize; used in random number stuff
raise Exception,"stuff" --> raise Exception("stuff")
wx 'classic' sizer.DeleteWindows?() or 'phoenix' sizer.Clear(True)
wx 'classic' SetToolTipString?(text) or 'phoenix' SetToolTip?(wx.ToolTip?(text)); define SetToolTipString?(self,text) to handle the choice in plots
status.SetFields? --> status.SetStatusText?
'classic' AddSimpleTool? or 'phoenix' self.AddTool? for plot toolbar; Bind different as well
define GetItemPydata? as it doesn't exist in wx 'phoenix'
allow python versions 2.7 & 3.6 to run GSAS-II
Bind override commented out - no logging capability (NB: remove all logging code?)
all import ContentsValidator? open filename & test if valid then close; filepointer removed from Reader
binary importers (mostly images) test for 'byte' type & convert as needed to satisfy py 3.6 str/byte rules

  • Property svn:eol-style set to native
File size: 4.9 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: $
4# $Author: toby $
5# $Revision: $
6# $URL: $
7# $Id: $
8########### SVN repository information ###################
9
10from __future__ import division, print_function
11import os
12import numpy as np
13import GSASIIobj as G2obj
14import GSASIIpath
15GSASIIpath.SetVersionNumber("$Revision: $")
16class Rigaku_ReaderClass(G2obj.ImportPowderData):
17    '''Routines to import powder data from a Rigaku .txt file with an angle and
18    then 1 or 11(!) intensity values on the line. The example file is proceeded
19    with 10 of blank lines, but I have assumed they could be any sort of text.
20    This code should work with an angle and any number of intensity values/line
21    as long as the number is the same on each line. The step size may not change. The
22    number of comment lines can also change, but should not appear to be intensity
23    values (numbers only).
24    '''
25    def __init__(self):
26        super(self.__class__,self).__init__( # fancy way to self-reference
27            extensionlist=('.txt','.TXT'),
28            strictExtension=True,
29            formatName = 'Rigaku .txt exported',
30            longFormatName = 'Rigaku powder data exported as .txt'
31            )
32        self.scriptable = True
33        self.vals = None
34        self.stepsize = None
35        self.skip = 0
36
37    # Validate the contents -- make sure we only have valid lines and set
38    # values we will need for later read.
39    def ContentsValidator(self, filename):
40        self.vals = None
41        self.stepsize = None
42        j = 0
43        prevAngle = None
44        header = True
45        self.skip = -1
46        fp = open(filename,'r')
47        for i,line in enumerate(fp):
48            sline = line.split()
49            vals = len(sline)
50            if header:
51                self.skip += 1
52                if not line.strip(): continue # ignore blank lines
53                err = False
54                for item in sline:
55                    try:
56                        float(item)
57                    except:
58                        err = True
59                        break
60                if err: continue
61                if vals < 1: continue
62                header = False # found first non-header line
63            if vals < 2:
64                print('Too few values for Rigaku .txt file')
65                fp.close()
66                return False
67            if self.vals is None:
68                self.vals = vals
69            elif self.vals != vals:
70                print('Inconsistent numbers values for Rigaku .txt file on line '+str(i+1))
71                fp.close()
72                return False
73            else:
74                j += 1
75            try: 
76                angle = float(sline[0])
77            except:
78                print('Unable to read angle on line '+str(i+1))
79                fp.close()
80                return False
81            if prevAngle is None:
82                prevAngle = angle
83                continue
84            stepsize = (angle-prevAngle)/(vals-1)
85            prevAngle = angle
86            if self.stepsize is None:
87                self.stepsize = stepsize
88            elif abs(self.stepsize - stepsize) > max(abs(stepsize),abs(self.stepsize))/10000. :
89                print('Inconsistent step size for Rigaku .txt file on line '+
90                        str(i+1) + ' here '+ repr(stepsize) + ' prev '+ repr(self.stepsize))
91                fp.close()
92                return False
93            if j > 30:
94                fp.close()
95                return True
96        fp.close()
97        return False
98           
99    def Reader(self,filename, ParentFrame=None, **kwarg):
100        'Read a Rigaku .txt file'
101        x = []
102        y = []
103        w = []
104        fp = open(filename,'r')
105        for i,line in enumerate(fp):
106            if i < self.skip: continue
107            sline = line.split()
108            try: 
109                angle = float(sline[0])
110            except:
111                print('Unable to read angle on line '+str(i+1))
112                self.errors = 'Error reading line: '+str(i+1)
113                return False
114            for j in sline[1:]:
115                x.append(angle)
116                angle += self.stepsize
117                try: 
118                    y.append(float(j))
119                except:
120                    print('Unable to read intensity on line '+str(i+1))
121                    self.errors = 'Error reading line: '+str(i+1)
122                    return False
123                w.append(1.0/max(1.,float(j)))
124        N = len(x)
125        self.powderdata = [
126            np.array(x), # x-axis values
127            np.array(y), # powder pattern intensities
128            np.array(w), # 1/sig(intensity)^2 values (weights)
129            np.zeros(N), # calc. intensities (zero)
130            np.zeros(N), # calc. background (zero)
131            np.zeros(N), # obs-calc profiles
132            ]
133        self.powderentry[0] = filename
134        #self.powderentry[2] = 1 # xye file only has one bank
135        self.idstring = os.path.basename(filename)
136        return True
Note: See TracBrowser for help on using the repository browser.