source: trunk/imports/G2sfact_CIF.py @ 1453

Last change on this file since 1453 was 1453, checked in by vondreele, 9 years ago

get HKLF data type into RefDict?
create a SetDefaultDData routine in GSASII.py
fix copyflags for sc extinction coeff
fix neutron resonant ff for TOF
fix error in making Hessian v-cov matrix - now matches the Jabobian one
put names in the Es, Ep & Eg sc extinction coeff
fix errors in SCExtinction - still problem with derivatives

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 13.6 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2014-08-01 20:19:48 +0000 (Fri, 01 Aug 2014) $
4# $Author: vondreele $
5# $Revision: 1453 $
6# $URL: trunk/imports/G2sfact_CIF.py $
7# $Id: G2sfact_CIF.py 1453 2014-08-01 20:19:48Z vondreele $
8########### SVN repository information ###################
9'''
10*Module G2sfact_CIF: CIF import*
11-----------------------------------
12Read structure factors from a CIF reflection table.
13
14'''
15# routines to read in structure factors from a CIF
16#
17import sys
18import numpy as np
19import os.path
20import GSASIIIO as G2IO
21import GSASIIpath
22GSASIIpath.SetVersionNumber("$Revision: 1453 $")
23import CifFile as cif # PyCifRW from James Hester
24
25class CIFhklReader(G2IO.ImportStructFactor):
26    'Routines to import Phase information from a CIF file'
27    def __init__(self):
28        super(self.__class__,self).__init__( # fancy way to self-reference
29            extensionlist = ('.CIF','.cif','.FCF','.fcf','.HKL','.hkl'),
30            strictExtension = False,
31            formatName = 'CIF',
32            longFormatName = 'CIF format structure factor file (.cif or .hkl)'
33            )
34    # Validate the contents
35    def ContentsValidator(self, filepointer):
36        'Use standard CIF validator'
37        return self.CIFValidator(filepointer)
38
39    def Reader(self, filename, filepointer, ParentFrame=None, **kwarg):
40        '''Read single crystal data from a CIF.
41        If multiple datasets are requested, use self.repeat and buffer caching.
42        '''
43        hklitems = [('_refln_index_h','_refln_index_k','_refln_index_l'),
44                    ('_refln.index_h','_refln.index_k','_refln.index_l')]
45        cellitems = [
46            ('_cell_length_a','_cell_length_b','_cell_length_c',
47             '_cell_angle_alpha','_cell_angle_beta','_cell_angle_gamma',),
48            ('_cell.length_a','_cell.length_b','_cell.length_c',
49             '_cell.angle_alpha','_cell.angle_beta','_cell.angle_gamma',),]
50
51        Fdatanames = ('_refln_f_meas','_refln.f_meas','_refln.f_meas_au',
52                      )
53       
54        F2datanames = ('_refln_f_squared_meas','_refln.f_squared_meas',
55            '_refln_intensity_meas','_refln.intensity_meas',
56                      )
57
58        Idatanames = ('_refln_intensity_meas','_refln.intensity_meas',
59                      ) # not used yet
60
61        Isignames = ('_refln_intensity_meas_sigma','_refln.intensity_meas_sigma',
62                      ) # not used yet
63
64        Fcalcnames = ('_refln_f_calc','_refln.f_calc','_refln.f_calc_au',
65                      )
66       
67        F2calcnames = ('_refln_f_squared_calc','_refln.f_squared_calc',
68                      )
69
70        Fsignames = ('_refln_f_meas_sigma','_refln.f_meas_sigma','_refln.f_meas_sigma_au',
71                    '_refln_f_sigma',
72                      )
73       
74        F2signames = ('_refln_f_squared_meas_sigma','_refln.f_squared_meas_sigma',
75                      '_refln_f_squared_sigma',
76                      '_refln_intensity_meas_sigma','_refln.intensity_meas_sigma',
77                      '_refln.intensity_sigma',)
78
79        phasenames = ('_refln_phase_calc','_refln.phase_calc',
80                      )
81
82
83        SGdataname = ('_symmetry_space_group_name_H-M', '_symmetry.space_group_name_H-M')
84                     
85        phasenamefields = (
86            '_chemical_name_common',
87            '_pd_phase_name',
88            '_chemical_formula_sum'
89            )
90        rdbuffer = kwarg.get('buffer')
91        cf = None
92        try:
93            if self.repeat and rdbuffer is not None:
94                cf = rdbuffer.get('lastcif')
95                print 'Reusing previously parsed CIF'
96            if cf is None:
97                self.ShowBusy() # this can take a while
98                try:
99                    cf = G2IO.ReadCIF(filename)
100                except Exception as detail:
101                    self.errors = "Parse or reading of file failed in pyCifRW; check syntax of file in enCIFer or CheckCIF"
102                    return False
103                finally:
104                    self.DoneBusy()
105            # scan blocks for reflections
106            self.errors = 'Error during scan of blocks for datasets'
107            blklist = []
108            for blk in cf.keys(): # scan for reflections, F or F2 values and cell lengths.
109                # Ignore blocks that do not have structure factors and a cell
110                blkkeys = [k.lower() for k in cf[blk].keys()]
111                gotFo = False
112                gotFo2 = False
113                for i in range(2):
114                    if hklitems[i][0] in blkkeys and hklitems[i][1] in blkkeys and hklitems[i][2] in blkkeys:
115                        dnIndex = i
116                        break
117                else:
118                    break # no reflections
119                for dn in Fdatanames: 
120                    if dn in blkkeys:
121                        blklist.append(blk)
122                        gotFo = True
123                        break
124                if gotFo: break
125                for dn in F2datanames: 
126                    if dn in blkkeys:
127                        blklist.append(blk)
128                        break
129                else:
130                    break
131            if not blklist:
132                selblk = None # no block to choose
133            elif len(blklist) == 1: # only one choice
134                selblk = 0
135            else:                       # choose from options
136                choice = []
137                for blknm in blklist:
138                    choice.append('')
139                    # accumulate some info about this phase
140                    choice[-1] += blknm + ': '
141                    for i in phasenamefields: # get a name for the phase
142                        name = cf[blknm].get(i)
143                        if name is None or name == '?' or name == '.':
144                            continue
145                        else:
146                            choice[-1] += name.strip()[:20] + ', '
147                            break
148                    s = ''
149                    fmt = "%.2f,"
150                    for i,key in enumerate(cellitems[dnIndex]):
151                        if i == 3: fmt = "%.f,"
152                        if i == 5: fmt = "%.f"
153                        val = cf[blknm].get(key)
154                        if val is None: break
155                        s += fmt % cif.get_number_with_esd(val)[0]
156                    if s: choice[-1] += ', cell: ' + s
157                    for dn in SGdataname:
158                        sg = cf[blknm].get(dn)
159                        if sg: 
160                            choice[-1] += ', (' + sg.strip() + ')'
161                            break
162                choice.append('Import all of the above')
163                if self.repeat: # we were called to repeat the read
164                    selblk = self.repeatcount
165                    self.repeatcount += 1
166                    if self.repeatcount >= len(blklist): self.repeat = False
167                else:
168                    selblk = self.BlockSelector(
169                        choice,
170                        ParentFrame=ParentFrame,
171                        title='Select a dataset from one the CIF data_ blocks below',
172                        size=(600,100),
173                        header='Dataset Selector')
174            self.errors = 'Error during reading of selected block'
175            if selblk is None:
176                return False # no block selected or available
177            if selblk >= len(blklist): # all blocks selected
178                selblk = 0
179                self.repeat = True
180                if rdbuffer is not None:
181                    rdbuffer['lastcif'] = cf # save the parsed cif for the next loop
182                self.repeatcount = 1
183            blknm = blklist[selblk]
184            blk = cf[blklist[selblk]]
185            self.objname = os.path.basename(filename)+':'+str(blknm)
186            self.errors = 'Error during reading of reflections'
187            # read in reflections
188            try:
189                refloop = blk.GetLoop(hklitems[0][0])
190                dnIndex = 0
191            except KeyError:
192                try:
193                    refloop = blk.GetLoop(hklitems[1][0])
194                    dnIndex = 1
195                except KeyError:
196                    self.errors += "\nUnexpected: '_refln[-.]index_h not found!"
197                    return False
198            itemkeys = {}
199            # prepare an index to the CIF reflection loop
200            for i,key in enumerate(refloop.keys()):
201                itemkeys[key.lower()] = i
202               
203            # scan for data names:
204            F2dn = None
205            Fdn = None
206            F2cdn = None
207            Fcdn = None
208            F2sdn = None
209            Fsdn = None
210            Phdn = None
211            FcalcPresent = False
212            for dn in F2datanames:
213                if dn in itemkeys:
214                    F2dn = dn
215                    for dn in F2calcnames:
216                        if dn in itemkeys:
217                            F2cdn = dn
218                            FcalcPresent = True
219                            break
220                    for dn in F2signames:
221                        if dn in itemkeys:
222                            F2sdn = dn
223                            break
224                    break
225            else:
226                for dn in Fdatanames:
227                    if dn in itemkeys:
228                        Fdn = dn
229                        for dn in Fcalcnames:
230                            if dn in itemkeys:
231                                Fcdn = dn
232                                FcalcPresent = True
233                                break
234                        for dn in Fsignames:
235                            if dn in itemkeys:
236                                Fsdn = dn
237                                break
238                        break
239                else:
240                    msg = "\nno F or F2 loop value found in file\n"
241                    msg += "A CIF reflection file needs to have at least one of\n"
242                    for dn in F2datanames+Fdatanames:
243                        msg += dn + ', '
244                    self.errors += msg                       
245                    return False
246            for dn in phasenames:
247                if dn in itemkeys:
248                    Phdn = dn
249                    break
250               
251            # loop over all reflections
252            for item in refloop:
253                F2c = 0.0
254                sigF2 = 0.0
255                HKL = []
256                try:
257                    for i in hklitems[dnIndex]: # '_refln[._]index_[hkl]'
258                        num = itemkeys.get(i)
259                        try:
260                            HKL.append(int(item[num]))
261                        except:
262                            HKL.append('.')
263                    #h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,Ext
264                    ref = HKL+[0,0,0,0,0, 0,0,0,0,0, 0] 
265                    if F2dn:
266                        F2 = item[itemkeys[F2dn]]
267                        if '(' in F2:
268                            F2, sigF2 = cif.get_number_with_esd(F2)
269                            F2 = float(F2)
270                            sigF2 = float(sigF2)
271                        elif F2sdn:
272                            F2 = float(F2)
273                            sigF2 = float(item[itemkeys[F2sdn]])
274                        else:
275                            F2 = float(F2)
276                        try:
277                            if F2cdn:
278                                F2c = float(item[itemkeys[F2cdn]])
279                        except:
280                            pass
281                    else:
282                        F = item[itemkeys[Fdn]]
283                        if '(' in F:
284                            F, sig = cif.get_number_with_esd(F)
285                        elif Fsdn:
286                            F = float(F)
287                            sig = float(item[itemkeys[Fsdn]])
288                        else:
289                            F = float(F)
290                            sig = 0.0
291                        F2 = F**2
292                        sigF2 = 2.0*F*sig
293                        try:
294                            if Fcdn:
295                                Fc = float(item[itemkeys[Fcdn]])
296                                F2c = Fc*Fc
297                        except:
298                            pass
299                               
300                    ref[8] = F2
301                    ref[5] = F2
302                    ref[6] = sigF2
303                    ref[9] = F2c
304                    ref[7] = F2c
305                    try:
306                        if Phdn:
307                            ref[10] = float(item[itemkeys[Phdn]])
308                    except:
309                        pass
310                except:
311                    continue # skip over incompletely parsed reflections
312                self.RefDict['RefList'].append(ref)
313                self.RefDict['FF'].append({})
314            self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
315            self.errors = 'Error during reading of dataset parameters'
316            if blk.get('_diffrn_radiation_probe'):
317                if blk['_diffrn_radiation_probe'] == 'neutron':
318                    Type = 'SNC'
319            elif blk.get('_diffrn_radiation.probe'):
320                if blk['_diffrn_radiation.probe'] == 'neutron':
321                    Type = 'SNC'
322            else:
323                type = 'SXC'
324            self.RefDict['Type'] = Type
325            if blk.get('_diffrn_radiation_wavelength'):
326                wave = float(blk['_diffrn_radiation_wavelength'])
327            elif blk.get('_diffrn_radiation.wavelength'):
328                wave = float(blk['_diffrn_radiation.wavelength'])
329            else:
330                wave = 1.5418
331            self.UpdateParameters(Type=Type,Wave=wave) # histogram type
332            return True
333        except Exception as detail:
334            self.errors += '\n  '+str(detail)
335            print self.formatName+' read error:'+str(detail) # for testing
336            import traceback
337            traceback.print_exc(file=sys.stdout)
338        return False
Note: See TracBrowser for help on using the repository browser.