Changeset 2738


Ignore:
Timestamp:
Mar 4, 2017 8:34:05 AM (6 years ago)
Author:
vondreele
Message:

removed all "except Exception as detail" blocks from importers & G2export_CIF. Were in the way of effective debugging of import codes.

Location:
trunk
Files:
15 edited

Legend:

Unmodified
Added
Removed
  • trunk/exports/G2export_CIF.py

    r2733 r2738  
    18941894            #=== multiblock: multiple phases and/or histograms ====================
    18951895            nsteps = 1 + len(self.Phases) + len(self.powderDict) + len(self.xtalDict)
    1896             try:
    1897                 dlg = wx.ProgressDialog('CIF progress','starting',nsteps,parent=self.G2frame)
     1896            dlg = wx.ProgressDialog('CIF progress','starting',nsteps,parent=self.G2frame)
    18981897#                Size = dlg.GetSize()
    18991898#                Size = (int(Size[0]*3),Size[1]) # increase size along x
    19001899#                dlg.SetSize(Size)
    1901                 dlg.CenterOnParent()
    1902 
    1903                 # publication info
    1904                 step = 1
    1905                 dlg.Update(step,"Exporting overall section")
    1906                 WriteCIFitem('\ndata_'+self.CIFname+'_publ')
    1907                 WriteAudit()
    1908                 WriteCIFitem('_pd_block_id',
    1909                              str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
    1910                              str(self.shortauthorname) + "|Overall")
    1911                 writeCIFtemplate(self.OverallParms['Controls'],'publ') #insert the publication template
    1912                 # ``template_publ.cif`` or a modified version
    1913                 # overall info
    1914                 WriteCIFitem('data_'+str(self.CIFname)+'_overall')
    1915                 WriteOverall()
    1916                 #============================================================
    1917                 WriteCIFitem('# POINTERS TO PHASE AND HISTOGRAM BLOCKS')
    1918                 datablockidDict = {} # save block names here -- N.B. check for conflicts between phase & hist names (unlikely!)
    1919                 # loop over phase blocks
    1920                 if len(self.Phases) > 1:
    1921                     loopprefix = ''
    1922                     WriteCIFitem('loop_   _pd_phase_block_id')
    1923                 else:
    1924                     loopprefix = '_pd_phase_block_id'
    1925 
    1926                 for phasenam in sorted(self.Phases.keys()):
    1927                     i = self.Phases[phasenam]['pId']
    1928                     datablockidDict[phasenam] = (str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
    1929                                  'phase_'+ str(i) + '|' + str(self.shortauthorname))
    1930                     WriteCIFitem(loopprefix,datablockidDict[phasenam])
    1931                 # loop over data blocks
    1932                 if len(self.powderDict) + len(self.xtalDict) > 1:
    1933                     loopprefix = ''
    1934                     WriteCIFitem('loop_   _pd_block_diffractogram_id')
    1935                 else:
    1936                     loopprefix = '_pd_block_diffractogram_id'
    1937                 for i in sorted(self.powderDict.keys()):
    1938                     hist = self.powderDict[i]
    1939                     histblk = self.Histograms[hist]
    1940                     instnam = histblk["Sample Parameters"]['InstrName']
    1941                     instnam = instnam.replace(' ','')
    1942                     j = histblk['hId']
    1943                     datablockidDict[hist] = (str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
    1944                                              str(self.shortauthorname) + "|" +
    1945                                              instnam + "_hist_"+str(j))
    1946                     WriteCIFitem(loopprefix,datablockidDict[hist])
    1947                 for i in sorted(self.xtalDict.keys()):
    1948                     hist = self.xtalDict[i]
    1949                     histblk = self.Histograms[hist]
    1950                     instnam = histblk["Instrument Parameters"][0]['InstrName']
    1951                     instnam = instnam.replace(' ','')
    1952                     i = histblk['hId']
    1953                     datablockidDict[hist] = (str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
    1954                                              str(self.shortauthorname) + "|" +
    1955                                              instnam + "_hist_"+str(i))
    1956                     WriteCIFitem(loopprefix,datablockidDict[hist])
    1957                 #============================================================
    1958                 # loop over phases, exporting them
    1959                 phasebyhistDict = {} # create a cross-reference to phases by histogram
    1960                 for j,phasenam in enumerate(sorted(self.Phases.keys())):
     1900            dlg.CenterOnParent()
     1901
     1902            # publication info
     1903            step = 1
     1904            dlg.Update(step,"Exporting overall section")
     1905            WriteCIFitem('\ndata_'+self.CIFname+'_publ')
     1906            WriteAudit()
     1907            WriteCIFitem('_pd_block_id',
     1908                         str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
     1909                         str(self.shortauthorname) + "|Overall")
     1910            writeCIFtemplate(self.OverallParms['Controls'],'publ') #insert the publication template
     1911            # ``template_publ.cif`` or a modified version
     1912            # overall info
     1913            WriteCIFitem('data_'+str(self.CIFname)+'_overall')
     1914            WriteOverall()
     1915            #============================================================
     1916            WriteCIFitem('# POINTERS TO PHASE AND HISTOGRAM BLOCKS')
     1917            datablockidDict = {} # save block names here -- N.B. check for conflicts between phase & hist names (unlikely!)
     1918            # loop over phase blocks
     1919            if len(self.Phases) > 1:
     1920                loopprefix = ''
     1921                WriteCIFitem('loop_   _pd_phase_block_id')
     1922            else:
     1923                loopprefix = '_pd_phase_block_id'
     1924
     1925            for phasenam in sorted(self.Phases.keys()):
     1926                i = self.Phases[phasenam]['pId']
     1927                datablockidDict[phasenam] = (str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
     1928                             'phase_'+ str(i) + '|' + str(self.shortauthorname))
     1929                WriteCIFitem(loopprefix,datablockidDict[phasenam])
     1930            # loop over data blocks
     1931            if len(self.powderDict) + len(self.xtalDict) > 1:
     1932                loopprefix = ''
     1933                WriteCIFitem('loop_   _pd_block_diffractogram_id')
     1934            else:
     1935                loopprefix = '_pd_block_diffractogram_id'
     1936            for i in sorted(self.powderDict.keys()):
     1937                hist = self.powderDict[i]
     1938                histblk = self.Histograms[hist]
     1939                instnam = histblk["Sample Parameters"]['InstrName']
     1940                instnam = instnam.replace(' ','')
     1941                j = histblk['hId']
     1942                datablockidDict[hist] = (str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
     1943                                         str(self.shortauthorname) + "|" +
     1944                                         instnam + "_hist_"+str(j))
     1945                WriteCIFitem(loopprefix,datablockidDict[hist])
     1946            for i in sorted(self.xtalDict.keys()):
     1947                hist = self.xtalDict[i]
     1948                histblk = self.Histograms[hist]
     1949                instnam = histblk["Instrument Parameters"][0]['InstrName']
     1950                instnam = instnam.replace(' ','')
     1951                i = histblk['hId']
     1952                datablockidDict[hist] = (str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
     1953                                         str(self.shortauthorname) + "|" +
     1954                                         instnam + "_hist_"+str(i))
     1955                WriteCIFitem(loopprefix,datablockidDict[hist])
     1956            #============================================================
     1957            # loop over phases, exporting them
     1958            phasebyhistDict = {} # create a cross-reference to phases by histogram
     1959            for j,phasenam in enumerate(sorted(self.Phases.keys())):
     1960                step += 1
     1961                dlg.Update(step,"Exporting phase "+phasenam+' (#'+str(j+1)+')')
     1962                i = self.Phases[phasenam]['pId']
     1963                WriteCIFitem('\ndata_'+self.CIFname+"_phase_"+str(i))
     1964                WriteCIFitem('# Information for phase '+str(i))
     1965                WriteCIFitem('_pd_block_id',datablockidDict[phasenam])
     1966                # report the phase
     1967                writeCIFtemplate(self.Phases[phasenam]['General'],'phase',phasenam) # write phase template
     1968                WritePhaseInfo(phasenam)
     1969                # preferred orientation
     1970                if self.ifPWDR:
     1971                    SH = FormatSH(phasenam)
     1972                    MD = FormatHAPpo(phasenam)
     1973                    if SH and MD:
     1974                        WriteCIFitem('_pd_proc_ls_pref_orient_corr', SH + '\n' + MD)
     1975                    elif SH or MD:
     1976                        WriteCIFitem('_pd_proc_ls_pref_orient_corr', SH + MD)
     1977                    else:
     1978                        WriteCIFitem('_pd_proc_ls_pref_orient_corr', 'none')
     1979                # report sample profile terms
     1980                PP = FormatPhaseProfile(phasenam)
     1981                if PP:
     1982                    WriteCIFitem('_pd_proc_ls_profile_function',PP)
     1983
     1984            #============================================================
     1985            # loop over histograms, exporting them
     1986            for i in sorted(self.powderDict.keys()):
     1987                hist = self.powderDict[i]
     1988                histblk = self.Histograms[hist]
     1989                if hist.startswith("PWDR"):
    19611990                    step += 1
    1962                     dlg.Update(step,"Exporting phase "+phasenam+' (#'+str(j+1)+')')
    1963                     i = self.Phases[phasenam]['pId']
    1964                     WriteCIFitem('\ndata_'+self.CIFname+"_phase_"+str(i))
    1965                     WriteCIFitem('# Information for phase '+str(i))
    1966                     WriteCIFitem('_pd_block_id',datablockidDict[phasenam])
    1967                     # report the phase
    1968                     writeCIFtemplate(self.Phases[phasenam]['General'],'phase',phasenam) # write phase template
    1969                     WritePhaseInfo(phasenam)
    1970                     # preferred orientation
    1971                     if self.ifPWDR:
    1972                         SH = FormatSH(phasenam)
    1973                         MD = FormatHAPpo(phasenam)
    1974                         if SH and MD:
    1975                             WriteCIFitem('_pd_proc_ls_pref_orient_corr', SH + '\n' + MD)
    1976                         elif SH or MD:
    1977                             WriteCIFitem('_pd_proc_ls_pref_orient_corr', SH + MD)
    1978                         else:
    1979                             WriteCIFitem('_pd_proc_ls_pref_orient_corr', 'none')
    1980                     # report sample profile terms
    1981                     PP = FormatPhaseProfile(phasenam)
    1982                     if PP:
    1983                         WriteCIFitem('_pd_proc_ls_profile_function',PP)
    1984 
    1985                 #============================================================
    1986                 # loop over histograms, exporting them
    1987                 for i in sorted(self.powderDict.keys()):
    1988                     hist = self.powderDict[i]
    1989                     histblk = self.Histograms[hist]
    1990                     if hist.startswith("PWDR"):
    1991                         step += 1
    1992                         dlg.Update(step,"Exporting "+hist.strip())
    1993                         WriteCIFitem('\ndata_'+self.CIFname+"_pwd_"+str(i))
    1994                         #instnam = histblk["Sample Parameters"]['InstrName']
    1995                         # report instrumental profile terms
    1996                         WriteCIFitem('_pd_proc_ls_profile_function',
    1997                             FormatInstProfile(histblk["Instrument Parameters"],histblk['hId']))
    1998                         WriteCIFitem('# Information for histogram '+str(i)+': '+hist)
    1999                         WriteCIFitem('_pd_block_id',datablockidDict[hist])
    2000                         histprm = self.Histograms[hist]["Sample Parameters"]
    2001                         writeCIFtemplate(histprm,'powder',histprm['InstrName']) # powder template
    2002                         WritePowderData(hist)
    2003                 for i in sorted(self.xtalDict.keys()):
    2004                     hist = self.xtalDict[i]
    2005                     histblk = self.Histograms[hist]
    2006                     if hist.startswith("HKLF"):
    2007                         step += 1
    2008                         dlg.Update(step,"Exporting "+hist.strip())
    2009                         WriteCIFitem('\ndata_'+self.CIFname+"_sx_"+str(i))
    2010                         #instnam = histblk["Instrument Parameters"][0]['InstrName']
    2011                         WriteCIFitem('# Information for histogram '+str(i)+': '+hist)
    2012                         WriteCIFitem('_pd_block_id',datablockidDict[hist])
    2013                         histprm = self.Histograms[hist]["Instrument Parameters"][0]
    2014                         writeCIFtemplate(histprm,'single',histprm['InstrName']) # single crystal template
    2015                         WriteSingleXtalData(hist)
    2016 
    2017             except Exception:
    2018                 import traceback
    2019                 print(traceback.format_exc())
    2020                 self.G2frame.ErrorDialog('Exception',
    2021                                          'Error occurred in CIF creation. '+
    2022                                          'See full error message in console output ')
    2023             finally:
    2024                 dlg.Destroy()
     1991                    dlg.Update(step,"Exporting "+hist.strip())
     1992                    WriteCIFitem('\ndata_'+self.CIFname+"_pwd_"+str(i))
     1993                    #instnam = histblk["Sample Parameters"]['InstrName']
     1994                    # report instrumental profile terms
     1995                    WriteCIFitem('_pd_proc_ls_profile_function',
     1996                        FormatInstProfile(histblk["Instrument Parameters"],histblk['hId']))
     1997                    WriteCIFitem('# Information for histogram '+str(i)+': '+hist)
     1998                    WriteCIFitem('_pd_block_id',datablockidDict[hist])
     1999                    histprm = self.Histograms[hist]["Sample Parameters"]
     2000                    writeCIFtemplate(histprm,'powder',histprm['InstrName']) # powder template
     2001                    WritePowderData(hist)
     2002            for i in sorted(self.xtalDict.keys()):
     2003                hist = self.xtalDict[i]
     2004                histblk = self.Histograms[hist]
     2005                if hist.startswith("HKLF"):
     2006                    step += 1
     2007                    dlg.Update(step,"Exporting "+hist.strip())
     2008                    WriteCIFitem('\ndata_'+self.CIFname+"_sx_"+str(i))
     2009                    #instnam = histblk["Instrument Parameters"][0]['InstrName']
     2010                    WriteCIFitem('# Information for histogram '+str(i)+': '+hist)
     2011                    WriteCIFitem('_pd_block_id',datablockidDict[hist])
     2012                    histprm = self.Histograms[hist]["Instrument Parameters"][0]
     2013                    writeCIFtemplate(histprm,'single',histprm['InstrName']) # single crystal template
     2014                    WriteSingleXtalData(hist)
     2015
     2016            dlg.Destroy()
    20252017
    20262018        WriteCIFitem('#--' + 15*'eof--' + '#')
     
    27282720        dlg.Destroy()
    27292721        if ret == wx.ID_OK:
    2730             try:
    2731                 cf = G2IO.ReadCIF(fil)
    2732                 if len(cf.keys()) == 0:
    2733                     raise Exception,"No CIF data_ blocks found"
    2734                 if len(cf.keys()) != 1:
    2735                     raise Exception, 'Error, CIF Template has more than one block: '+fil
    2736                 self.dict["CIF_template"] = fil
    2737             except Exception as err:
    2738                 print('\nError reading CIF: '+fil)
    2739                 dlg = wx.MessageDialog(self.cifdefs,
    2740                                    'Error reading CIF '+fil,
    2741                                    'Error in CIF file',
    2742                                    wx.OK)
    2743                 dlg.ShowModal()
    2744                 dlg.Destroy()
    2745                 print(err.message)
    2746                 return
     2722            cf = G2IO.ReadCIF(fil)
     2723            if len(cf.keys()) == 0:
     2724                raise Exception,"No CIF data_ blocks found"
     2725            if len(cf.keys()) != 1:
     2726                raise Exception, 'Error, CIF Template has more than one block: '+fil
     2727            self.dict["CIF_template"] = fil
    27472728            self.repaint() #EditCIFDefaults()
    27482729
  • trunk/imports/G2phase.py

    r2539 r2738  
    5858    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
    5959        'Read a PDF file using :meth:`ReadPDBPhase`'
    60         try:
    61             self.Phase = self.ReadPDBPhase(filename, ParentFrame)
    62             return True
    63         except Exception as detail:
    64             self.errors += '\n  '+str(detail)
    65             print 'PDB read error:',detail # for testing
    66             traceback.print_exc(file=sys.stdout)
    67             return False
     60        self.Phase = self.ReadPDBPhase(filename, ParentFrame)
     61        return True
    6862       
    6963    def ReadPDBPhase(self,filename,parent=None):
     
    186180    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
    187181        'Read a phase from a GSAS .EXP file using :meth:`ReadEXPPhase`'
    188         try:
    189             self.Phase = self.ReadEXPPhase(ParentFrame, filepointer)
    190             return True
    191         except Exception as detail:
    192             self.errors += '\n  '+str(detail)
    193             print 'GSAS .EXP read error:',detail # for testing
    194             traceback.print_exc(file=sys.stdout)
    195             return False
     182        self.Phase = self.ReadEXPPhase(ParentFrame, filepointer)
     183        return True
    196184
    197185    def ReadEXPPhase(self, G2frame,filepointer):
     
    384372    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
    385373        'Read a m50 file using :meth:`ReadJANAPhase`'
    386         try:
    387             self.Phase = self.ReadJANAPhase(filename, ParentFrame)
    388             return True
    389         except Exception as detail:
    390             self.errors += '\n  '+str(detail)
    391             print 'JANA read error:',detail # for testing
    392             traceback.print_exc(file=sys.stdout)
    393             return False
     374        self.Phase = self.ReadJANAPhase(filename, ParentFrame)
     375        return True
    394376       
    395377    def ReadJANAPhase(self,filename,parent=None):
  • trunk/imports/G2phase_CIF.py

    r2470 r2738  
    5656            '_cell_length_a','_cell_length_b','_cell_length_c',
    5757            '_cell_angle_alpha','_cell_angle_beta','_cell_angle_gamma',)
    58         cellwaveitems = (
    59             '_cell_wave_vector_seq_id',
    60             '_cell_wave_vector_x','_cell_wave_vector_y','_cell_wave_vector_z')
     58#        cellwaveitems = (
     59#            '_cell_wave_vector_seq_id',
     60#            '_cell_wave_vector_x','_cell_wave_vector_y','_cell_wave_vector_z')
    6161        reqitems = (
    6262             '_atom_site_fract_x',
     
    6969            '_chemical_formula_sum'
    7070            )
    71         try:
    72             self.ShowBusy() # this can take a while
    73             try:
    74                 cf = G2IO.ReadCIF(filename)
    75             except Exception as detail:
    76                 self.errors = "Parse or reading of file failed in pyCifRW; check syntax of file in enCIFer or CheckCIF"
    77                 return False
    78             finally:
    79                 self.DoneBusy()
    80             # scan blocks for structural info
    81             self.errors = 'Error during scan of blocks for datasets'
    82             str_blklist = []
    83             for blk in cf.keys():
    84                 for r in reqitems+cellitems:
    85                     if r not in cf[blk].keys():
     71        self.ShowBusy() # this can take a while
     72        cf = G2IO.ReadCIF(filename)
     73        self.DoneBusy()
     74        # scan blocks for structural info
     75        self.errors = 'Error during scan of blocks for datasets'
     76        str_blklist = []
     77        for blk in cf.keys():
     78            for r in reqitems+cellitems:
     79                if r not in cf[blk].keys():
     80                    break
     81            else:
     82                str_blklist.append(blk)
     83        if not str_blklist:
     84            selblk = None # no block to choose
     85        elif len(str_blklist) == 1: # only one choice
     86            selblk = 0
     87        else:                       # choose from options
     88            choice = []
     89            for blknm in str_blklist:
     90                choice.append('')
     91                # accumumlate some info about this phase
     92                choice[-1] += blknm + ': '
     93                for i in phasenamefields: # get a name for the phase
     94                    name = cf[blknm].get(i).strip()
     95                    if name is None or name == '?' or name == '.':
     96                        continue
     97                    else:
     98                        choice[-1] += name.strip()[:20] + ', '
    8699                        break
    87                 else:
    88                     str_blklist.append(blk)
    89             if not str_blklist:
    90                 selblk = None # no block to choose
    91             elif len(str_blklist) == 1: # only one choice
    92                 selblk = 0
    93             else:                       # choose from options
    94                 choice = []
    95                 for blknm in str_blklist:
    96                     choice.append('')
    97                     # accumumlate some info about this phase
    98                     choice[-1] += blknm + ': '
    99                     for i in phasenamefields: # get a name for the phase
    100                         name = cf[blknm].get(i).strip()
    101                         if name is None or name == '?' or name == '.':
    102                             continue
    103                         else:
    104                             choice[-1] += name.strip()[:20] + ', '
    105                             break
    106                     na = len(cf[blknm].get("_atom_site_fract_x"))
    107                     if na == 1:
    108                         choice[-1] += '1 atom'
     100                na = len(cf[blknm].get("_atom_site_fract_x"))
     101                if na == 1:
     102                    choice[-1] += '1 atom'
     103                else:
     104                    choice[-1] += ('%d' % nd) + ' atoms'
     105                choice[-1] += ', cell: '
     106                fmt = "%.2f,"
     107                for i,key in enumerate(cellitems):
     108                    if i == 3: fmt = "%.f,"
     109                    if i == 5: fmt = "%.f"
     110                    choice[-1] += fmt % cif.get_number_with_esd(
     111                        cf[blknm].get(key))[0]
     112                sg = cf[blknm].get("_symmetry_space_group_name_H-M",'')
     113                if not sg: sg = cf[blknm].get("_space_group_name_H-M_alt",'')
     114                if sg: choice[-1] += ', (' + sg.strip() + ')'
     115            selblk = self.PhaseSelector(
     116                choice,
     117                ParentFrame=ParentFrame,
     118                title= 'Select a phase from one the CIF data_ blocks below',
     119                size=(600,100)
     120                )
     121        self.errors = 'Error during reading of selected block'
     122        if selblk is None:
     123            returnstat = False # no block selected or available
     124        else:
     125            blknm = str_blklist[selblk]
     126            blk = cf[str_blklist[selblk]]
     127            E = True
     128            Super = False
     129            SpGrp = blk.get("_symmetry_space_group_name_H-M",'')
     130            if not SpGrp:
     131                SpGrp = blk.get("_space_group_name_H-M_alt",'')
     132            if not SpGrp:
     133                sspgrp = blk.get("_space_group_ssg_name",'').split('(')
     134                SpGrp = sspgrp[0]
     135                SuperSg = '('+sspgrp[1].replace('\\','')
     136                Super = True
     137                SuperVec = [[0,0,.1],False,4]
     138            # try normalizing the space group, to see if we can pick the space group out of a table
     139            SpGrpNorm = G2spc.StandardizeSpcName(SpGrp)
     140            if SpGrpNorm:
     141                E,SGData = G2spc.SpcGroup(SpGrpNorm)
     142            # nope, try the space group "out of the Box"
     143            if E and SpGrp:
     144                E,SGData = G2spc.SpcGroup(SpGrp)
     145            if E:
     146                if not SpGrp:
     147                    self.warnings += 'No space group name was found in the CIF.'
     148                    self.warnings += '\nThe space group has been set to "P 1". '
     149                    self.warnings += "Change this in phase's General tab."
     150                else:
     151                    self.warnings += 'ERROR in space group symbol '+SpGrp
     152                    self.warnings += '\nThe space group has been set to "P 1". '
     153                    self.warnings += "Change this in phase's General tab."
     154                    self.warnings += '\nAre there spaces separating axial fields?\n\nError msg: '
     155                    self.warnings += G2spc.SGErrors(E)
     156                SGData = G2IO.SGData # P 1
     157            self.Phase['General']['SGData'] = SGData
     158            # cell parameters
     159            cell = []
     160            for lbl in cellitems:
     161                cell.append(cif.get_number_with_esd(blk[lbl])[0])
     162            Volume = G2lat.calc_V(G2lat.cell2A(cell))
     163            self.Phase['General']['Cell'] = [False,]+cell+[Volume,]
     164            # read in atoms
     165            self.errors = 'Error during reading of atoms'
     166            atomlbllist = [] # table to look up atom IDs
     167            atomloop = blk.GetLoop('_atom_site_label')
     168            atomkeys = [i.lower() for i in atomloop.keys()]
     169            if not blk.get('_atom_site_type_symbol'):
     170                self.isodistort_warnings += '\natom types are missing. \n Check & revise atom types as needed'
     171            if blk.get('_atom_site_aniso_label'):
     172                anisoloop = blk.GetLoop('_atom_site_aniso_label')
     173                anisokeys = [i.lower() for i in anisoloop.keys()]
     174                anisolabels = blk.get('_atom_site_aniso_label')
     175            else:
     176                anisoloop = None
     177                anisokeys = []
     178                anisolabels = []
     179            if Super:
     180                occFloop = None
     181                occCloop = None
     182                occFdict = {}
     183                occCdict = {}
     184                displSloop = None
     185                displFloop = None
     186                dispSdict = {}
     187                dispFdict = {}
     188                UijFloop = None
     189                UijFdict = {}
     190                if blk.get('_atom_site_occ_Fourier_atom_site_label'):
     191                    occFloop = blk.GetLoop('_atom_site_occ_Fourier_atom_site_label')
     192                    occFdict = dict(occFloop.items())
     193                if blk.get('_atom_site_occ_special_func_atom_site_label'):  #Crenel (i.e. Block Wave) occ
     194                    occCloop = blk.GetLoop('_atom_site_occ_special_func_atom_site_label')
     195                    occCdict = dict(occCloop.items())
     196                if blk.get('_atom_site_displace_Fourier_atom_site_label'):
     197                    displFloop = blk.GetLoop('_atom_site_displace_Fourier_atom_site_label')
     198                    displFdict = dict(displFloop.items())                           
     199                if blk.get('_atom_site_displace_special_func_atom_site_label'): #sawtooth
     200                    displSloop = blk.GetLoop('_atom_site_displace_special_func_atom_site_label')
     201                    displSdict = dict(displSloop.items())
     202                if blk.get('_atom_site_U_Fourier_atom_site_label'):
     203                    UijFloop = blk.GetLoop('_atom_site_U_Fourier_atom_site_label')
     204                    UijFdict = dict(UijFloop.items())
     205            self.Phase['Atoms'] = []
     206            G2AtomDict = {  '_atom_site_type_symbol' : 1,
     207                            '_atom_site_label' : 0,
     208                            '_atom_site_fract_x' : 3,
     209                            '_atom_site_fract_y' : 4,
     210                            '_atom_site_fract_z' : 5,
     211                            '_atom_site_occupancy' : 6,
     212                            '_atom_site_aniso_u_11' : 11,
     213                            '_atom_site_aniso_u_22' : 12,
     214                            '_atom_site_aniso_u_33' : 13,
     215                            '_atom_site_aniso_u_12' : 14,
     216                            '_atom_site_aniso_u_13' : 15,
     217                            '_atom_site_aniso_u_23' : 16, }
     218
     219            ranIdlookup = {}
     220            for aitem in atomloop:
     221                atomlist = ['','','',0,0,0,1.0,'',0,'I',0.01,0,0,0,0,0,0,0]
     222                atomlist[-1] = ran.randint(0,sys.maxint) # add a random Id
     223                while atomlist[-1] in ranIdlookup:
     224                    atomlist[-1] = ran.randint(0,sys.maxint) # make it unique
     225                for val,key in zip(aitem,atomkeys):
     226                    col = G2AtomDict.get(key)
     227                    if col >= 3:
     228                        atomlist[col] = cif.get_number_with_esd(val)[0]
     229                        if col >= 11: atomlist[9] = 'A' # if any Aniso term is defined, set flag
     230                    elif col is not None:
     231                        atomlist[col] = val
     232                    elif key in ('_atom_site_thermal_displace_type',
     233                               '_atom_site_adp_type'):   #Iso or Aniso?
     234                        if val.lower() == 'uani':
     235                            atomlist[9] = 'A'
     236                    elif key == '_atom_site_u_iso_or_equiv':
     237                        uisoval =cif.get_number_with_esd(val)[0]
     238                        if uisoval is not None: atomlist[10] = uisoval
     239                if not atomlist[1] and atomlist[0]:
     240                    typ = atomlist[0].rstrip('0123456789-+')
     241                    if G2elem.CheckElement(typ):
     242                        atomlist[1] = typ
     243                    if not atomlist[1]:
     244                        atomlist[1] = 'Xe'
     245                        self.warnings += ' Atom type '+typ+' not recognized; Xe assumed\n'
     246                if atomlist[0] in anisolabels: # does this atom have aniso values in separate loop?
     247                    atomlist[9] = 'A'  # set the aniso flag
     248                    for val,key in zip( # load the values
     249                            anisoloop.GetKeyedPacket('_atom_site_aniso_label',atomlist[0]),
     250                            anisokeys):
     251                        col = G2AtomDict.get(key)
     252                        if col:
     253                            atomlist[col] = cif.get_number_with_esd(val)[0]
     254                atomlist[7],atomlist[8] = G2spc.SytSym(atomlist[3:6],SGData)[:2]
     255                atomlist[1] = G2elem.FixValence(atomlist[1])
     256                self.Phase['Atoms'].append(atomlist)
     257                ranIdlookup[atomlist[0]] = atomlist[-1]
     258                if atomlist[0] in atomlbllist:
     259                    self.warnings += ' ERROR: repeated atom label: '+atomlist[0]
     260                else:
     261                    atomlbllist.append(atomlist[0])
     262                if Super:
     263                    Sfrac = []
     264                    Sadp = []                     
     265                    Spos = np.zeros((4,6))
     266                    nim = -1
     267                    for i,item in enumerate(displFdict['_atom_site_displace_Fourier_atom_site_label']):
     268                        if item == atomlist[0]:
     269                            waveType = 'Fourier'                               
     270                            ix = ['x','y','z'].index(displFdict['_atom_site_displace_Fourier_axis'][i])
     271                            im = int(displFdict['_atom_site_displace_Fourier_wave_vector_seq_id'][i])
     272                            if im != nim:
     273                                nim = im
     274                            val = displFdict['_atom_site_displace_Fourier_param_sin'][i]
     275                            Spos[im-1][ix] = cif.get_number_with_esd(val)[0]
     276                            val = displFdict['_atom_site_displace_Fourier_param_cos'][i]
     277                            Spos[im-1][ix+3] = cif.get_number_with_esd(val)[0]
     278                    if nim >= 0:
     279                        Spos = [[spos,False] for spos in Spos[:nim]]
    109280                    else:
    110                         choice[-1] += ('%d' % nd) + ' atoms'
    111                     choice[-1] += ', cell: '
    112                     fmt = "%.2f,"
    113                     for i,key in enumerate(cellitems):
    114                         if i == 3: fmt = "%.f,"
    115                         if i == 5: fmt = "%.f"
    116                         choice[-1] += fmt % cif.get_number_with_esd(
    117                             cf[blknm].get(key))[0]
    118                     sg = cf[blknm].get("_symmetry_space_group_name_H-M",'')
    119                     if not sg: sg = cf[blknm].get("_space_group_name_H-M_alt",'')
    120                     if sg: choice[-1] += ', (' + sg.strip() + ')'
    121                 selblk = self.PhaseSelector(
    122                     choice,
    123                     ParentFrame=ParentFrame,
    124                     title= 'Select a phase from one the CIF data_ blocks below',
    125                     size=(600,100)
    126                     )
    127             self.errors = 'Error during reading of selected block'
    128             if selblk is None:
    129                 returnstat = False # no block selected or available
    130             else:
    131                 blknm = str_blklist[selblk]
    132                 blk = cf[str_blklist[selblk]]
    133                 E = True
    134                 Super = False
    135                 SpGrp = blk.get("_symmetry_space_group_name_H-M",'')
    136                 if not SpGrp:
    137                     SpGrp = blk.get("_space_group_name_H-M_alt",'')
    138                 if not SpGrp:
    139                     sspgrp = blk.get("_space_group_ssg_name",'').split('(')
    140                     SpGrp = sspgrp[0]
    141                     SuperSg = '('+sspgrp[1].replace('\\','')
    142                     Super = True
    143                     SuperVec = [[0,0,.1],False,4]
    144                 # try normalizing the space group, to see if we can pick the space group out of a table
    145                 SpGrpNorm = G2spc.StandardizeSpcName(SpGrp)
    146                 if SpGrpNorm:
    147                     E,SGData = G2spc.SpcGroup(SpGrpNorm)
    148                 # nope, try the space group "out of the Box"
    149                 if E and SpGrp:
    150                     E,SGData = G2spc.SpcGroup(SpGrp)
    151                 if E:
    152                     if not SpGrp:
    153                         self.warnings += 'No space group name was found in the CIF.'
    154                         self.warnings += '\nThe space group has been set to "P 1". '
    155                         self.warnings += "Change this in phase's General tab."
    156                     else:
    157                         self.warnings += 'ERROR in space group symbol '+SpGrp
    158                         self.warnings += '\nThe space group has been set to "P 1". '
    159                         self.warnings += "Change this in phase's General tab."
    160                         self.warnings += '\nAre there spaces separating axial fields?\n\nError msg: '
    161                         self.warnings += G2spc.SGErrors(E)
    162                     SGData = G2IO.SGData # P 1
    163                 self.Phase['General']['SGData'] = SGData
    164                 # cell parameters
    165                 cell = []
    166                 for lbl in cellitems:
    167                     cell.append(cif.get_number_with_esd(blk[lbl])[0])
    168                 Volume = G2lat.calc_V(G2lat.cell2A(cell))
    169                 self.Phase['General']['Cell'] = [False,]+cell+[Volume,]
    170                 # read in atoms
    171                 self.errors = 'Error during reading of atoms'
    172                 atomlbllist = [] # table to look up atom IDs
    173                 atomloop = blk.GetLoop('_atom_site_label')
    174                 atomkeys = [i.lower() for i in atomloop.keys()]
    175                 if not blk.get('_atom_site_type_symbol'):
    176                     self.isodistort_warnings += '\natom types are missing. \n Check & revise atom types as needed'
    177                 if blk.get('_atom_site_aniso_label'):
    178                     anisoloop = blk.GetLoop('_atom_site_aniso_label')
    179                     anisokeys = [i.lower() for i in anisoloop.keys()]
    180                     anisolabels = blk.get('_atom_site_aniso_label')
    181                 else:
    182                     anisoloop = None
    183                     anisokeys = []
    184                     anisolabels = []
    185                 if Super:
    186                     occFloop = None
    187                     occCloop = None
    188                     occFdict = {}
    189                     cooCdict = {}
    190                     displSloop = None
    191                     displFloop = None
    192                     dispSdict = {}
    193                     dispFdict = {}
    194                     UijFloop = None
    195                     UijFdict = {}
    196                     if blk.get('_atom_site_occ_Fourier_atom_site_label'):
    197                         occFloop = blk.GetLoop('_atom_site_occ_Fourier_atom_site_label')
    198                         occFdict = dict(occFloop.items())
    199                     if blk.get('_atom_site_occ_special_func_atom_site_label'):  #Crenel (i.e. Block Wave) occ
    200                         occCloop = blk.GetLoop('_atom_site_occ_special_func_atom_site_label')
    201                         occCdict = dict(occCloop.items())
    202                     if blk.get('_atom_site_displace_Fourier_atom_site_label'):
    203                         displFloop = blk.GetLoop('_atom_site_displace_Fourier_atom_site_label')
    204                         displFdict = dict(displFloop.items())                           
    205                     if blk.get('_atom_site_displace_special_func_atom_site_label'): #sawtooth
    206                         displSloop = blk.GetLoop('_atom_site_displace_special_func_atom_site_label')
    207                         displSdict = dict(displSloop.items())
    208                     if blk.get('_atom_site_U_Fourier_atom_site_label'):
    209                         UijFloop = blk.GetLoop('_atom_site_U_Fourier_atom_site_label')
    210                         UijFdict = dict(UijFloop.items())
    211                 self.Phase['Atoms'] = []
    212                 G2AtomDict = {  '_atom_site_type_symbol' : 1,
    213                                 '_atom_site_label' : 0,
    214                                 '_atom_site_fract_x' : 3,
    215                                 '_atom_site_fract_y' : 4,
    216                                 '_atom_site_fract_z' : 5,
    217                                 '_atom_site_occupancy' : 6,
    218                                 '_atom_site_aniso_u_11' : 11,
    219                                 '_atom_site_aniso_u_22' : 12,
    220                                 '_atom_site_aniso_u_33' : 13,
    221                                 '_atom_site_aniso_u_12' : 14,
    222                                 '_atom_site_aniso_u_13' : 15,
    223                                 '_atom_site_aniso_u_23' : 16, }
    224 
    225                 ranIdlookup = {}
    226                 for aitem in atomloop:
    227                     atomlist = ['','','',0,0,0,1.0,'',0,'I',0.01,0,0,0,0,0,0,0]
    228                     atomlist[-1] = ran.randint(0,sys.maxint) # add a random Id
    229                     while atomlist[-1] in ranIdlookup:
    230                         atomlist[-1] = ran.randint(0,sys.maxint) # make it unique
    231                     for val,key in zip(aitem,atomkeys):
    232                         col = G2AtomDict.get(key)
    233                         if col >= 3:
    234                             atomlist[col] = cif.get_number_with_esd(val)[0]
    235                             if col >= 11: atomlist[9] = 'A' # if any Aniso term is defined, set flag
    236                         elif col is not None:
    237                             atomlist[col] = val
    238                         elif key in ('_atom_site_thermal_displace_type',
    239                                    '_atom_site_adp_type'):   #Iso or Aniso?
    240                             if val.lower() == 'uani':
    241                                 atomlist[9] = 'A'
    242                         elif key == '_atom_site_u_iso_or_equiv':
    243                             uisoval =cif.get_number_with_esd(val)[0]
    244                             if uisoval is not None: atomlist[10] = uisoval
    245                     if not atomlist[1] and atomlist[0]:
    246                         typ = atomlist[0].rstrip('0123456789-+')
    247                         if G2elem.CheckElement(typ):
    248                             atomlist[1] = typ
    249                         if not atomlist[1]:
    250                             atomlist[1] = 'Xe'
    251                             self.warnings += ' Atom type '+typ+' not recognized; Xe assumed\n'
    252                     if atomlist[0] in anisolabels: # does this atom have aniso values in separate loop?
    253                         atomlist[9] = 'A'  # set the aniso flag
    254                         for val,key in zip( # load the values
    255                                 anisoloop.GetKeyedPacket('_atom_site_aniso_label',atomlist[0]),
    256                                 anisokeys):
    257                             col = G2AtomDict.get(key)
    258                             if col:
    259                                 atomlist[col] = cif.get_number_with_esd(val)[0]
    260                     atomlist[7],atomlist[8] = G2spc.SytSym(atomlist[3:6],SGData)[:2]
    261                     atomlist[1] = G2elem.FixValence(atomlist[1])
    262                     self.Phase['Atoms'].append(atomlist)
    263                     ranIdlookup[atomlist[0]] = atomlist[-1]
    264                     if atomlist[0] in atomlbllist:
    265                         self.warnings += ' ERROR: repeated atom label: '+atomlist[0]
    266                     else:
    267                         atomlbllist.append(atomlist[0])
    268                     if Super:
    269                         Sfrac = []
    270                         Sadp = []                     
    271                         Spos = np.zeros((4,6))
     281                        Spos = []
     282                    if UijFdict:
    272283                        nim = -1
    273                         for i,item in enumerate(displFdict['_atom_site_displace_Fourier_atom_site_label']):
     284                        Sadp = np.zeros((4,12))
     285                        for i,item in enumerate(UijFdict['_atom_site_U_Fourier_atom_site_label']):
    274286                            if item == atomlist[0]:
    275                                 waveType = 'Fourier'                               
    276                                 ix = ['x','y','z'].index(displFdict['_atom_site_displace_Fourier_axis'][i])
    277                                 im = int(displFdict['_atom_site_displace_Fourier_wave_vector_seq_id'][i])
     287                                ix = ['U11','U22','U33','U12','U13','U23'].index(UijFdict['_atom_site_U_Fourier_tens_elem'][i])
     288                                im = int(UijFdict['_atom_site_U_Fourier_wave_vector_seq_id'][i])
    278289                                if im != nim:
    279290                                    nim = im
    280                                 val = displFdict['_atom_site_displace_Fourier_param_sin'][i]
    281                                 Spos[im-1][ix] = cif.get_number_with_esd(val)[0]
    282                                 val = displFdict['_atom_site_displace_Fourier_param_cos'][i]
    283                                 Spos[im-1][ix+3] = cif.get_number_with_esd(val)[0]
     291                                val = UijFdict['_atom_site_U_Fourier_param_sin'][i]
     292                                Sadp[im-1][ix] = cif.get_number_with_esd(val)[0]
     293                                val = UijFdict['_atom_site_U_Fourier_param_cos'][i]
     294                                Sadp[im-1][ix+6] = cif.get_number_with_esd(val)[0]
    284295                        if nim >= 0:
    285                             Spos = [[spos,False] for spos in Spos[:nim]]
     296                            Sadp = [[sadp,False] for sadp in Sadp[:nim]]
    286297                        else:
    287                             Spos = []
    288                         if UijFdict:
    289                             nim = -1
    290                             Sadp = np.zeros((4,12))
    291                             for i,item in enumerate(UijFdict['_atom_site_U_Fourier_atom_site_label']):
    292                                 if item == atomlist[0]:
    293                                     ix = ['U11','U22','U33','U12','U13','U23'].index(UijFdict['_atom_site_U_Fourier_tens_elem'][i])
    294                                     im = int(UijFdict['_atom_site_U_Fourier_wave_vector_seq_id'][i])
    295                                     if im != nim:
    296                                         nim = im
    297                                     val = UijFdict['_atom_site_U_Fourier_param_sin'][i]
    298                                     Sadp[im-1][ix] = cif.get_number_with_esd(val)[0]
    299                                     val = UijFdict['_atom_site_U_Fourier_param_cos'][i]
    300                                     Sadp[im-1][ix+6] = cif.get_number_with_esd(val)[0]
    301                             if nim >= 0:
    302                                 Sadp = [[sadp,False] for sadp in Sadp[:nim]]
    303                             else:
    304                                 Sadp = []
    305                        
    306                         SSdict = {'SS1':{'waveType':waveType,'Sfrac':Sfrac,'Spos':Spos,'Sadp':Sadp,'Smag':[]}}
    307                         atomlist.append(SSdict)
    308                 if len(atomlbllist) != len(self.Phase['Atoms']):
    309                     self.isodistort_warnings += '\nRepeated atom labels prevents ISODISTORT decode'
    310                 for lbl in phasenamefields: # get a name for the phase
    311                     name = blk.get(lbl)
    312                     if name is None:
    313                         continue
    314                     name = name.strip()
    315                     if name == '?' or name == '.':
    316                         continue
    317                     else:
    318                         break
    319                 else: # no name found, use block name for lack of a better choice
    320                     name = blknm
    321                 self.Phase['General']['Name'] = name.strip()[:20]
    322                 self.Phase['General']['Super'] = Super
    323                 if Super:
    324                     self.Phase['General']['Type'] = 'modulated'
    325                     self.Phase['General']['SuperVec'] = SuperVec
    326                     self.Phase['General']['SuperSg'] = SuperSg
    327                     self.Phase['General']['SSGData'] = G2spc.SSpcGroup(SGData,SuperSg)[1]
    328                 if not self.isodistort_warnings:
    329                     if blk.get('_iso_displacivemode_label') or blk.get('_iso_occupancymode_label'):
    330                         self.errors = "Error while processing ISODISTORT constraints"
    331                         self.ISODISTORT_proc(blk,atomlbllist,ranIdlookup)
    332                 else:
    333                     self.warnings += self.isodistort_warnings
    334                 returnstat = True
    335         except Exception as detail:
    336             self.errors += '\n  '+str(detail)
    337             print 'CIF error:',detail # for testing
    338             print sys.exc_info()[0] # for testing
    339             import traceback
    340             print traceback.format_exc()
    341             returnstat = False
     298                            Sadp = []
     299                   
     300                    SSdict = {'SS1':{'waveType':waveType,'Sfrac':Sfrac,'Spos':Spos,'Sadp':Sadp,'Smag':[]}}
     301                    atomlist.append(SSdict)
     302            if len(atomlbllist) != len(self.Phase['Atoms']):
     303                self.isodistort_warnings += '\nRepeated atom labels prevents ISODISTORT decode'
     304            for lbl in phasenamefields: # get a name for the phase
     305                name = blk.get(lbl)
     306                if name is None:
     307                    continue
     308                name = name.strip()
     309                if name == '?' or name == '.':
     310                    continue
     311                else:
     312                    break
     313            else: # no name found, use block name for lack of a better choice
     314                name = blknm
     315            self.Phase['General']['Name'] = name.strip()[:20]
     316            self.Phase['General']['Super'] = Super
     317            if Super:
     318                self.Phase['General']['Type'] = 'modulated'
     319                self.Phase['General']['SuperVec'] = SuperVec
     320                self.Phase['General']['SuperSg'] = SuperSg
     321                self.Phase['General']['SSGData'] = G2spc.SSpcGroup(SGData,SuperSg)[1]
     322            if not self.isodistort_warnings:
     323                if blk.get('_iso_displacivemode_label') or blk.get('_iso_occupancymode_label'):
     324                    self.errors = "Error while processing ISODISTORT constraints"
     325                    self.ISODISTORT_proc(blk,atomlbllist,ranIdlookup)
     326            else:
     327                self.warnings += self.isodistort_warnings
     328            returnstat = True
    342329        return returnstat
    343330
  • trunk/imports/G2phase_GPX.py

    r1812 r2738  
    6464                self.errors = 'No phase selected'
    6565                return False # User pressed cancel
    66         try:
    67             self.Phase = G2stIO.GetAllPhaseData(filename,phasenames[selblk])
    68             self.Phase['Histograms'] = {}       #remove any histograms
    69             self.Phase['Pawley ref'] = []       # & any Pawley refl.
    70             self.Phase['ranId'] = ran.randint(0,sys.maxint)
    71             return True
    72         except Exception as detail:
    73             self.errors = 'Error reading selected phase'
    74             self.errors += '\n  '+str(detail)
    75             print self.formatName+' error:',detail # for testing
    76             print sys.exc_info()[0] # for testing
    77             import traceback
    78             print traceback.format_exc()
     66        self.Phase = G2stIO.GetAllPhaseData(filename,phasenames[selblk])
     67        self.Phase['Histograms'] = {}       #remove any histograms
     68        self.Phase['Pawley ref'] = []       # & any Pawley refl.
     69        self.Phase['ranId'] = ran.randint(0,sys.maxint)
     70        return True
  • trunk/imports/G2phase_INS.py

    r2736 r2738  
    1616'''
    1717import sys
    18 import traceback
    19 import math
    2018import numpy as np
    2119import random as ran
     
    4947    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
    5048        'Read a ins file using :meth:`ReadINSPhase`'
    51         #try:
    5249        self.Phase = self.ReadINSPhase(filename, ParentFrame)
    5350        return True
    54         #except Exception as detail:
    55         #    self.errors += '\n  '+str(detail)
    56         #    print 'INS read error:',detail # for testing
    57         #    traceback.print_exc(file=sys.stdout)
    58         #    return False
    5951
    6052    def ReadINSPhase(self,filename,parent=None):
     
    6860            'SUMP','L.S.','CGLS','BLOC','DAMP','STIR','WGHT','FVAR','BOND','CONF','MPLA',
    6961            'HTAB','LIST','ACTA','SIZE','TEMP','WPDB','FMAP','GRID','PLAN','MOLE']
    70         EightPiSq = 8.*math.pi**2
    7162        self.errors = 'Error opening file'
    7263        file = open(filename, 'Ur')
    7364        Phase = {}
    7465        Title = ''
    75         Compnd = ''
    7666        Atoms = []
    7767        aTypes = []
    78         A = np.zeros(shape=(3,3))
    7968        S = file.readline()
    8069        line = 1
    8170        SGData = None
    8271        cell = None
    83         numbs = [str(i) for i in range(10)]
    8472        while S:
    8573            if '!' in S:
     
    8775            self.errors = 'Error reading at line '+str(line)
    8876            Atom = []
    89             Aindx = [ch in numbs for ch in S[:4]]   #False for all letters
    9077            if 'TITL' in S[:4].upper():
    9178                Title = S[4:72].strip()
     
    10087                Volume = G2lat.calc_V(G2lat.cell2A(cell))
    10188                AA,AB = G2lat.cell2AB(cell)
    102                 SpGrp = 'P 1'
    10389                SGData = G2IO.SGData # P 1
    10490                self.warnings += '\nThe space group is not given in an ins file and has been set to "P 1".'
  • trunk/imports/G2pwd_BrukerRAW.py

    r2700 r2738  
    6767            raise Exception    #for now
    6868        elif 'ver. 2' in self.formatName:
    69             try:
    70                 File.seek(4)
    71                 nBlock = int(st.unpack('<i',File.read(4))[0])
    72                 File.seek(168)
    73                 self.comments.append('Date/Time='+File.read(20))
    74                 self.comments.append('Anode='+File.read(2))
    75                 self.comments.append('Ka1=%.5f'%(st.unpack('<f',File.read(4))[0]))
    76                 self.comments.append('Ka2=%.5f'%(st.unpack('<f',File.read(4))[0]))
    77                 self.comments.append('Ka2/Ka1=%.5f'%(st.unpack('<f',File.read(4))[0]))
    78                 File.seek(206)
    79                 self.comments.append('Kb=%.5f'%(st.unpack('<f',File.read(4))[0]))
    80                 pos = 256
    81                 File.seek(pos)
    82                 blockNum = kwarg.get('blocknum',0)
    83                 self.idstring = ospath.basename(filename) + ' Scan '+str(blockNum)
    84                 if blockNum <= nBlock:
    85                     for iBlock in range(blockNum):
    86                         headLen = int(st.unpack('<H',File.read(2))[0])
    87                         nSteps = int(st.unpack('<H',File.read(2))[0])
    88                         if iBlock+1 == blockNum:
    89                             File.seek(pos+12)
    90                             step = st.unpack('<f',File.read(4))[0]
    91                             start2Th = st.unpack('<f',File.read(4))[0]
    92                             pos += headLen      #position at start of data block
    93                             File.seek(pos)                                   
    94                             x = np.array([start2Th+i*step for i in range(nSteps)])
    95                             y = np.array([max(1.,st.unpack('<f',File.read(4))[0]) for i in range(nSteps)])
    96                             y = np.where(y<0.,y,1.)
    97                             w = 1./y
    98                             self.powderdata = [x,y,w,np.zeros(nSteps),np.zeros(nSteps),np.zeros(nSteps)]
    99                             break
    100                         pos += headLen+4*nSteps
    101                         File.seek(pos)
    102                     if blockNum == nBlock:
    103                         self.repeat = False                                   
    104                 File.close()
    105             except Exception as detail:
    106                 self.errors += '\n  '+str(detail)
    107                 print self.formatName+' read error:'+str(detail) # for testing
    108                 import traceback
    109                 traceback.print_exc(file=sys.stdout)
    110                 return False
     69            File.seek(4)
     70            nBlock = int(st.unpack('<i',File.read(4))[0])
     71            File.seek(168)
     72            self.comments.append('Date/Time='+File.read(20))
     73            self.comments.append('Anode='+File.read(2))
     74            self.comments.append('Ka1=%.5f'%(st.unpack('<f',File.read(4))[0]))
     75            self.comments.append('Ka2=%.5f'%(st.unpack('<f',File.read(4))[0]))
     76            self.comments.append('Ka2/Ka1=%.5f'%(st.unpack('<f',File.read(4))[0]))
     77            File.seek(206)
     78            self.comments.append('Kb=%.5f'%(st.unpack('<f',File.read(4))[0]))
     79            pos = 256
     80            File.seek(pos)
     81            blockNum = kwarg.get('blocknum',0)
     82            self.idstring = ospath.basename(filename) + ' Scan '+str(blockNum)
     83            if blockNum <= nBlock:
     84                for iBlock in range(blockNum):
     85                    headLen = int(st.unpack('<H',File.read(2))[0])
     86                    nSteps = int(st.unpack('<H',File.read(2))[0])
     87                    if iBlock+1 == blockNum:
     88                        File.seek(pos+12)
     89                        step = st.unpack('<f',File.read(4))[0]
     90                        start2Th = st.unpack('<f',File.read(4))[0]
     91                        pos += headLen      #position at start of data block
     92                        File.seek(pos)                                   
     93                        x = np.array([start2Th+i*step for i in range(nSteps)])
     94                        y = np.array([max(1.,st.unpack('<f',File.read(4))[0]) for i in range(nSteps)])
     95                        y = np.where(y<0.,y,1.)
     96                        w = 1./y
     97                        self.powderdata = [x,y,w,np.zeros(nSteps),np.zeros(nSteps),np.zeros(nSteps)]
     98                        break
     99                    pos += headLen+4*nSteps
     100                    File.seek(pos)
     101                if blockNum == nBlock:
     102                    self.repeat = False                                   
     103            File.close()
    111104        elif 'ver. 3' in self.formatName:
    112             try:
    113                 File.seek(12)
    114                 nBlock = int(st.unpack('<i',File.read(4))[0])
    115                 self.comments.append('Date='+File.read(10))
    116                 self.comments.append('Time='+File.read(10))
    117                 File.seek(326)
    118                 self.comments.append('Sample='+File.read(60))
    119                 File.seek(564)
    120                 radius = st.unpack('<f',File.read(4))[0]
    121                 self.comments.append('Gonio. radius=%.2f'%(radius))
    122                 self.Sample['Gonio. radius'] = radius
    123                 File.seek(608)
    124                 self.comments.append('Anode='+File.read(4))
    125                 File.seek(616)
    126                 self.comments.append('Ka mean=%.5f'%(st.unpack('<d',File.read(8))[0]))
    127                 self.comments.append('Ka1=%.5f'%(st.unpack('<d',File.read(8))[0]))
    128                 self.comments.append('Ka2=%.5f'%(st.unpack('<d',File.read(8))[0]))
    129                 self.comments.append('Kb=%.5f'%(st.unpack('<d',File.read(8))[0]))
    130                 self.comments.append('Ka2/Ka1=%.5f'%(st.unpack('<d',File.read(8))[0]))
    131                 pos = 712
    132                 File.seek(pos)      #position at 1st block header
    133                 blockNum = kwarg.get('blocknum',0)
    134                 self.idstring = ospath.basename(filename) + ' Scan '+str(blockNum)
    135                 if blockNum <= nBlock:
    136                     for iBlock in range(blockNum):
    137                         headLen = int(st.unpack('<i',File.read(4))[0])
    138                         if nBlock > 1:
    139                             headLen += 40
    140                         nSteps = int(st.unpack('<i',File.read(4))[0])
    141                         if not nSteps: break
    142                         if iBlock+1 == blockNum:
    143                             st.unpack('<d',File.read(8))[0]
    144                             start2Th = st.unpack('<d',File.read(8))[0]
    145                             File.seek(pos+212)
    146                             temp = st.unpack('<f',File.read(4))[0]
    147                             if temp > 0.:
    148                                 self.Sample['Temperature'] = temp                                                       
    149                             File.seek(pos+176)
    150                             step = st.unpack('<d',File.read(8))[0]
    151                             pos += headLen      #position at start of data block
    152                             File.seek(pos)                                   
    153                             x = np.array([start2Th+i*step for i in range(nSteps)])
    154                             y = np.array([max(1.,st.unpack('<f',File.read(4))[0]) for i in range(nSteps)])
    155                             w = 1./y
    156                             self.powderdata = [x,y,w,np.zeros(nSteps),np.zeros(nSteps),np.zeros(nSteps)]
    157                             break
    158                         pos += headLen+4*nSteps
    159                         File.seek(pos)
    160                     if blockNum == nBlock:
    161                         self.repeat = False                                   
    162                 File.close()
    163             except Exception as detail:
    164                 self.errors += '\n  '+str(detail)
    165                 print self.formatName+' read error:'+str(detail) # for testing
    166                 import traceback
    167                 traceback.print_exc(file=sys.stdout)
    168                 return False
     105            File.seek(12)
     106            nBlock = int(st.unpack('<i',File.read(4))[0])
     107            self.comments.append('Date='+File.read(10))
     108            self.comments.append('Time='+File.read(10))
     109            File.seek(326)
     110            self.comments.append('Sample='+File.read(60))
     111            File.seek(564)
     112            radius = st.unpack('<f',File.read(4))[0]
     113            self.comments.append('Gonio. radius=%.2f'%(radius))
     114            self.Sample['Gonio. radius'] = radius
     115            File.seek(608)
     116            self.comments.append('Anode='+File.read(4))
     117            File.seek(616)
     118            self.comments.append('Ka mean=%.5f'%(st.unpack('<d',File.read(8))[0]))
     119            self.comments.append('Ka1=%.5f'%(st.unpack('<d',File.read(8))[0]))
     120            self.comments.append('Ka2=%.5f'%(st.unpack('<d',File.read(8))[0]))
     121            self.comments.append('Kb=%.5f'%(st.unpack('<d',File.read(8))[0]))
     122            self.comments.append('Ka2/Ka1=%.5f'%(st.unpack('<d',File.read(8))[0]))
     123            pos = 712
     124            File.seek(pos)      #position at 1st block header
     125            blockNum = kwarg.get('blocknum',0)
     126            self.idstring = ospath.basename(filename) + ' Scan '+str(blockNum)
     127            if blockNum <= nBlock:
     128                for iBlock in range(blockNum):
     129                    headLen = int(st.unpack('<i',File.read(4))[0])
     130                    if nBlock > 1:
     131                        headLen += 40
     132                    nSteps = int(st.unpack('<i',File.read(4))[0])
     133                    if not nSteps: break
     134                    if iBlock+1 == blockNum:
     135                        st.unpack('<d',File.read(8))[0]
     136                        start2Th = st.unpack('<d',File.read(8))[0]
     137                        File.seek(pos+212)
     138                        temp = st.unpack('<f',File.read(4))[0]
     139                        if temp > 0.:
     140                            self.Sample['Temperature'] = temp                                                       
     141                        File.seek(pos+176)
     142                        step = st.unpack('<d',File.read(8))[0]
     143                        pos += headLen      #position at start of data block
     144                        File.seek(pos)                                   
     145                        x = np.array([start2Th+i*step for i in range(nSteps)])
     146                        y = np.array([max(1.,st.unpack('<f',File.read(4))[0]) for i in range(nSteps)])
     147                        w = 1./y
     148                        self.powderdata = [x,y,w,np.zeros(nSteps),np.zeros(nSteps),np.zeros(nSteps)]
     149                        break
     150                    pos += headLen+4*nSteps
     151                    File.seek(pos)
     152                if blockNum == nBlock:
     153                    self.repeat = False                                   
     154            File.close()
    169155           
    170156        elif 'ver. 4' in self.formatName:   #does not work - format still elusive
    171             try:
    172                 File.seek(12)   #ok
    173                 self.comments.append('Date='+File.read(10))
    174                 self.comments.append('Time='+File.read(10))
    175                 File.seek(144)
    176                 self.comments.append('Sample='+File.read(60))
    177                 File.seek(564)  # where is it?
    178                 radius = st.unpack('<f',File.read(4))[0]
    179                 self.comments.append('Gonio. radius=%.2f'%(radius))
    180                 self.Sample['Gonio. radius'] = radius
    181                 File.seek(516)  #ok
    182                 self.comments.append('Anode='+File.read(4))
    183                 File.seek(472)  #ok
    184                 self.comments.append('Ka mean=%.5f'%(st.unpack('<d',File.read(8))[0]))
    185                 self.comments.append('Ka1=%.5f'%(st.unpack('<d',File.read(8))[0]))
    186                 self.comments.append('Ka2=%.5f'%(st.unpack('<d',File.read(8))[0]))
    187                 self.comments.append('Kb=%.5f'%(st.unpack('<d',File.read(8))[0]))
    188                 self.comments.append('Ka2/Ka1=%.5f'%(st.unpack('<d',File.read(8))[0]))
    189                 File.seek(pos)  #deliberate fail here - pos not known from file contents
    190                 self.idstring = ospath.basename(filename) + ' Scan '+str(1)
    191                 nSteps = int(st.unpack('<i',File.read(4))[0])
    192                 st.unpack('<d',File.read(8))[0]
    193                 start2Th = st.unpack('<d',File.read(8))[0]
    194                 File.seek(pos+176)
    195                 step = st.unpack('<d',File.read(8))[0]
    196                 pos += headLen      #position at start of data block
    197                 File.seek(pos)                                   
    198                 x = np.array([start2Th+i*step for i in range(nSteps)])
    199                 y = np.array([max(1.,st.unpack('<f',File.read(4))[0]) for i in range(nSteps)])
    200                 w = 1./y
    201                 self.powderdata = [x,y,w,np.zeros(nSteps),np.zeros(nSteps),np.zeros(nSteps)]
    202                 File.close()
    203             except Exception as detail:
    204                 self.errors += '\n  '+str(detail)
    205                 print self.formatName+' read error:'+str(detail) # for testing
    206                 import traceback
    207                 traceback.print_exc(file=sys.stdout)
    208                 return False
     157            File.seek(12)   #ok
     158            self.comments.append('Date='+File.read(10))
     159            self.comments.append('Time='+File.read(10))
     160            File.seek(144)
     161            self.comments.append('Sample='+File.read(60))
     162            File.seek(564)  # where is it?
     163            radius = st.unpack('<f',File.read(4))[0]
     164            self.comments.append('Gonio. radius=%.2f'%(radius))
     165            self.Sample['Gonio. radius'] = radius
     166            File.seek(516)  #ok
     167            self.comments.append('Anode='+File.read(4))
     168            File.seek(472)  #ok
     169            self.comments.append('Ka mean=%.5f'%(st.unpack('<d',File.read(8))[0]))
     170            self.comments.append('Ka1=%.5f'%(st.unpack('<d',File.read(8))[0]))
     171            self.comments.append('Ka2=%.5f'%(st.unpack('<d',File.read(8))[0]))
     172            self.comments.append('Kb=%.5f'%(st.unpack('<d',File.read(8))[0]))
     173            self.comments.append('Ka2/Ka1=%.5f'%(st.unpack('<d',File.read(8))[0]))
     174            File.seek(pos)  #deliberate fail here - pos not known from file contents
     175            self.idstring = ospath.basename(filename) + ' Scan '+str(1)
     176            nSteps = int(st.unpack('<i',File.read(4))[0])
     177            st.unpack('<d',File.read(8))[0]
     178            start2Th = st.unpack('<d',File.read(8))[0]
     179            File.seek(pos+176)
     180            step = st.unpack('<d',File.read(8))[0]
     181            pos += headLen      #position at start of data block
     182            File.seek(pos)                                   
     183            x = np.array([start2Th+i*step for i in range(nSteps)])
     184            y = np.array([max(1.,st.unpack('<f',File.read(4))[0]) for i in range(nSteps)])
     185            w = 1./y
     186            self.powderdata = [x,y,w,np.zeros(nSteps),np.zeros(nSteps),np.zeros(nSteps)]
     187            File.close()
    209188           
    210189        return True
  • trunk/imports/G2pwd_CIF.py

    r2516 r2738  
    1414
    1515'''
    16 import sys
    1716import numpy as np
    1817import os.path
     
    9695            self.ShowBusy() # this can take a while
    9796            print "Starting parse of CIF file"
    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()
     97            cf = G2IO.ReadCIF(filename)
     98            self.DoneBusy()
    10599            print "CIF file parsed"
    106100        # scan all blocks for sets of data
    107101        if choicelist is None:
    108             try:
    109                 choicelist = []
    110                 for blk in cf.keys():
    111                     blkkeys = [k.lower() for k in cf[blk].keys()] # save a list of the data items, since we will use it often
    112                     # scan through block for x items
    113                     xldict = {}
    114                     for x in xDataItems:
    115                         if type(x) is tuple: # check for the presence of all three items that define a range of data
    116                             if not all([i in blkkeys for i in x]): continue
    117                             try:
    118                                 items = [float(cf[blk][xi]) for xi in x]
    119                                 l = 1 + int(0.5 + (items[1]-items[0])/items[2])
    120                             except:
    121                                 continue
     102            choicelist = []
     103            for blk in cf.keys():
     104                blkkeys = [k.lower() for k in cf[blk].keys()] # save a list of the data items, since we will use it often
     105                # scan through block for x items
     106                xldict = {}
     107                for x in xDataItems:
     108                    if type(x) is tuple: # check for the presence of all three items that define a range of data
     109                        if not all([i in blkkeys for i in x]): continue
     110                        try:
     111                            items = [float(cf[blk][xi]) for xi in x]
     112                            l = 1 + int(0.5 + (items[1]-items[0])/items[2])
     113                        except:
     114                            continue
     115                    else:
     116                        if x not in blkkeys: continue
     117                        l = len(cf[blk][x])
     118                    if xldict.get(l) is None:
     119                        xldict[l] = [x]
     120                    else:
     121                        xldict[l].append(x)
     122                # now look for matching intensity items
     123                yldict = {}
     124                suldict = {}
     125                for y in intDataItems:
     126                    if y in blkkeys:
     127                        l = len(cf[blk][y])
     128                        if yldict.get(l) is None:
     129                            yldict[l] = [y]
    122130                        else:
    123                             if x not in blkkeys: continue
    124                             l = len(cf[blk][x])
    125                         if xldict.get(l) is None:
    126                             xldict[l] = [x]
     131                            yldict[l].append(y)
     132                        # now check if the first item has an uncertainty
     133                        if cif.get_number_with_esd(cf[blk][y][0])[1] is None: continue
     134                        if suldict.get(l) is None:
     135                            suldict[l] = [y]
    127136                        else:
    128                             xldict[l].append(x)
    129                     # now look for matching intensity items
    130                     yldict = {}
    131                     suldict = {}
    132                     for y in intDataItems:
    133                         if y in blkkeys:
    134                             l = len(cf[blk][y])
    135                             if yldict.get(l) is None:
    136                                 yldict[l] = [y]
    137                             else:
    138                                 yldict[l].append(y)
    139                             # now check if the first item has an uncertainty
    140                             if cif.get_number_with_esd(cf[blk][y][0])[1] is None: continue
    141                             if suldict.get(l) is None:
    142                                 suldict[l] = [y]
    143                             else:
    144                                 suldict[l].append(y)
    145                     for y in ESDDataItems:
    146                         if y in blkkeys:
    147                             l = len(cf[blk][y])
    148                             if suldict.get(l) is None:
    149                                 suldict[l] = [y]
    150                             else:
    151                                 suldict[l].append(y)
    152                     modldict = {}
    153                     for y in ModDataItems:
    154                         if y in blkkeys:
    155                             l = len(cf[blk][y])
    156                             if modldict.get(l) is None:
    157                                 modldict[l] = [y]
    158                             else:
    159                                 modldict[l].append(y)
    160                     for l in xldict:
    161                         if yldict.get(l) is None: continue
    162                         choicelist.append([blk,l,xldict[l],yldict[l],suldict.get(l,[]),modldict.get(l,[])])
    163                         #print blk,l,xldict[l],yldict[l],suldict.get(l,[]),modldict.get(l,[])
    164             except Exception as detail:
    165                 self.errors = "Error scanning blocks"
    166                 self.errors += "\n  Read exception: "+str(detail)
    167                 print self.formatName+' read error:'+str(detail) # for testing
    168                 import traceback
    169                 traceback.print_exc(file=sys.stdout)
    170                 #self.errors += "\n  Traceback info:\n"+str(traceback.format_exc())
    171                 return False
     137                            suldict[l].append(y)
     138                for y in ESDDataItems:
     139                    if y in blkkeys:
     140                        l = len(cf[blk][y])
     141                        if suldict.get(l) is None:
     142                            suldict[l] = [y]
     143                        else:
     144                            suldict[l].append(y)
     145                modldict = {}
     146                for y in ModDataItems:
     147                    if y in blkkeys:
     148                        l = len(cf[blk][y])
     149                        if modldict.get(l) is None:
     150                            modldict[l] = [y]
     151                        else:
     152                            modldict[l].append(y)
     153                for l in xldict:
     154                    if yldict.get(l) is None: continue
     155                    choicelist.append([blk,l,xldict[l],yldict[l],suldict.get(l,[]),modldict.get(l,[])])
     156                    #print blk,l,xldict[l],yldict[l],suldict.get(l,[]),modldict.get(l,[])
    172157            print "CIF file scanned for blocks with data"
    173158        if not choicelist:
     
    240225
    241226        # now read in the values
    242         try:
    243             self.ShowBusy() # this can also take a while
    244             # x-values
    245             xcf = xch[xi]
    246             if type(xcf) is tuple:
    247                 vals = [float(cf[blk][xi]) for xi in xcf]
    248                 x = np.array(
    249                     [(i*vals[2] + vals[0]) for i in range(1 + int(0.5 + (vals[1]-vals[0])/vals[2]))]
    250                     )
     227        self.ShowBusy() # this can also take a while
     228        # x-values
     229        xcf = xch[xi]
     230        if type(xcf) is tuple:
     231            vals = [float(cf[blk][ixi]) for ixi in xcf]
     232            x = np.array([(i*vals[2] + vals[0]) for i in range(1 + int(0.5 + (vals[1]-vals[0])/vals[2]))])
     233        else:
     234            vl = []
     235            for val in cf[blk].get(xcf,'?'):
     236                v,e = cif.get_number_with_esd(val)
     237                if v is None: # not parsed
     238                    vl.append(np.NaN)
     239                else:
     240                    vl.append(v)
     241            x = np.array(vl)
     242        # y-values
     243        ycf = ych[yi]
     244        vl = []
     245        v2 = []
     246        for val in cf[blk].get(ycf,'?'):
     247            v,e = cif.get_number_with_esd(val)
     248            if v is None: # not parsed
     249                vl.append(np.NaN)
     250                v2.append(np.NaN)
    251251            else:
    252                 vl = []
    253                 for val in cf[blk].get(xcf,'?'):
     252                vl.append(v)
     253                v2.append(max(e,1.0))
     254        y = np.array(vl)
     255        w = 1./np.array(v2)**2
     256        # weights
     257        if sui == -1:
     258            # no weights
     259            vl = np.zeros(len(x)) + 1.
     260        else:
     261            vl = []
     262            sucf = such[sui]
     263            if sucf ==  '_pd_proc_ls_weight':
     264                for val in cf[blk].get(sucf,'?'):
    254265                    v,e = cif.get_number_with_esd(val)
    255266                    if v is None: # not parsed
     267                        vl.append(0.)
     268                    else:
     269                        vl.append(v)
     270            elif sucf ==  '_pd_meas_counts_total':
     271                for val in cf[blk].get(sucf,'?'):
     272                    v,e = cif.get_number_with_esd(val)
     273                    if v is None: # not parsed
     274                        vl.append(0.)
     275                    elif v <= 0:
     276                        vl.append(1.)
     277                    else:
     278                        vl.append(1./v)
     279            else:
     280                for val in cf[blk].get(sucf,'?'):
     281                    v,e = cif.get_number_with_esd(val)
     282                    if v is None or e is None: # not parsed or no ESD
    256283                        vl.append(np.NaN)
    257                     else:
    258                         vl.append(v)
    259                 x = np.array(vl)
    260             # y-values
    261             ycf = ych[yi]
     284                    elif e <= 0:
     285                        vl.append(1.)
     286                    else:
     287                        vl.append(1./(e*e))
     288#            w = np.array(vl)
     289        # intensity modification factor
     290        if modi >= 1:
     291            ycf = modch[modi-1]
    262292            vl = []
    263             v2 = []
    264293            for val in cf[blk].get(ycf,'?'):
    265294                v,e = cif.get_number_with_esd(val)
    266295                if v is None: # not parsed
    267296                    vl.append(np.NaN)
    268                     v2.append(np.NaN)
    269297                else:
    270298                    vl.append(v)
    271                     v2.append(max(e,1.0))
    272             y = np.array(vl)
    273             w = 1./np.array(v2)**2
    274             # weights
    275             if sui == -1:
    276                 # no weights
    277                 vl = np.zeros(len(x)) + 1.
    278             else:
    279                 vl = []
    280                 sucf = such[sui]
    281                 if sucf ==  '_pd_proc_ls_weight':
    282                     for val in cf[blk].get(sucf,'?'):
    283                         v,e = cif.get_number_with_esd(val)
    284                         if v is None: # not parsed
    285                             vl.append(0.)
    286                         else:
    287                             vl.append(v)
    288                 elif sucf ==  '_pd_meas_counts_total':
    289                     for val in cf[blk].get(sucf,'?'):
    290                         v,e = cif.get_number_with_esd(val)
    291                         if v is None: # not parsed
    292                             vl.append(0.)
    293                         elif v <= 0:
    294                             vl.append(1.)
    295                         else:
    296                             vl.append(1./v)
    297                 else:
    298                     for val in cf[blk].get(sucf,'?'):
    299                         v,e = cif.get_number_with_esd(val)
    300                         if v is None or e is None: # not parsed or no ESD
    301                             vl.append(np.NaN)
    302                         elif e <= 0:
    303                             vl.append(1.)
    304                         else:
    305                             vl.append(1./(e*e))
    306 #            w = np.array(vl)
    307             # intensity modification factor
    308             if modi >= 1:
    309                 ycf = modch[modi-1]
    310                 vl = []
    311                 for val in cf[blk].get(ycf,'?'):
    312                     v,e = cif.get_number_with_esd(val)
    313                     if v is None: # not parsed
    314                         vl.append(np.NaN)
    315                     else:
    316                         vl.append(v)
    317                 y /= np.array(vl)
    318                 w /= np.array(vl)
    319             N = len(x)
    320         except Exception as detail:
    321             self.errors = "Error reading from selected block"
    322             self.errors += "\n  Read exception: "+str(detail)
    323             print self.formatName+' read error:'+str(detail) # for testing
    324             import traceback
    325             traceback.print_exc(file=sys.stdout)
    326             #self.errors += "\n  Traceback info:\n"+str(traceback.format_exc())
    327             return False
    328         finally:
    329             self.DoneBusy()
    330             print "CIF file, read from selected block"
     299            y /= np.array(vl)
     300            w /= np.array(vl)
     301        N = len(x)
     302        self.DoneBusy()
     303        print "CIF file, read from selected block"
    331304
    332305        self.errors = "Error while storing read values"
  • trunk/imports/G2pwd_FP.py

    r2516 r2738  
    7272        y = []
    7373        w = []
    74         try:
    75             gotCcomment = False
    76             begin = True
    77             steps = False
    78             Stop = False
    79             N = 0
    80             for i,S in enumerate(filepointer):
    81                 self.errors = 'Error reading line: '+str(i+1)
    82                 # or a block of comments delimited by /* and */
    83                 # or (GSAS style) each line can begin with '#' or '!'
    84                 if begin:
    85                     if gotCcomment and S.find('*/') > -1:
    86                         self.comments.append(S[:-1])
    87                         begin = False
    88                         continue
    89                     if S.strip().startswith('/*'):
    90                         self.comments.append(S[:-1])
    91                         gotCcomment = True
    92                         continue   
    93                     if S.lstrip()[0] in ["'",'#','!',]:
    94                         self.comments.append(S[:-1])
    95                         continue       #ignore comments, if any
     74        gotCcomment = False
     75        begin = True
     76        steps = False
     77        Stop = False
     78        N = 0
     79        for i,S in enumerate(filepointer):
     80            self.errors = 'Error reading line: '+str(i+1)
     81            # or a block of comments delimited by /* and */
     82            # or (GSAS style) each line can begin with '#' or '!'
     83            if begin:
     84                if gotCcomment and S.find('*/') > -1:
     85                    self.comments.append(S[:-1])
     86                    begin = False
     87                    continue
     88                if S.strip().startswith('/*'):
     89                    self.comments.append(S[:-1])
     90                    gotCcomment = True
     91                    continue   
     92                if S.lstrip()[0] in ["'",'#','!',]:
     93                    self.comments.append(S[:-1])
     94                    continue       #ignore comments, if any
     95                else:
     96                    begin = False
     97            # valid line to read
     98            if not steps:
     99                vals = S.split(None,4)
     100                if len(vals) >= 3:
     101                    steps = True
     102                    start = float(vals[0])
     103                    step = float(vals[1])
     104                    stop = float(vals[2])
     105                    if len(vals) > 3:
     106                        self.comments.append(vals[3][:-1])
     107                    continue
     108            vals = S.split()    #data strings
     109            try:
     110                for j in range(len(vals)):
     111                    x.append(start+N*step)
     112                    f = float(vals[j])
     113                    if f <= 0.0:
     114                        y.append(0.0)
     115                        w.append(0.0)
    96116                    else:
    97                         begin = False
    98                 # valid line to read
    99                 if not steps:
    100                     vals = S.split(None,4)
    101                     if len(vals) >= 3:
    102                         steps = True
    103                         start = float(vals[0])
    104                         step = float(vals[1])
    105                         stop = float(vals[2])
    106                         if len(vals) > 3:
    107                             self.comments.append(vals[3][:-1])
    108                         continue
    109                 vals = S.split()    #data strings
     117                        y.append(float(vals[j]))
     118                        w.append(1.0/float(vals[j]))
     119                    if x[-1] >= stop:
     120                        Stop = True
     121                        break
     122                    N += 1
     123                if Stop:
     124                    break
     125            except ValueError:
     126                msg = 'Error parsing number in line '+str(i+1)
     127                print msg
     128                print S
     129                break
     130            except:
     131                msg = 'Error in line '+str(i+1)
     132                print msg
     133                print S
     134                break
     135        N = len(x)
     136        if N <= 1: return False
     137        self.powderdata = [
     138            np.array(x), # x-axis values
     139            np.array(y), # powder pattern intensities
     140            np.array(w), # 1/sig(intensity)^2 values (weights)
     141            np.zeros(N), # calc. intensities (zero)
     142            np.zeros(N), # calc. background (zero)
     143            np.zeros(N), # obs-calc profiles
     144            ]
     145        self.powderentry[0] = filename
     146        #self.powderentry[1] = pos # bank offset (N/A here)
     147        #self.powderentry[2] = 1 # xye file only has one bank
     148        self.idstring = ospath.basename(filename)
     149        # scan comments for temperature
     150        Temperature = 300
     151        for S in self.comments:
     152            if 'Temp' in S.split('=')[0]:
    110153                try:
    111                     for j in range(len(vals)):
    112                         x.append(start+N*step)
    113                         f = float(vals[j])
    114                         if f <= 0.0:
    115                             y.append(0.0)
    116                             w.append(0.0)
    117                         else:
    118                             y.append(float(vals[j]))
    119                             w.append(1.0/float(vals[j]))
    120                         if x[-1] >= stop:
    121                             Stop = True
    122                             break
    123                         N += 1
    124                     if Stop:
    125                         break
    126                 except ValueError:
    127                     msg = 'Error parsing number in line '+str(i+1)
    128                     print msg
    129                     print S
    130                     break
     154                    Temperature = float(S.split('=')[1])
    131155                except:
    132                     msg = 'Error in line '+str(i+1)
    133                     print msg
    134                     print S
    135                     break
    136             N = len(x)
    137             if N <= 1: return False
    138             self.powderdata = [
    139                 np.array(x), # x-axis values
    140                 np.array(y), # powder pattern intensities
    141                 np.array(w), # 1/sig(intensity)^2 values (weights)
    142                 np.zeros(N), # calc. intensities (zero)
    143                 np.zeros(N), # calc. background (zero)
    144                 np.zeros(N), # obs-calc profiles
    145                 ]
    146             self.powderentry[0] = filename
    147             #self.powderentry[1] = pos # bank offset (N/A here)
    148             #self.powderentry[2] = 1 # xye file only has one bank
    149             self.idstring = ospath.basename(filename)
    150             # scan comments for temperature
    151             Temperature = 300
    152             for S in self.comments:
    153                 if 'Temp' in S.split('=')[0]:
    154                     try:
    155                         Temperature = float(S.split('=')[1])
    156                     except:
    157                         pass
    158             self.Sample['Temperature'] = Temperature
     156                    pass
     157        self.Sample['Temperature'] = Temperature
    159158
    160             return True
    161         except Exception as detail:
    162             self.errors += '\n  '+str(detail)
    163             print self.formatName+' read error:'+str(detail) # for testing
    164             import traceback
    165             traceback.print_exc(file=sys.stdout)
    166             return False
     159        return True
    167160
  • trunk/imports/G2pwd_GPX.py

    r1574 r2738  
    100100                    rdbuffer['selections'] = selections
    101101
    102         try:
    103             fl = open(filename,'rb')
    104             fl.seek(poslist[selblk])
    105             data = cPickle.load(fl)
    106             N = len(data[0][1][1][0])
    107             #self.powderdata = data[0][1][1]
    108             self.powderdata = [
    109                 data[0][1][1][0], # x-axis values
    110                 data[0][1][1][1], # powder pattern intensities
    111                 data[0][1][1][2], # 1/sig(intensity)^2 values (weights)
    112                 np.zeros(N), # calc. intensities (zero)
    113                 np.zeros(N), # calc. background (zero)
    114                 np.zeros(N), # obs-calc profiles
    115             ]
    116             self.powderentry[0] = filename
    117             self.powderentry[2] = selblk+1
    118             # pull some sections from the PWDR children
    119             for i in range(1,len(data)):
    120                 if data[i][0] == 'Comments':
    121                     self.comments = data[i][1]
    122                     continue
    123                 elif data[i][0] == 'Sample Parameters':
    124                     self.Sample = data[i][1]
    125                     continue
    126                 for keepitem in ('Limits','Background','Instrument Parameters'):
    127                     if data[i][0] == keepitem:
    128                         self.pwdparms[data[i][0]] = data[i][1]
    129                         break
    130             self.idstring = data[0][0][5:]
    131             self.repeat_instparm = False # prevent reuse of iparm when several hists are read
    132             return True
    133         except Exception as detail:
    134             self.errors = 'Error reading selected histogram\n  '+str(detail)
    135             print self.formatName+' error:',detail # for testing
    136             print sys.exc_info()[0] # for testing
    137             import traceback
    138             print traceback.format_exc()
    139             return False
    140         finally:
    141             fl.close()
     102        fl = open(filename,'rb')
     103        fl.seek(poslist[selblk])
     104        data = cPickle.load(fl)
     105        N = len(data[0][1][1][0])
     106        #self.powderdata = data[0][1][1]
     107        self.powderdata = [
     108            data[0][1][1][0], # x-axis values
     109            data[0][1][1][1], # powder pattern intensities
     110            data[0][1][1][2], # 1/sig(intensity)^2 values (weights)
     111            np.zeros(N), # calc. intensities (zero)
     112            np.zeros(N), # calc. background (zero)
     113            np.zeros(N), # obs-calc profiles
     114        ]
     115        self.powderentry[0] = filename
     116        self.powderentry[2] = selblk+1
     117        # pull some sections from the PWDR children
     118        for i in range(1,len(data)):
     119            if data[i][0] == 'Comments':
     120                self.comments = data[i][1]
     121                continue
     122            elif data[i][0] == 'Sample Parameters':
     123                self.Sample = data[i][1]
     124                continue
     125            for keepitem in ('Limits','Background','Instrument Parameters'):
     126                if data[i][0] == keepitem:
     127                    self.pwdparms[data[i][0]] = data[i][1]
     128                    break
     129        self.idstring = data[0][0][5:]
     130        self.repeat_instparm = False # prevent reuse of iparm when several hists are read
     131        fl.close()
     132        return True
  • trunk/imports/G2pwd_csv.py

    r2516 r2738  
    1616'''
    1717
    18 import sys
    1918import os.path as ospath
    2019import numpy as np
     
    5756        y = []
    5857        w = []
    59         try:
    60             begin = True
    61             for i,S in enumerate(filepointer):
    62                 vals = S.replace(',',' ').replace(';',' ').split()
    63                 if len(vals) < 2 and i > 0:
    64                     print 'Line '+str(i+1)+' cannot be read:\n\t'+S
    65                     continue
     58        for i,S in enumerate(filepointer):
     59            vals = S.replace(',',' ').replace(';',' ').split()
     60            if len(vals) < 2 and i > 0:
     61                print 'Line '+str(i+1)+' cannot be read:\n\t'+S
     62                continue
     63            try:
     64                x.append(float(vals[0]))
     65                f = float(vals[1])
     66                if f <= 0.0:
     67                    y.append(0.0)
     68                    w.append(0.0)
     69                elif len(vals) == 3:
     70                    y.append(float(vals[1]))
     71                    w.append(1.0/float(vals[2])**2)
     72                else:
     73                    y.append(float(vals[1]))
     74                    w.append(1.0/float(vals[1]))
     75                err = False
     76            except ValueError:
     77                err = True
     78                msg = 'Error parsing number in line '+str(i+1)
     79            except:
     80                err = True
     81                msg = 'Error in line '+str(i+1)
     82            if err and i > 0:
     83                print msg
     84                print S
     85                break
     86        N = len(x)
     87        self.powderdata = [
     88            np.array(x), # x-axis values
     89            np.array(y), # powder pattern intensities
     90            np.array(w), # 1/sig(intensity)^2 values (weights)
     91            np.zeros(N), # calc. intensities (zero)
     92            np.zeros(N), # calc. background (zero)
     93            np.zeros(N), # obs-calc profiles
     94            ]
     95        self.powderentry[0] = filename
     96        #self.powderentry[1] = pos # bank offset (N/A here)
     97        #self.powderentry[2] = 1 # xye file only has one bank
     98        self.idstring = ospath.basename(filename)
     99        # scan comments for temperature
     100        Temperature = 300
     101        for S in self.comments:
     102            if 'Temp' in S.split('=')[0]:
    66103                try:
    67                     x.append(float(vals[0]))
    68                     f = float(vals[1])
    69                     if f <= 0.0:
    70                         y.append(0.0)
    71                         w.append(0.0)
    72                     elif len(vals) == 3:
    73                         y.append(float(vals[1]))
    74                         w.append(1.0/float(vals[2])**2)
    75                     else:
    76                         y.append(float(vals[1]))
    77                         w.append(1.0/float(vals[1]))
    78                     err = False
    79                 except ValueError:
    80                     err = True
    81                     msg = 'Error parsing number in line '+str(i+1)
     104                    Temperature = float(S.split('=')[1])
    82105                except:
    83                     err = True
    84                     msg = 'Error in line '+str(i+1)
    85                 if err and i > 0:
    86                     print msg
    87                     print S
    88                     break
    89             N = len(x)
    90             self.powderdata = [
    91                 np.array(x), # x-axis values
    92                 np.array(y), # powder pattern intensities
    93                 np.array(w), # 1/sig(intensity)^2 values (weights)
    94                 np.zeros(N), # calc. intensities (zero)
    95                 np.zeros(N), # calc. background (zero)
    96                 np.zeros(N), # obs-calc profiles
    97                 ]
    98             self.powderentry[0] = filename
    99             #self.powderentry[1] = pos # bank offset (N/A here)
    100             #self.powderentry[2] = 1 # xye file only has one bank
    101             self.idstring = ospath.basename(filename)
    102             # scan comments for temperature
    103             Temperature = 300
    104             for S in self.comments:
    105                 if 'Temp' in S.split('=')[0]:
    106                     try:
    107                         Temperature = float(S.split('=')[1])
    108                     except:
    109                         pass
    110             self.Sample['Temperature'] = Temperature
     106                    pass
     107        self.Sample['Temperature'] = Temperature
    111108
    112             return True
    113         except Exception as detail:
    114             self.errors += '\n  '+str(detail)
    115             print self.formatName+' read error:'+str(detail) # for testing
    116             import traceback
    117             traceback.print_exc(file=sys.stdout)
    118             return False
     109        return True
  • trunk/imports/G2pwd_fxye.py

    r2516 r2738  
    244244        def Tmap2TOF(TMap,clockWd):
    245245            TOF = []
    246             chWdt = []
    247246            Tch,T,Step = TMap[0]
    248247            for tmap in TMap[1:]:
     
    253252            return TOF
    254253
    255         x = []
    256         y = []
    257         w = []
    258254        Banks = []
    259255        Pos = []
     
    275271        # in the input file.
    276272        if len(Banks) != len(Pos) or len(Banks) == 0:
    277             try:
    278                 i = -1
    279                 while True:
    280                     i += 1
    281                     S = filepointer.readline()
    282                     if len(S) == 0: break
    283                        
    284                     if i==0: # first line is always a comment
    285                         self.errors = 'Error reading title'
    286                         title = S[:-1]
    287                         comments = [[title,]]
    288                         continue
    289                     if i==1 and S[:4].lower() == 'inst' and ':' in S:
    290                         # 2nd line is instrument parameter file (optional)
    291                         self.errors = 'Error reading instrument parameter filename'
    292                         self.instparm = S.split(':')[1].strip('[]').strip()
    293                         continue
    294                     if S[0] == '#': # allow comments anywhere in the file
    295                         # comments in fact should only preceed BANK lines
    296                         comments[-1].append(S[:-1])
    297                         continue
    298                     if S[:4] == 'BANK':
    299                         self.errors = 'Error reading bank:'
    300                         self.errors += '  '+str(S)
    301                         comments.append([title,])
    302                         Banks.append(S)
    303                         Pos.append(filepointer.tell())
    304                     if S[:8] == 'TIME_MAP':     #assumes one time map; HIPPO has multiple time maps
    305                         if len(Banks) == 0:
    306                             self.errors = 'Error reading time map before any bank lines'
    307                         else:
    308                             self.errors = 'Error reading time map after bank:\n  '+str(Banks[-1])
    309                         timemap,clockwd,mapNo = GetTimeMap(filepointer,filepointer.tell(),S)
    310                         self.TimeMap[mapNo] = timemap
    311                         self.clockWd[mapNo] = clockwd
    312                        
    313             except Exception as detail:
    314                 self.errors += '\n  '+str(detail)
    315                 print self.formatName+' scan error:'+str(detail) # for testing
    316                 import traceback
    317                 traceback.print_exc(file=sys.stdout)
    318                 return False
     273            i = -1
     274            while True:
     275                i += 1
     276                S = filepointer.readline()
     277                if len(S) == 0: break
     278                   
     279                if i==0: # first line is always a comment
     280                    self.errors = 'Error reading title'
     281                    title = S[:-1]
     282                    comments = [[title,]]
     283                    continue
     284                if i==1 and S[:4].lower() == 'inst' and ':' in S:
     285                    # 2nd line is instrument parameter file (optional)
     286                    self.errors = 'Error reading instrument parameter filename'
     287                    self.instparm = S.split(':')[1].strip('[]').strip()
     288                    continue
     289                if S[0] == '#': # allow comments anywhere in the file
     290                    # comments in fact should only preceed BANK lines
     291                    comments[-1].append(S[:-1])
     292                    continue
     293                if S[:4] == 'BANK':
     294                    self.errors = 'Error reading bank:'
     295                    self.errors += '  '+str(S)
     296                    comments.append([title,])
     297                    Banks.append(S)
     298                    Pos.append(filepointer.tell())
     299                if S[:8] == 'TIME_MAP':     #assumes one time map; HIPPO has multiple time maps
     300                    if len(Banks) == 0:
     301                        self.errors = 'Error reading time map before any bank lines'
     302                    else:
     303                        self.errors = 'Error reading time map after bank:\n  '+str(Banks[-1])
     304                    timemap,clockwd,mapNo = GetTimeMap(filepointer,filepointer.tell(),S)
     305                    self.TimeMap[mapNo] = timemap
     306                    self.clockWd[mapNo] = clockwd
     307                   
    319308
    320309        # Now select the bank to read
     
    359348        except ValueError:
    360349            bnkNo = 1
    361         try:
    362             if 'FXYE' in Bank:
    363                 self.errors = 'Error reading FXYE data in Bank\n  '+Banks[selblk]
    364                 self.powderdata = GetFXYEdata(filepointer,Pos[selblk],Banks[selblk])
    365             elif 'FXY' in Bank:
    366                 self.errors = 'Error reading FXY data in Bank\n  '+Banks[selblk]
    367                 self.powderdata = GetFXYdata(filepointer,Pos[selblk],Banks[selblk])
    368             elif 'ESD' in Bank:
    369                 self.errors = 'Error reading ESD data in Bank\n  '+Banks[selblk]
    370                 self.powderdata = GetESDdata(filepointer,Pos[selblk],Banks[selblk])
    371             elif 'STD' in Bank:
    372                 self.errors = 'Error reading STD data in Bank\n  '+Banks[selblk]
    373                 self.powderdata = GetSTDdata(filepointer,Pos[selblk],Banks[selblk])
    374             elif 'ALT' in Bank:
    375                 self.errors = 'Error reading ALT data in Bank\n  '+Banks[selblk]
    376                 self.powderdata = GetALTdata(filepointer,Pos[selblk],Banks[selblk])
    377             else:
    378                 self.errors = 'Error reading STD data in Bank\n  '+Banks[selblk]
    379                 self.powderdata = GetSTDdata(filepointer,Pos[selblk],Banks[selblk])
    380         except Exception as detail:
    381             self.errors += '\n  '+str(detail)
    382             print self.formatName+' read error:'+str(detail) # for testing
    383             import traceback
    384             traceback.print_exc(file=sys.stdout)
    385             return False
     350        if 'FXYE' in Bank:
     351            self.errors = 'Error reading FXYE data in Bank\n  '+Banks[selblk]
     352            self.powderdata = GetFXYEdata(filepointer,Pos[selblk],Banks[selblk])
     353        elif 'FXY' in Bank:
     354            self.errors = 'Error reading FXY data in Bank\n  '+Banks[selblk]
     355            self.powderdata = GetFXYdata(filepointer,Pos[selblk],Banks[selblk])
     356        elif 'ESD' in Bank:
     357            self.errors = 'Error reading ESD data in Bank\n  '+Banks[selblk]
     358            self.powderdata = GetESDdata(filepointer,Pos[selblk],Banks[selblk])
     359        elif 'STD' in Bank:
     360            self.errors = 'Error reading STD data in Bank\n  '+Banks[selblk]
     361            self.powderdata = GetSTDdata(filepointer,Pos[selblk],Banks[selblk])
     362        elif 'ALT' in Bank:
     363            self.errors = 'Error reading ALT data in Bank\n  '+Banks[selblk]
     364            self.powderdata = GetALTdata(filepointer,Pos[selblk],Banks[selblk])
     365        else:
     366            self.errors = 'Error reading STD data in Bank\n  '+Banks[selblk]
     367            self.powderdata = GetSTDdata(filepointer,Pos[selblk],Banks[selblk])
    386368
    387369        self.errors = 'Error processing information after read complete'
  • trunk/imports/G2pwd_xye.py

    r2516 r2738  
    1515'''
    1616
    17 import sys
    1817import os.path as ospath
    1918import numpy as np
     
    7170        y = []
    7271        w = []
    73         try:
    74             gotCcomment = False
    75             begin = True
    76             for i,S in enumerate(filepointer):
    77                 self.errors = 'Error reading line: '+str(i+1)
    78                 # or a block of comments delimited by /* and */
    79                 # or (GSAS style) each line can begin with '#'
    80                 if begin:
    81                     if gotCcomment and S.find('*/') > -1:
    82                         self.comments.append(S[:-1])
    83                         begin = False
    84                         continue
    85                     if S.strip().startswith('/*'):
    86                         self.comments.append(S[:-1])
    87                         gotCcomment = True
    88                         continue   
    89                     if S[0] in ["'",'#']:
    90                         self.comments.append(S[:-1])
    91                         continue       #ignore comments, if any
    92                     else:
    93                         begin = False
    94                 # valid line to read
    95                 #vals = S.split()
    96                 vals = S.replace(',',' ').replace(';',' ').split()
    97                 if len(vals) < 2:
    98                     print 'Line '+str(i+1)+' cannot be read:\n\t'+S
     72        gotCcomment = False
     73        begin = True
     74        for i,S in enumerate(filepointer):
     75            self.errors = 'Error reading line: '+str(i+1)
     76            # or a block of comments delimited by /* and */
     77            # or (GSAS style) each line can begin with '#'
     78            if begin:
     79                if gotCcomment and S.find('*/') > -1:
     80                    self.comments.append(S[:-1])
     81                    begin = False
    9982                    continue
     83                if S.strip().startswith('/*'):
     84                    self.comments.append(S[:-1])
     85                    gotCcomment = True
     86                    continue   
     87                if S[0] in ["'",'#']:
     88                    self.comments.append(S[:-1])
     89                    continue       #ignore comments, if any
     90                else:
     91                    begin = False
     92            # valid line to read
     93            #vals = S.split()
     94            vals = S.replace(',',' ').replace(';',' ').split()
     95            if len(vals) < 2:
     96                print 'Line '+str(i+1)+' cannot be read:\n\t'+S
     97                continue
     98            try:
     99                x.append(float(vals[0]))
     100                f = float(vals[1])
     101                if f <= 0.0:
     102                    y.append(0.0)
     103                    w.append(0.0)
     104                elif len(vals) == 3:
     105                    y.append(float(vals[1]))
     106                    w.append(1.0/float(vals[2])**2)
     107                else:
     108                    y.append(float(vals[1]))
     109                    w.append(1.0/float(vals[1]))
     110            except ValueError:
     111                msg = 'Error parsing number in line '+str(i+1)
     112                print msg
     113                print S
     114                break
     115            except:
     116                msg = 'Error in line '+str(i+1)
     117                print msg
     118                print S
     119                break
     120        N = len(x)
     121        self.powderdata = [
     122            np.array(x), # x-axis values
     123            np.array(y), # powder pattern intensities
     124            np.array(w), # 1/sig(intensity)^2 values (weights)
     125            np.zeros(N), # calc. intensities (zero)
     126            np.zeros(N), # calc. background (zero)
     127            np.zeros(N), # obs-calc profiles
     128            ]
     129        self.powderentry[0] = filename
     130        #self.powderentry[1] = pos # bank offset (N/A here)
     131        #self.powderentry[2] = 1 # xye file only has one bank
     132        self.idstring = ospath.basename(filename)
     133        # scan comments for temperature
     134        Temperature = 300
     135        for S in self.comments:
     136            if 'Temp' in S.split('=')[0]:
    100137                try:
    101                     x.append(float(vals[0]))
    102                     f = float(vals[1])
    103                     if f <= 0.0:
    104                         y.append(0.0)
    105                         w.append(0.0)
    106                     elif len(vals) == 3:
    107                         y.append(float(vals[1]))
    108                         w.append(1.0/float(vals[2])**2)
    109                     else:
    110                         y.append(float(vals[1]))
    111                         w.append(1.0/float(vals[1]))
    112                 except ValueError:
    113                     msg = 'Error parsing number in line '+str(i+1)
    114                     print msg
    115                     print S
    116                     break
     138                    Temperature = float(S.split('=')[1])
    117139                except:
    118                     msg = 'Error in line '+str(i+1)
    119                     print msg
    120                     print S
    121                     break
    122             N = len(x)
    123             self.powderdata = [
    124                 np.array(x), # x-axis values
    125                 np.array(y), # powder pattern intensities
    126                 np.array(w), # 1/sig(intensity)^2 values (weights)
    127                 np.zeros(N), # calc. intensities (zero)
    128                 np.zeros(N), # calc. background (zero)
    129                 np.zeros(N), # obs-calc profiles
    130                 ]
    131             self.powderentry[0] = filename
    132             #self.powderentry[1] = pos # bank offset (N/A here)
    133             #self.powderentry[2] = 1 # xye file only has one bank
    134             self.idstring = ospath.basename(filename)
    135             # scan comments for temperature
    136             Temperature = 300
    137             for S in self.comments:
    138                 if 'Temp' in S.split('=')[0]:
    139                     try:
    140                         Temperature = float(S.split('=')[1])
    141                     except:
    142                         pass
    143             self.Sample['Temperature'] = Temperature
     140                    pass
     141        self.Sample['Temperature'] = Temperature
    144142
    145             return True
    146         except Exception as detail:
    147             self.errors += '\n  '+str(detail)
    148             print self.formatName+' read error:'+str(detail) # for testing
    149             import traceback
    150             traceback.print_exc(file=sys.stdout)
    151             return False
    152 
     143        return True
  • trunk/imports/G2sad_xye.py

    r1300 r2738  
    5656        y = []
    5757        w = []
    58         try:
    59             wave = 1.5428   #Cuka default
    60             Temperature = 300
    61             Ndata = 0
    62             for i,S in enumerate(filepointer):
    63                 if len(S) == 1:     #skip blank line
    64                     continue
    65                 if '=' in S:
    66                     self.comments.append(S[:-1])
    67                     if 'wave' in S.split('=')[0].lower():
    68                         try:
    69                             wave = float(S.split('=')[1])
    70                         except:
    71                             pass
    72                     continue
    73                 vals = S.split()
    74                 if len(vals) >= 2:
     58        wave = 1.5428   #Cuka default
     59        Temperature = 300
     60        for i,S in enumerate(filepointer):
     61            if len(S) == 1:     #skip blank line
     62                continue
     63            if '=' in S:
     64                self.comments.append(S[:-1])
     65                if 'wave' in S.split('=')[0].lower():
    7566                    try:
    76                         data = [float(val) for val in vals]
    77                         x.append(float(data[0]))
    78                         f = float(data[1])
    79                         if f <= 0.0:
    80                             del x[-1]
    81                             continue
    82                         elif len(vals) > 2:
    83                             y.append(float(data[1]))
    84                             w.append(1.0/float(data[2])**2)
    85                         else:
    86                             y.append(float(data[1]))
    87                             w.append(1.0/float(data[1]))
    88                     except ValueError:
    89                         msg = 'Error in line '+str(i+1)
    90                         print msg
    91                         continue
    92             N = len(x)
    93             for S in self.comments:
    94                 if 'Temp' in S.split('=')[0]:
    95                     try:
    96                         Temperature = float(S.split('=')[1])
     67                        wave = float(S.split('=')[1])
    9768                    except:
    9869                        pass
    99             self.instdict['wave'] = wave
    100             self.instdict['type'] = 'LXC'
    101             x = np.array(x)
    102             self.smallangledata = [
    103                 x, # x-axis values q
    104                 np.array(y), # small angle pattern intensities
    105                 np.array(w), # 1/sig(intensity)^2 values (weights)
    106                 np.zeros(N), # calc. intensities (zero)
    107                 np.zeros(N), # obs-calc profiles
    108                 np.zeros(N), # fix bkg
    109                 ]
    110             self.smallangleentry[0] = filename
    111             self.smallangleentry[2] = 1 # xye file only has one bank
    112             self.idstring = ospath.basename(filename)
    113             # scan comments for temperature
    114             self.Sample['Temperature'] = Temperature
    115    
    116             return True
    117         except Exception as detail:
    118             self.errors += '\n  '+str(detail)
    119             print self.formatName+' read error:'+str(detail) # for testing
    120             import traceback
    121             traceback.print_exc(file=sys.stdout)
    122             return False
     70                continue
     71            vals = S.split()
     72            if len(vals) >= 2:
     73                try:
     74                    data = [float(val) for val in vals]
     75                    x.append(float(data[0]))
     76                    f = float(data[1])
     77                    if f <= 0.0:
     78                        del x[-1]
     79                        continue
     80                    elif len(vals) > 2:
     81                        y.append(float(data[1]))
     82                        w.append(1.0/float(data[2])**2)
     83                    else:
     84                        y.append(float(data[1]))
     85                        w.append(1.0/float(data[1]))
     86                except ValueError:
     87                    msg = 'Error in line '+str(i+1)
     88                    print msg
     89                    continue
     90        N = len(x)
     91        for S in self.comments:
     92            if 'Temp' in S.split('=')[0]:
     93                try:
     94                    Temperature = float(S.split('=')[1])
     95                except:
     96                    pass
     97        self.instdict['wave'] = wave
     98        self.instdict['type'] = 'LXC'
     99        x = np.array(x)
     100        self.smallangledata = [
     101            x, # x-axis values q
     102            np.array(y), # small angle pattern intensities
     103            np.array(w), # 1/sig(intensity)^2 values (weights)
     104            np.zeros(N), # calc. intensities (zero)
     105            np.zeros(N), # obs-calc profiles
     106            np.zeros(N), # fix bkg
     107            ]
     108        self.smallangleentry[0] = filename
     109        self.smallangleentry[2] = 1 # xye file only has one bank
     110        self.idstring = ospath.basename(filename)
     111        # scan comments for temperature
     112        self.Sample['Temperature'] = Temperature
     113
     114        return True
    123115
    124116class txt_nmXRayReaderClass(G2IO.ImportSmallAngleData):
     
    154146        y = []
    155147        w = []
    156         try:
    157             wave = 1.5428   #Cuka default
    158             Temperature = 300
    159             Ndata = 0
    160             for i,S in enumerate(filepointer):
    161                 if len(S) == 1:     #skip blank line
    162                     continue
    163                 if '=' in S:
    164                     self.comments.append(S[:-1])
    165                     if 'wave' in S.split('=')[0].lower():
    166                         try:
    167                             wave = float(S.split('=')[1])
    168                         except:
    169                             pass
    170                     continue
    171                 vals = S.split()
    172                 if len(vals) >= 2:
     148        wave = 1.5428   #Cuka default
     149        Temperature = 300
     150        for i,S in enumerate(filepointer):
     151            if len(S) == 1:     #skip blank line
     152                continue
     153            if '=' in S:
     154                self.comments.append(S[:-1])
     155                if 'wave' in S.split('=')[0].lower():
    173156                    try:
    174                         data = [float(val) for val in vals]
    175                         x.append(float(data[0])/10.)        #convert nm-1 to A-1
    176                         f = float(data[1])
    177                         if f <= 0.0:
    178                             x.pop()
    179                             continue
    180                         elif len(vals) > 2:
    181                             y.append(float(data[1]))
    182                             w.append(1.0/float(data[2])**2)
    183                         else:
    184                             y.append(float(data[1]))
    185                             w.append(1.0/float(data[1]))
    186                     except ValueError:
    187                         msg = 'Error in line '+str(i+1)
    188                         print msg
    189                         continue
    190             N = len(x)
    191             for S in self.comments:
    192                 if 'Temp' in S.split('=')[0]:
    193                     try:
    194                         Temperature = float(S.split('=')[1])
     157                        wave = float(S.split('=')[1])
    195158                    except:
    196159                        pass
    197             self.instdict['wave'] = wave
    198             self.instdict['type'] = 'LXC'
    199             x = np.array(x)
    200             self.smallangledata = [
    201                 x, # x-axis values q
    202                 np.array(y), # small angle pattern intensities
    203                 np.array(w), # 1/sig(intensity)^2 values (weights)
    204                 np.zeros(N), # calc. intensities (zero)
    205                 np.zeros(N), # obs-calc profiles
    206                 np.zeros(N), # fix bkg
    207                 ]
    208             self.smallangleentry[0] = filename
    209             self.smallangleentry[2] = 1 # xye file only has one bank
    210             self.idstring = ospath.basename(filename)
    211             # scan comments for temperature
    212             self.Sample['Temperature'] = Temperature
    213    
    214             return True
    215         except Exception as detail:
    216             self.errors += '\n  '+str(detail)
    217             print self.formatName+' read error:'+str(detail) # for testing
    218             import traceback
    219             traceback.print_exc(file=sys.stdout)
    220             return False
     160                continue
     161            vals = S.split()
     162            if len(vals) >= 2:
     163                try:
     164                    data = [float(val) for val in vals]
     165                    x.append(float(data[0])/10.)        #convert nm-1 to A-1
     166                    f = float(data[1])
     167                    if f <= 0.0:
     168                        x.pop()
     169                        continue
     170                    elif len(vals) > 2:
     171                        y.append(float(data[1]))
     172                        w.append(1.0/float(data[2])**2)
     173                    else:
     174                        y.append(float(data[1]))
     175                        w.append(1.0/float(data[1]))
     176                except ValueError:
     177                    msg = 'Error in line '+str(i+1)
     178                    print msg
     179                    continue
     180        N = len(x)
     181        for S in self.comments:
     182            if 'Temp' in S.split('=')[0]:
     183                try:
     184                    Temperature = float(S.split('=')[1])
     185                except:
     186                    pass
     187        self.instdict['wave'] = wave
     188        self.instdict['type'] = 'LXC'
     189        x = np.array(x)
     190        self.smallangledata = [
     191            x, # x-axis values q
     192            np.array(y), # small angle pattern intensities
     193            np.array(w), # 1/sig(intensity)^2 values (weights)
     194            np.zeros(N), # calc. intensities (zero)
     195            np.zeros(N), # obs-calc profiles
     196            np.zeros(N), # fix bkg
     197            ]
     198        self.smallangleentry[0] = filename
     199        self.smallangleentry[2] = 1 # xye file only has one bank
     200        self.idstring = ospath.basename(filename)
     201        # scan comments for temperature
     202        self.Sample['Temperature'] = Temperature
     203
     204        return True
    221205
    222206class txt_CWNeutronReaderClass(G2IO.ImportSmallAngleData):
     
    252236        y = []
    253237        w = []
    254         try:
    255             wave = 1.5428   #Cuka default
    256             Temperature = 300
    257             Ndata = 0
    258             for i,S in enumerate(filepointer):
    259                 if len(S) == 1:     #skip blank line
    260                     continue
    261                 if '=' in S:
    262                     self.comments.append(S[:-1])
    263                     if 'wave' in S.split('=')[0].lower():
    264                         try:
    265                             wave = float(S.split('=')[1])
    266                         except:
    267                             pass
    268                     continue
    269                 vals = S.split()
    270                 if len(vals) >= 2:
     238        wave = 1.5428   #Cuka default
     239        Temperature = 300
     240        for i,S in enumerate(filepointer):
     241            if len(S) == 1:     #skip blank line
     242                continue
     243            if '=' in S:
     244                self.comments.append(S[:-1])
     245                if 'wave' in S.split('=')[0].lower():
    271246                    try:
    272                         data = [float(val) for val in vals]
    273                         x.append(float(data[0]))
    274                         f = float(data[1])
    275                         if f <= 0.0:
    276                             y.append(0.0)
    277                             w.append(1.0)
    278                         elif len(vals) > 2:
    279                             y.append(float(data[1]))
    280                             w.append(1.0/float(data[2])**2)
    281                         else:
    282                             y.append(float(data[1]))
    283                             w.append(1.0/float(data[1]))
    284                     except ValueError:
    285                         msg = 'Error in line '+str(i+1)
    286                         print msg
    287                         continue
    288             N = len(x)
    289             for S in self.comments:
    290                 if 'Temp' in S.split('=')[0]:
    291                     try:
    292                         Temperature = float(S.split('=')[1])
     247                        wave = float(S.split('=')[1])
    293248                    except:
    294249                        pass
    295             self.instdict['wave'] = wave
    296             self.instdict['type'] = 'LNC'
    297             x = np.array(x)
    298             if np.any(x > 2.):         #q must be nm-1
    299                 x /= 10.
    300             self.smallangledata = [
    301                 x, # x-axis values q
    302                 np.array(y), # small angle pattern intensities
    303                 np.array(w), # 1/sig(intensity)^2 values (weights)
    304                 np.zeros(N), # calc. intensities (zero)
    305                 np.zeros(N), # obs-calc profiles
    306                 np.zeros(N), # fix bkg
    307                 ]
    308             self.smallangleentry[0] = filename
    309             self.smallangleentry[2] = 1 # xye file only has one bank
    310             self.idstring = ospath.basename(filename)
    311             # scan comments for temperature
    312             self.Sample['Temperature'] = Temperature
    313    
    314             return True
    315         except Exception as detail:
    316             self.errors += '\n  '+str(detail)
    317             print self.formatName+' read error:'+str(detail) # for testing
    318             import traceback
    319             traceback.print_exc(file=sys.stdout)
    320             return False
     250                continue
     251            vals = S.split()
     252            if len(vals) >= 2:
     253                try:
     254                    data = [float(val) for val in vals]
     255                    x.append(float(data[0]))
     256                    f = float(data[1])
     257                    if f <= 0.0:
     258                        y.append(0.0)
     259                        w.append(1.0)
     260                    elif len(vals) > 2:
     261                        y.append(float(data[1]))
     262                        w.append(1.0/float(data[2])**2)
     263                    else:
     264                        y.append(float(data[1]))
     265                        w.append(1.0/float(data[1]))
     266                except ValueError:
     267                    msg = 'Error in line '+str(i+1)
     268                    print msg
     269                    continue
     270        N = len(x)
     271        for S in self.comments:
     272            if 'Temp' in S.split('=')[0]:
     273                try:
     274                    Temperature = float(S.split('=')[1])
     275                except:
     276                    pass
     277        self.instdict['wave'] = wave
     278        self.instdict['type'] = 'LNC'
     279        x = np.array(x)
     280        if np.any(x > 2.):         #q must be nm-1
     281            x /= 10.
     282        self.smallangledata = [
     283            x, # x-axis values q
     284            np.array(y), # small angle pattern intensities
     285            np.array(w), # 1/sig(intensity)^2 values (weights)
     286            np.zeros(N), # calc. intensities (zero)
     287            np.zeros(N), # obs-calc profiles
     288            np.zeros(N), # fix bkg
     289            ]
     290        self.smallangleentry[0] = filename
     291        self.smallangleentry[2] = 1 # xye file only has one bank
     292        self.idstring = ospath.basename(filename)
     293        # scan comments for temperature
     294        self.Sample['Temperature'] = Temperature
     295
     296        return True
    321297
    322298class txt_nmCWNeutronReaderClass(G2IO.ImportSmallAngleData):
     
    352328        y = []
    353329        w = []
    354         try:
    355             wave = 1.5428   #Cuka default
    356             Temperature = 300
    357             Ndata = 0
    358             for i,S in enumerate(filepointer):
    359                 if len(S) == 1:     #skip blank line
    360                     continue
    361                 if '=' in S:
    362                     self.comments.append(S[:-1])
    363                     if 'wave' in S.split('=')[0].lower():
    364                         try:
    365                             wave = float(S.split('=')[1])
    366                         except:
    367                             pass
    368                     continue
    369                 vals = S.split()
    370                 if len(vals) >= 2:
     330        wave = 1.5428   #Cuka default
     331        Temperature = 300
     332        for i,S in enumerate(filepointer):
     333            if len(S) == 1:     #skip blank line
     334                continue
     335            if '=' in S:
     336                self.comments.append(S[:-1])
     337                if 'wave' in S.split('=')[0].lower():
    371338                    try:
    372                         data = [float(val) for val in vals]
    373                         x.append(float(data[0])/10.)    #convert to A-1
    374                         f = float(data[1])
    375                         if f <= 0.0:
    376                             y.append(0.0)
    377                             w.append(1.0)
    378                         elif len(vals) > 2:
    379                             y.append(float(data[1]))
    380                             w.append(1.0/float(data[2])**2)
    381                         else:
    382                             y.append(float(data[1]))
    383                             w.append(1.0/float(data[1]))
    384                     except ValueError:
    385                         msg = 'Error in line '+str(i+1)
    386                         print msg
    387                         continue
    388             N = len(x)
    389             for S in self.comments:
    390                 if 'Temp' in S.split('=')[0]:
    391                     try:
    392                         Temperature = float(S.split('=')[1])
     339                        wave = float(S.split('=')[1])
    393340                    except:
    394341                        pass
    395             self.instdict['wave'] = wave
    396             self.instdict['type'] = 'LNC'
    397             x = np.array(x)
    398             self.smallangledata = [
    399                 x, # x-axis values q
    400                 np.array(y), # small angle pattern intensities
    401                 np.array(w), # 1/sig(intensity)^2 values (weights)
    402                 np.zeros(N), # calc. intensities (zero)
    403                 np.zeros(N), # obs-calc profiles
    404                 np.zeros(N), # fix bkg
    405                 ]
    406             self.smallangleentry[0] = filename
    407             self.smallangleentry[2] = 1 # xye file only has one bank
    408             self.idstring = ospath.basename(filename)
    409             # scan comments for temperature
    410             self.Sample['Temperature'] = Temperature
    411    
    412             return True
    413         except Exception as detail:
    414             self.errors += '\n  '+str(detail)
    415             print self.formatName+' read error:'+str(detail) # for testing
    416             import traceback
    417             traceback.print_exc(file=sys.stdout)
    418             return False
     342                continue
     343            vals = S.split()
     344            if len(vals) >= 2:
     345                try:
     346                    data = [float(val) for val in vals]
     347                    x.append(float(data[0])/10.)    #convert to A-1
     348                    f = float(data[1])
     349                    if f <= 0.0:
     350                        y.append(0.0)
     351                        w.append(1.0)
     352                    elif len(vals) > 2:
     353                        y.append(float(data[1]))
     354                        w.append(1.0/float(data[2])**2)
     355                    else:
     356                        y.append(float(data[1]))
     357                        w.append(1.0/float(data[1]))
     358                except ValueError:
     359                    msg = 'Error in line '+str(i+1)
     360                    print msg
     361                    continue
     362        N = len(x)
     363        for S in self.comments:
     364            if 'Temp' in S.split('=')[0]:
     365                try:
     366                    Temperature = float(S.split('=')[1])
     367                except:
     368                    pass
     369        self.instdict['wave'] = wave
     370        self.instdict['type'] = 'LNC'
     371        x = np.array(x)
     372        self.smallangledata = [
     373            x, # x-axis values q
     374            np.array(y), # small angle pattern intensities
     375            np.array(w), # 1/sig(intensity)^2 values (weights)
     376            np.zeros(N), # calc. intensities (zero)
     377            np.zeros(N), # obs-calc profiles
     378            np.zeros(N), # fix bkg
     379            ]
     380        self.smallangleentry[0] = filename
     381        self.smallangleentry[2] = 1 # xye file only has one bank
     382        self.idstring = ospath.basename(filename)
     383        # scan comments for temperature
     384        self.Sample['Temperature'] = Temperature
     385
     386        return True
  • trunk/imports/G2sfact.py

    r2138 r2738  
    1616import sys
    1717import numpy as np
    18 import copy
    1918import GSASIIIO as G2IO
    2019import GSASIIpath
     
    6059    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
    6160        'Read the file'
    62         try:
    63             for line,S in enumerate(filepointer):
    64                 self.errors = '  Error reading line '+str(line+1)
    65                 if S[0] == '#': continue       #ignore comments, if any
    66                 h,k,l,Fo,sigFo = S.split()
    67                 h,k,l = [int(h),int(k),int(l)]
    68                 if not any([h,k,l]):
    69                     break
    70                 Fo = float(Fo)
    71                 sigFo = float(sigFo)
    72                 # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
    73                 self.RefDict['RefList'].append([h,k,l,1,0,Fo**2,2.*Fo*sigFo,0,Fo**2,0,0,0])
    74             self.errors = 'Error after reading reflections (unexpected!)'
    75             self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
    76             self.RefDict['Type'] = 'SXC'
    77             self.RefDict['Super'] = 0
    78             self.UpdateParameters(Type='SXC',Wave=None) # histogram type
    79             return True
    80         except Exception as detail:
    81             self.errors += '\n  '+str(detail)
    82             print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
    83             import traceback
    84             traceback.print_exc(file=sys.stdout)
    85             return False
     61        for line,S in enumerate(filepointer):
     62            self.errors = '  Error reading line '+str(line+1)
     63            if S[0] == '#': continue       #ignore comments, if any
     64            h,k,l,Fo,sigFo = S.split()
     65            h,k,l = [int(h),int(k),int(l)]
     66            if not any([h,k,l]):
     67                break
     68            Fo = float(Fo)
     69            sigFo = float(sigFo)
     70            # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
     71            self.RefDict['RefList'].append([h,k,l,1,0,Fo**2,2.*Fo*sigFo,0,Fo**2,0,0,0])
     72        self.errors = 'Error after reading reflections (unexpected!)'
     73        self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
     74        self.RefDict['Type'] = 'SXC'
     75        self.RefDict['Super'] = 0
     76        self.UpdateParameters(Type='SXC',Wave=None) # histogram type
     77        return True
    8678
    8779class HKLMF_ReaderClass(G2IO.ImportStructFactor):
     
    10193    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
    10294        'Read the file'
    103         try:
    104             for line,S in enumerate(filepointer):
    105                 self.errors = '  Error reading line '+str(line+1)
    106                 if S[0] == '#': continue       #ignore comments, if any
    107                 h,k,l,m,Fo= S.split()
    108                 h,k,l,m = [int(h),int(k),int(l),int(m)]
    109                 if h == 999 or not any([h,k,l]):
    110                     break
    111                 Fo = float(Fo)
    112                 sigFo2 = Fo
    113                 if Fo < 1.0:
    114                     sigFo2 = 1.0
    115                # h,k,l,m,tw,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
    116                 self.RefDict['RefList'].append([h,k,l,m,1,0,Fo**2,sigFo2,0,Fo**2,0,0,0])
    117             self.errors = 'Error after reading reflections (unexpected!)'
    118             self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
    119             self.RefDict['Type'] = 'SXC'
    120             self.RefDict['Super'] = 1
    121             self.UpdateParameters(Type='SXC',Wave=None) # histogram type
    122             return True
    123         except Exception as detail:
    124             self.errors += '\n  '+str(detail)
    125             print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
    126             import traceback
    127             traceback.print_exc(file=sys.stdout)
    128             return False
     95        for line,S in enumerate(filepointer):
     96            self.errors = '  Error reading line '+str(line+1)
     97            if S[0] == '#': continue       #ignore comments, if any
     98            h,k,l,m,Fo= S.split()
     99            h,k,l,m = [int(h),int(k),int(l),int(m)]
     100            if h == 999 or not any([h,k,l]):
     101                break
     102            Fo = float(Fo)
     103            sigFo2 = Fo
     104            if Fo < 1.0:
     105                sigFo2 = 1.0
     106           # h,k,l,m,tw,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
     107            self.RefDict['RefList'].append([h,k,l,m,1,0,Fo**2,sigFo2,0,Fo**2,0,0,0])
     108        self.errors = 'Error after reading reflections (unexpected!)'
     109        self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
     110        self.RefDict['Type'] = 'SXC'
     111        self.RefDict['Super'] = 1
     112        self.UpdateParameters(Type='SXC',Wave=None) # histogram type
     113        return True
    129114
    130115class SHELX4_ReaderClass(G2IO.ImportStructFactor):
     
    150135    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
    151136        'Read the file'
    152         try:
    153             for line,S in enumerate(filepointer):
    154                 self.errors = '  Error reading line '+str(line+1)
    155                 if S[0] == '#': continue       #ignore comments, if any
    156                 h,k,l = S[:12].split()
    157                 Fo,sigFo = S[12:].split()[:2]
     137        for line,S in enumerate(filepointer):
     138            self.errors = '  Error reading line '+str(line+1)
     139            if S[0] == '#': continue       #ignore comments, if any
     140            h,k,l = S[:12].split()
     141            Fo,sigFo = S[12:].split()[:2]
    158142#                h,k,l,Fo,sigFo = S[:4],S[4:8],S[8:12],S[12:20],S[20:28]
    159                 h,k,l = [int(h),int(k),int(l)]
    160                 if not any([h,k,l]):
    161                     break
    162                 Fo = float(Fo)
    163                 sigFo = float(sigFo)
    164                 # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
    165                 self.RefDict['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0])
    166                 #self.RefDict['FF'].append({}) # now done in OnImportSfact
    167             self.errors = 'Error after reading reflections (unexpected!)'
    168             self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
    169             self.RefDict['Type'] = 'SXC'
    170             self.RefDict['Super'] = 0
    171             self.UpdateParameters(Type='SXC',Wave=None) # histogram type
    172             return True
    173         except Exception as detail:
    174             self.errors += '\n  '+str(detail)
    175             print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
    176             import traceback
    177             traceback.print_exc(file=sys.stdout)
    178             return False
     143            h,k,l = [int(h),int(k),int(l)]
     144            if not any([h,k,l]):
     145                break
     146            Fo = float(Fo)
     147            sigFo = float(sigFo)
     148            # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
     149            self.RefDict['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0])
     150            #self.RefDict['FF'].append({}) # now done in OnImportSfact
     151        self.errors = 'Error after reading reflections (unexpected!)'
     152        self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
     153        self.RefDict['Type'] = 'SXC'
     154        self.RefDict['Super'] = 0
     155        self.UpdateParameters(Type='SXC',Wave=None) # histogram type
     156        return True
    179157           
    180158class SHELX5_ReaderClass(G2IO.ImportStructFactor):
     
    216194        TwMax = [-1,[]]
    217195        first = True
    218         try:
    219             for line,S in enumerate(filepointer):
    220                 self.errors = '  Error reading line '+str(line+1)
     196        for line,S in enumerate(filepointer):
     197            self.errors = '  Error reading line '+str(line+1)
     198            if self.Super == 0:
     199                SH = S[:12]
     200                SF = S[12:32]
     201                h,k,l = SH.split()
     202                Fo,sigFo,Tw = SF.split()
     203#                    h,k,l,Fo,sigFo,Tw = S[:4],S[4:8],S[8:12],S[12:20],S[20:28],S[28:32]
     204                h,k,l = [int(h),int(k),int(l)]
     205            elif self.Super == 1:
     206                SH = S[:16]
     207                SF = S[16:36]
     208                h,k,l,m1 = SH.split()
     209                Fo,sigFo,Tw = SF.split()
     210#                    h,k,l,m1,Fo,sigFo,Tw = S[:4],S[4:8],S[8:12],S[12:16],S[16:24],S[24:32],S[32:36]
     211                h,k,l,m1 = [int(h),int(k),int(l),int(m1)]
     212            Tw = Tw.strip()
     213            if Tw in ['','0']:
     214                Tw = '1'
     215            if not any([h,k,l]):
     216                break
     217            if '-' in Tw:
     218                if Tw == '-1':  #fix reversed twin ids
     219                    Tw = '-2'
     220                    if first:
     221                        self.warnings += '\nPrimary twin id changed to 1'
     222                        first = False
     223                TwId = -int(Tw)-1
     224                TwSet[TwId] = np.array([h,k,l])
     225                if TwId not in TwMax[1]:
     226                    TwMax[1].append(TwId)
     227            else:
     228                if Tw != '1':  #fix reversed twin ids
     229                    if first:
     230                        self.warnings += '\nPrimary twin id changed to 1\nNB: multiple primary twins not working'
     231                        first = False
     232                    Tw = '1'
     233                TwId = int(Tw)-1
     234                if TwSet:
     235                    TwDict[len(self.RefDict['RefList'])] = TwSet
     236                    TwSet = {}   
     237                Fo = float(Fo)
     238                sigFo = float(sigFo)
     239                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
    221240                if self.Super == 0:
    222                     SH = S[:12]
    223                     SF = S[12:32]
    224                     h,k,l = SH.split()
    225                     Fo,sigFo,Tw = SF.split()
    226 #                    h,k,l,Fo,sigFo,Tw = S[:4],S[4:8],S[8:12],S[12:20],S[20:28],S[28:32]
    227                     h,k,l = [int(h),int(k),int(l)]
     241                    self.RefDict['RefList'].append([h,k,l,int(Tw),0,Fo,sigFo,0,Fo,0,0,0])
    228242                elif self.Super == 1:
    229                     SH = S[:16]
    230                     SF = S[16:36]
    231                     h,k,l,m1 = SH.split()
    232                     Fo,sigFo,Tw = SF.split()
    233 #                    h,k,l,m1,Fo,sigFo,Tw = S[:4],S[4:8],S[8:12],S[12:16],S[16:24],S[24:32],S[32:36]
    234                     h,k,l,m1 = [int(h),int(k),int(l),int(m1)]
    235                 Tw = Tw.strip()
    236                 if Tw in ['','0']:
    237                     Tw = '1'
    238                 if not any([h,k,l]):
    239                     break
    240                 if '-' in Tw:
    241                     if Tw == '-1':  #fix reversed twin ids
    242                         Tw = '-2'
    243                         if first:
    244                             self.warnings += '\nPrimary twin id changed to 1'
    245                             first = False
    246                     TwId = -int(Tw)-1
    247                     TwSet[TwId] = np.array([h,k,l])
    248                     if TwId not in TwMax[1]:
    249                         TwMax[1].append(TwId)
    250                 else:
    251                     if Tw != '1':  #fix reversed twin ids
    252                         if first:
    253                             self.warnings += '\nPrimary twin id changed to 1\nNB: multiple primary twins not working'
    254                             first = False
    255                         Tw = '1'
    256                     TwId = int(Tw)-1
    257                     if TwSet:
    258                         TwDict[len(self.RefDict['RefList'])] = TwSet
    259                         TwSet = {}   
    260                     Fo = float(Fo)
    261                     sigFo = float(sigFo)
    262                     # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
    263                     if self.Super == 0:
    264                         self.RefDict['RefList'].append([h,k,l,int(Tw),0,Fo,sigFo,0,Fo,0,0,0])
    265                     elif self.Super == 1:
    266                         self.RefDict['RefList'].append([h,k,l,m1,int(Tw),0,Fo,sigFo,0,Fo,0,0,0])
    267                 TwMax[0] = max(TwMax[0],TwId)
    268             self.errors = 'Error after reading reflections (unexpected!)'
    269             self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
    270             self.RefDict['Type'] = 'SXC'
    271             self.RefDict['Super'] = self.Super
    272             self.RefDict['TwDict'] = TwDict
    273             self.RefDict['TwMax'] = TwMax
    274             self.UpdateParameters(Type='SXC',Wave=None) # histogram type
    275             return True
    276         except Exception as detail:
    277             self.errors += '\n  '+str(detail)
    278             print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
    279             import traceback
    280             traceback.print_exc(file=sys.stdout)
    281             return False
     243                    self.RefDict['RefList'].append([h,k,l,m1,int(Tw),0,Fo,sigFo,0,Fo,0,0,0])
     244            TwMax[0] = max(TwMax[0],TwId)
     245        self.errors = 'Error after reading reflections (unexpected!)'
     246        self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
     247        self.RefDict['Type'] = 'SXC'
     248        self.RefDict['Super'] = self.Super
     249        self.RefDict['TwDict'] = TwDict
     250        self.RefDict['TwMax'] = TwMax
     251        self.UpdateParameters(Type='SXC',Wave=None) # histogram type
     252        return True
    282253
    283254class SHELX6_ReaderClass(G2IO.ImportStructFactor):
     
    320291        TwMax = [-1,[]]
    321292        first = True
    322         try:
    323             for line,S in enumerate(filepointer):
    324                 self.errors = '  Error reading line '+str(line+1)
    325                 h,k,l,m1,m2,m3,Fo,sigFo,Tw = S[:4],S[4:8],S[8:12],S[12:16],S[16:20],S[20:24],S[24:32],S[32:40],S[40:44]
    326                 h,k,l,m1,m2,m3 = [int(h),int(k),int(l),int(m1),int(m2),int(m3)]
    327                 if m2 or m3:
    328                     self.warnings += '\n(3+2) & (3+3) Supersymmetry not allowed in GSAS-II. Reformulate as twinned (3+1) supersymmetry'
    329                     raise self.ImportException("Supersymmetry too high; GSAS-II limited to (3+1) supersymmetry")                               
    330                 Tw = Tw.strip()
    331                 if Tw in ['','0']:
     293        for line,S in enumerate(filepointer):
     294            self.errors = '  Error reading line '+str(line+1)
     295            h,k,l,m1,m2,m3,Fo,sigFo,Tw = S[:4],S[4:8],S[8:12],S[12:16],S[16:20],S[20:24],S[24:32],S[32:40],S[40:44]
     296            h,k,l,m1,m2,m3 = [int(h),int(k),int(l),int(m1),int(m2),int(m3)]
     297            if m2 or m3:
     298                self.warnings += '\n(3+2) & (3+3) Supersymmetry not allowed in GSAS-II. Reformulate as twinned (3+1) supersymmetry'
     299                raise self.ImportException("Supersymmetry too high; GSAS-II limited to (3+1) supersymmetry")                               
     300            Tw = Tw.strip()
     301            if Tw in ['','0']:
     302                Tw = '1'
     303            if not any([h,k,l]):    #look for 0 0 0 or blank line
     304                break
     305            if '-' in Tw:
     306                if Tw == '-1':  #fix reversed twin ids
     307                    Tw = '-2'
     308                    if first:
     309                        self.warnings += '\nPrimary twin id changed to 1'
     310                        first = False
     311                TwId = -int(Tw)-1
     312                TwSet[TwId] = np.array([h,k,l])
     313                if TwId not in TwMax[1]:
     314                    TwMax[1].append(TwId)
     315            else:
     316                if Tw != '1':  #fix reversed twin ids
     317                    if first:
     318                        self.warnings += '\nPrimary twin id changed to 1\nNB: multiple primary twins not working'
     319                        first = False
    332320                    Tw = '1'
    333                 if not any([h,k,l]):    #look for 0 0 0 or blank line
    334                     break
    335                 if '-' in Tw:
    336                     if Tw == '-1':  #fix reversed twin ids
    337                         Tw = '-2'
    338                         if first:
    339                             self.warnings += '\nPrimary twin id changed to 1'
    340                             first = False
    341                     TwId = -int(Tw)-1
    342                     TwSet[TwId] = np.array([h,k,l])
    343                     if TwId not in TwMax[1]:
    344                         TwMax[1].append(TwId)
    345                 else:
    346                     if Tw != '1':  #fix reversed twin ids
    347                         if first:
    348                             self.warnings += '\nPrimary twin id changed to 1\nNB: multiple primary twins not working'
    349                             first = False
    350                         Tw = '1'
    351                     TwId = int(Tw)-1
    352                     if TwSet:
    353                         TwDict[len(self.RefDict['RefList'])] = TwSet
    354                         TwSet = {}   
    355                     Fo = float(Fo)
    356                     sigFo = float(sigFo)
    357                     # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
    358                     self.RefDict['RefList'].append([h,k,l,m1,int(Tw),0,Fo,sigFo,0,Fo,0,0,0])
    359                 TwMax[0] = max(TwMax[0],TwId)
    360             self.errors = 'Error after reading reflections (unexpected!)'
    361             self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
    362             self.RefDict['Type'] = 'SXC'
    363             self.RefDict['Super'] = self.Super
    364             self.RefDict['TwDict'] = TwDict
    365             self.RefDict['TwMax'] = TwMax
    366             self.UpdateParameters(Type='SXC',Wave=None) # histogram type
    367             return True
    368         except Exception as detail:
    369             self.errors += '\n  '+str(detail)
    370             print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
    371             import traceback
    372             traceback.print_exc(file=sys.stdout)
    373             return False
     321                TwId = int(Tw)-1
     322                if TwSet:
     323                    TwDict[len(self.RefDict['RefList'])] = TwSet
     324                    TwSet = {}   
     325                Fo = float(Fo)
     326                sigFo = float(sigFo)
     327                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
     328                self.RefDict['RefList'].append([h,k,l,m1,int(Tw),0,Fo,sigFo,0,Fo,0,0,0])
     329            TwMax[0] = max(TwMax[0],TwId)
     330        self.errors = 'Error after reading reflections (unexpected!)'
     331        self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
     332        self.RefDict['Type'] = 'SXC'
     333        self.RefDict['Super'] = self.Super
     334        self.RefDict['TwDict'] = TwDict
     335        self.RefDict['TwMax'] = TwMax
     336        self.UpdateParameters(Type='SXC',Wave=None) # histogram type
     337        return True
    374338
    375339class M90_ReaderClass(G2IO.ImportStructFactor):
     
    407371    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
    408372        'Read the file'
    409         try:
    410             for line,S in enumerate(filepointer):
    411                 self.errors = '  Error reading line '+str(line+1)
    412                 if S[0] == '#': continue       #ignore comments, if any
    413                 try:
    414                     if self.Super == 0:
    415                         h,k,l,Fo,sigFo = S.split()[:5]
    416                         h,k,l = [int(h),int(k),int(l)]
    417                     elif self.Super == 1:
    418                         h,k,l,m1,Fo,sigFo = S.split()[:6]
    419                         h,k,l,m1 = [int(h),int(k),int(l),int(m1)]
    420                 except ValueError:  #skipping text at front
    421                     if not S:
    422                         break
    423                     text = S.split()
    424                     if text[0] == 'lambda':
    425                         wave = float(text[1])
    426                     continue
    427                 Fo = float(Fo)
    428                 sigFo = float(sigFo)
    429                 # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
     373        for line,S in enumerate(filepointer):
     374            self.errors = '  Error reading line '+str(line+1)
     375            if S[0] == '#': continue       #ignore comments, if any
     376            try:
    430377                if self.Super == 0:
    431                     self.RefDict['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0])
     378                    h,k,l,Fo,sigFo = S.split()[:5]
     379                    h,k,l = [int(h),int(k),int(l)]
    432380                elif self.Super == 1:
    433                     self.RefDict['RefList'].append([h,k,l,m1,1,0,Fo,sigFo,0,Fo,0,0,0])
    434             self.errors = 'Error after reading reflections (unexpected!)'
    435             self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
    436             self.RefDict['Type'] = 'SXC'
    437             self.RefDict['Super'] = self.Super
    438             self.UpdateParameters(Type='SXC',Wave=wave) # histogram type
    439             return True
    440         except Exception as detail:
    441             self.errors += '\n  '+str(detail)
    442             print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
    443             import traceback
    444             traceback.print_exc(file=sys.stdout)
    445             return False
     381                    h,k,l,m1,Fo,sigFo = S.split()[:6]
     382                    h,k,l,m1 = [int(h),int(k),int(l),int(m1)]
     383            except ValueError:  #skipping text at front
     384                if not S:
     385                    break
     386                text = S.split()
     387                if text[0] == 'lambda':
     388                    wave = float(text[1])
     389                continue
     390            Fo = float(Fo)
     391            sigFo = float(sigFo)
     392            # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
     393            if self.Super == 0:
     394                self.RefDict['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0])
     395            elif self.Super == 1:
     396                self.RefDict['RefList'].append([h,k,l,m1,1,0,Fo,sigFo,0,Fo,0,0,0])
     397        self.errors = 'Error after reading reflections (unexpected!)'
     398        self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
     399        self.RefDict['Type'] = 'SXC'
     400        self.RefDict['Super'] = self.Super
     401        self.UpdateParameters(Type='SXC',Wave=wave) # histogram type
     402        return True
    446403           
    447404class NT_HKLF2_ReaderClass(G2IO.ImportStructFactor):
     
    479436        'Read the file'
    480437        filepointer.seek(0)
    481         try:
    482             for line,S in enumerate(filepointer):
    483                 self.errors = '  Error reading line '+str(line+1)
    484                 if S[0] == '#': continue       #ignore comments, if any
    485                 data = S.split()
    486                 h,k,l,Fo,sigFo,bN,wave,tbar = data[:8]  #bN = 1..., 6 dir cos next                   
    487                 h,k,l = [int(h),int(k),int(l)]
    488                 if not any([h,k,l]):
    489                     break
    490                 Fo = float(Fo)
    491                 sigFo = float(sigFo)
    492                 wave = float(wave)
    493                 tbar = float(tbar)
    494                 if len(self.Banks):
    495                     self.Banks[int(bN)-1]['RefDict']['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
    496                 else:
    497                 # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
    498                     self.RefDict['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
     438        for line,S in enumerate(filepointer):
     439            self.errors = '  Error reading line '+str(line+1)
     440            if S[0] == '#': continue       #ignore comments, if any
     441            data = S.split()
     442            h,k,l,Fo,sigFo,bN,wave,tbar = data[:8]  #bN = 1..., 6 dir cos next                   
     443            h,k,l = [int(h),int(k),int(l)]
     444            if not any([h,k,l]):
     445                break
     446            Fo = float(Fo)
     447            sigFo = float(sigFo)
     448            wave = float(wave)
     449            tbar = float(tbar)
    499450            if len(self.Banks):
    500                 self.UpdateParameters(Type='SNT',Wave=None) # histogram type
    501                 for Bank in self.Banks:
    502                     Bank['RefDict']['RefList'] = np.array(Bank['RefDict']['RefList'])
    503                     Bank['RefDict']['Type'] = 'SNT'                   
    504                     Bank['RefDict']['Super'] = 0
     451                self.Banks[int(bN)-1]['RefDict']['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
    505452            else:
    506                 self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
    507                 self.RefDict['Type'] = 'SNT'
    508                 self.RefDict['Super'] = 0
    509                 self.errors = 'Error after reading reflections (unexpected!)'
    510                 self.UpdateParameters(Type='SNT',Wave=None) # histogram type
    511             return True
    512         except Exception as detail:
    513             self.errors += '\n  '+str(detail)
    514             print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
    515             import traceback
    516             traceback.print_exc(file=sys.stdout)
    517             return False
     453            # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
     454                self.RefDict['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
     455        if len(self.Banks):
     456            self.UpdateParameters(Type='SNT',Wave=None) # histogram type
     457            for Bank in self.Banks:
     458                Bank['RefDict']['RefList'] = np.array(Bank['RefDict']['RefList'])
     459                Bank['RefDict']['Type'] = 'SNT'                   
     460                Bank['RefDict']['Super'] = 0
     461        else:
     462            self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
     463            self.RefDict['Type'] = 'SNT'
     464            self.RefDict['Super'] = 0
     465            self.errors = 'Error after reading reflections (unexpected!)'
     466            self.UpdateParameters(Type='SNT',Wave=None) # histogram type
     467        return True
    518468
    519469class NT_JANA2K_ReaderClass(G2IO.ImportStructFactor):
     
    549499        'Read the file'
    550500        filepointer.seek(0)
    551         try:
    552             for line,S in enumerate(filepointer):
    553                 self.errors = '  Error reading line '+str(line+1)
    554                 if S[0] in ['#','(']: continue       #ignore comments & fortran format line
    555                 data = S.split()
    556                 h,k,l,Fo,sigFo,bN,wave,x,x,tbar = data[:10]  #bN = 1..., 6 dir cos next                   
    557                 h,k,l = [int(h),int(k),int(l)]
    558                 if not any([h,k,l]):
    559                     break
    560                 Fo = float(Fo)
    561                 sigFo = float(sigFo)
    562                 wave = float(wave)
    563                 tbar = float(tbar)
    564                 if len(self.Banks):
    565                     self.Banks[int(bN)-1]['RefDict']['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
    566                 else:
    567                 # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
    568                     self.RefDict['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
     501        for line,S in enumerate(filepointer):
     502            self.errors = '  Error reading line '+str(line+1)
     503            if S[0] in ['#','(']: continue       #ignore comments & fortran format line
     504            data = S.split()
     505            h,k,l,Fo,sigFo,bN,wave,x,x,tbar = data[:10]  #bN = 1..., 6 dir cos next                   
     506            h,k,l = [int(h),int(k),int(l)]
     507            if not any([h,k,l]):
     508                break
     509            Fo = float(Fo)
     510            sigFo = float(sigFo)
     511            wave = float(wave)
     512            tbar = float(tbar)
    569513            if len(self.Banks):
    570                 self.UpdateParameters(Type='SNT',Wave=None) # histogram type
    571                 for Bank in self.Banks:
    572                     Bank['RefDict']['RefList'] = np.array(Bank['RefDict']['RefList'])
    573                     Bank['RefDict']['Type'] = 'SNT'                   
    574                     Bank['RefDict']['Super'] = 0        #for now                   
     514                self.Banks[int(bN)-1]['RefDict']['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
    575515            else:
    576                 self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
    577                 self.RefDict['Type'] = 'SNT'
    578                 self.RefDict['Super'] = 0   #for now
    579                 self.errors = 'Error after reading reflections (unexpected!)'
    580                 self.UpdateParameters(Type='SNT',Wave=None) # histogram type
    581             return True
    582         except Exception as detail:
    583             self.errors += '\n  '+str(detail)
    584             print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
    585             import traceback
    586             traceback.print_exc(file=sys.stdout)
    587             return False
     516            # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
     517                self.RefDict['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
     518        if len(self.Banks):
     519            self.UpdateParameters(Type='SNT',Wave=None) # histogram type
     520            for Bank in self.Banks:
     521                Bank['RefDict']['RefList'] = np.array(Bank['RefDict']['RefList'])
     522                Bank['RefDict']['Type'] = 'SNT'                   
     523                Bank['RefDict']['Super'] = 0        #for now                   
     524        else:
     525            self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
     526            self.RefDict['Type'] = 'SNT'
     527            self.RefDict['Super'] = 0   #for now
     528            self.errors = 'Error after reading reflections (unexpected!)'
     529            self.UpdateParameters(Type='SNT',Wave=None) # histogram type
     530        return True
    588531
    589532class ISIS_SXD_INT_ReaderClass(G2IO.ImportStructFactor):
     
    620563        'Read the file'
    621564        filepointer.seek(0)
    622         try:
    623             for line,S in enumerate(filepointer):
    624                 self.errors = '  Error reading line '+str(line+1)
    625                 if S[0] == '#': continue       #ignore comments, if any
    626                 if S[0] == '(': continue        #ignore the format line
    627                 data = S.split()
    628                 h,k,l,Fo,sigFo,bN,wave,x,x,tbar = data[:10]                   
    629                 h,k,l = [int(h),int(k),int(l)]
    630                 if not any([h,k,l]):
    631                     break
    632                 Fo = float(Fo)
    633                 sigFo = float(sigFo)
    634                 wave = float(wave)
    635                 tbar = float(tbar)
    636                 if len(self.Banks):
    637                     self.Banks[int(bN)-1]['RefDict']['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
    638                 else:
    639                 # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
    640                     self.RefDict['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
     565        for line,S in enumerate(filepointer):
     566            self.errors = '  Error reading line '+str(line+1)
     567            if S[0] == '#': continue       #ignore comments, if any
     568            if S[0] == '(': continue        #ignore the format line
     569            data = S.split()
     570            h,k,l,Fo,sigFo,bN,wave,x,x,tbar = data[:10]                   
     571            h,k,l = [int(h),int(k),int(l)]
     572            if not any([h,k,l]):
     573                break
     574            Fo = float(Fo)
     575            sigFo = float(sigFo)
     576            wave = float(wave)
     577            tbar = float(tbar)
    641578            if len(self.Banks):
    642                 self.UpdateParameters(Type='SNT',Wave=None) # histogram type
    643                 for Bank in self.Banks:
    644                     Bank['RefDict']['RefList'] = np.array(Bank['RefDict']['RefList'])
    645                     Bank['RefDict']['Type'] = 'SNT'                   
    646                     Bank['RefDict']['Super'] = 0
     579                self.Banks[int(bN)-1]['RefDict']['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
    647580            else:
    648                 self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
    649                 self.RefDict['Type'] = 'SNT'
    650                 self.RefDict['Super'] = 0
    651                 self.errors = 'Error after reading reflections (unexpected!)'
    652                 self.UpdateParameters(Type='SNT',Wave=None) # histogram type
    653             return True
    654         except Exception as detail:
    655             self.errors += '\n  '+str(detail)
    656             print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
    657             import traceback
    658             traceback.print_exc(file=sys.stdout)
    659             return False
    660 
     581            # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
     582                self.RefDict['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
     583        if len(self.Banks):
     584            self.UpdateParameters(Type='SNT',Wave=None) # histogram type
     585            for Bank in self.Banks:
     586                Bank['RefDict']['RefList'] = np.array(Bank['RefDict']['RefList'])
     587                Bank['RefDict']['Type'] = 'SNT'                   
     588                Bank['RefDict']['Super'] = 0
     589        else:
     590            self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
     591            self.RefDict['Type'] = 'SNT'
     592            self.RefDict['Super'] = 0
     593            self.errors = 'Error after reading reflections (unexpected!)'
     594            self.UpdateParameters(Type='SNT',Wave=None) # histogram type
     595        return True
     596
  • trunk/imports/G2sfact_CIF.py

    r2136 r2738  
    5656                      )
    5757
    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
     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
    6363
    6464        Fcalcnames = ('_refln_f_calc','_refln.f_calc','_refln.f_calc_au',
     
    9090        rdbuffer = kwarg.get('buffer')
    9191        cf = None
     92        if self.repeat and rdbuffer is not None:
     93            cf = rdbuffer.get('lastcif')
     94            print 'Reusing previously parsed CIF'
     95        if cf is None:
     96            self.ShowBusy() # this can take a while
     97            cf = G2IO.ReadCIF(filename)
     98            self.DoneBusy()
     99        # scan blocks for reflections
     100        self.errors = 'Error during scan of blocks for datasets'
     101        blklist = []
     102        for blk in cf.keys(): # scan for reflections, F or F2 values and cell lengths.
     103            # Ignore blocks that do not have structure factors and a cell
     104            blkkeys = [k.lower() for k in cf[blk].keys()]
     105            gotFo = False
     106            im = 0
     107            for i in range(2):
     108                if hklitems[i][3] in blkkeys:   #Super lattice reflections h,k,l,m
     109                    im = 1
     110                if hklitems[i][0] in blkkeys and hklitems[i][1] in blkkeys and hklitems[i][2] in blkkeys:
     111                    dnIndex = i
     112                    break
     113            else:
     114                break # no reflections
     115            for dn in Fdatanames:
     116                if dn in blkkeys:
     117                    blklist.append(blk)
     118                    gotFo = True
     119                    break
     120            if gotFo: break
     121            for dn in F2datanames:
     122                if dn in blkkeys:
     123                    blklist.append(blk)
     124                    break
     125            else:
     126                break
     127        if not blklist:
     128            selblk = None # no block to choose
     129        elif len(blklist) == 1: # only one choice
     130            selblk = 0
     131        else:                       # choose from options
     132            choice = []
     133            for blknm in blklist:
     134                choice.append('')
     135                # accumulate some info about this phase
     136                choice[-1] += blknm + ': '
     137                for i in phasenamefields: # get a name for the phase
     138                    name = cf[blknm].get(i)
     139                    if name is None or name == '?' or name == '.':
     140                        continue
     141                    else:
     142                        choice[-1] += name.strip()[:20] + ', '
     143                        break
     144                s = ''
     145                fmt = "%.2f,"
     146                for i,key in enumerate(cellitems[dnIndex]):
     147                    if i == 3: fmt = "%.f,"
     148                    if i == 5: fmt = "%.f"
     149                    val = cf[blknm].get(key)
     150                    if val is None: break
     151                    s += fmt % cif.get_number_with_esd(val)[0]
     152                if s: choice[-1] += ', cell: ' + s
     153                for dn in SGdataname:
     154                    sg = cf[blknm].get(dn)
     155                    if sg:
     156                        choice[-1] += ', (' + sg.strip() + ')'
     157                        break
     158            choice.append('Import all of the above')
     159            if self.repeat: # we were called to repeat the read
     160                selblk = self.repeatcount
     161                self.repeatcount += 1
     162                if self.repeatcount >= len(blklist): self.repeat = False
     163            else:
     164                selblk = self.BlockSelector(
     165                    choice,
     166                    ParentFrame=ParentFrame,
     167                    title='Select a dataset from one the CIF data_ blocks below',
     168                    size=(600,100),
     169                    header='Dataset Selector')
     170        self.errors = 'Error during reading of selected block'
     171        if selblk is None:
     172            return False # no block selected or available
     173        if selblk >= len(blklist): # all blocks selected
     174            selblk = 0
     175            self.repeat = True
     176            if rdbuffer is not None:
     177                rdbuffer['lastcif'] = cf # save the parsed cif for the next loop
     178            self.repeatcount = 1
     179        blknm = blklist[selblk]
     180        blk = cf[blklist[selblk]]
     181        self.objname = os.path.basename(filename)+':'+str(blknm)
     182        self.errors = 'Error during reading of reflections'
     183        # read in reflections
    92184        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                 im = 0
    114                 for i in range(2):
    115                     if hklitems[i][3] in blkkeys:   #Super lattice reflections h,k,l,m
    116                         im = 1
    117                     if hklitems[i][0] in blkkeys and hklitems[i][1] in blkkeys and hklitems[i][2] in blkkeys:
    118                         dnIndex = i
     185            refloop = blk.GetLoop(hklitems[0][0])
     186            dnIndex = 0
     187        except KeyError:
     188            try:
     189                refloop = blk.GetLoop(hklitems[1][0])
     190                dnIndex = 1
     191            except KeyError:
     192                self.errors += "\nUnexpected: '_refln[-.]index_h not found!"
     193                return False
     194        itemkeys = {}
     195        # prepare an index to the CIF reflection loop
     196        for i,key in enumerate(refloop.keys()):
     197            itemkeys[key.lower()] = i
     198           
     199        # scan for data names:
     200        F2dn = None
     201        Fdn = None
     202        F2cdn = None
     203        Fcdn = None
     204        F2sdn = None
     205        Fsdn = None
     206        Phdn = None
     207        FcalcPresent = False
     208        for dn in F2datanames:
     209            if dn in itemkeys:
     210                F2dn = dn
     211                for dm in F2calcnames:
     212                    if dm in itemkeys:
     213                        F2cdn = dm
     214                        FcalcPresent = True
    119215                        break
    120                 else:
    121                     break # no reflections
    122                 for dn in Fdatanames:
    123                     if dn in blkkeys:
    124                         blklist.append(blk)
    125                         gotFo = True
     216                for dm in F2signames:
     217                    if dm in itemkeys:
     218                        F2sdn = dm
    126219                        break
    127                 if gotFo: break
    128                 for dn in F2datanames:
    129                     if dn in blkkeys:
    130                         blklist.append(blk)
    131                         break
    132                 else:
    133                     break
    134             if not blklist:
    135                 selblk = None # no block to choose
    136             elif len(blklist) == 1: # only one choice
    137                 selblk = 0
    138             else:                       # choose from options
    139                 choice = []
    140                 for blknm in blklist:
    141                     choice.append('')
    142                     # accumulate some info about this phase
    143                     choice[-1] += blknm + ': '
    144                     for i in phasenamefields: # get a name for the phase
    145                         name = cf[blknm].get(i)
    146                         if name is None or name == '?' or name == '.':
    147                             continue
    148                         else:
    149                             choice[-1] += name.strip()[:20] + ', '
     220                break
     221        else:
     222            for dn in Fdatanames:
     223                if dn in itemkeys:
     224                    Fdn = dn
     225                    for dm in Fcalcnames:
     226                        if dm in itemkeys:
     227                            Fcdn = dm
    150228                            break
    151                     s = ''
    152                     fmt = "%.2f,"
    153                     for i,key in enumerate(cellitems[dnIndex]):
    154                         if i == 3: fmt = "%.f,"
    155                         if i == 5: fmt = "%.f"
    156                         val = cf[blknm].get(key)
    157                         if val is None: break
    158                         s += fmt % cif.get_number_with_esd(val)[0]
    159                     if s: choice[-1] += ', cell: ' + s
    160                     for dn in SGdataname:
    161                         sg = cf[blknm].get(dn)
    162                         if sg:
    163                             choice[-1] += ', (' + sg.strip() + ')'
    164                             break
    165                 choice.append('Import all of the above')
    166                 if self.repeat: # we were called to repeat the read
    167                     selblk = self.repeatcount
    168                     self.repeatcount += 1
    169                     if self.repeatcount >= len(blklist): self.repeat = False
    170                 else:
    171                     selblk = self.BlockSelector(
    172                         choice,
    173                         ParentFrame=ParentFrame,
    174                         title='Select a dataset from one the CIF data_ blocks below',
    175                         size=(600,100),
    176                         header='Dataset Selector')
    177             self.errors = 'Error during reading of selected block'
    178             if selblk is None:
    179                 return False # no block selected or available
    180             if selblk >= len(blklist): # all blocks selected
    181                 selblk = 0
    182                 self.repeat = True
    183                 if rdbuffer is not None:
    184                     rdbuffer['lastcif'] = cf # save the parsed cif for the next loop
    185                 self.repeatcount = 1
    186             blknm = blklist[selblk]
    187             blk = cf[blklist[selblk]]
    188             self.objname = os.path.basename(filename)+':'+str(blknm)
    189             self.errors = 'Error during reading of reflections'
    190             # read in reflections
    191             try:
    192                 refloop = blk.GetLoop(hklitems[0][0])
    193                 dnIndex = 0
    194             except KeyError:
    195                 try:
    196                     refloop = blk.GetLoop(hklitems[1][0])
    197                     dnIndex = 1
    198                 except KeyError:
    199                     self.errors += "\nUnexpected: '_refln[-.]index_h not found!"
    200                     return False
    201             itemkeys = {}
    202             # prepare an index to the CIF reflection loop
    203             for i,key in enumerate(refloop.keys()):
    204                 itemkeys[key.lower()] = i
    205                
    206             # scan for data names:
    207             F2dn = None
    208             Fdn = None
    209             F2cdn = None
    210             Fcdn = None
    211             F2sdn = None
    212             Fsdn = None
    213             Phdn = None
    214             FcalcPresent = False
    215             for dn in F2datanames:
    216                 if dn in itemkeys:
    217                     F2dn = dn
    218                     for dm in F2calcnames:
     229                    for dm in Fsignames:
    219230                        if dm in itemkeys:
    220                             F2cdn = dm
    221                             FcalcPresent = True
    222                             break
    223                     for dm in F2signames:
    224                         if dm in itemkeys:
    225                             F2sdn = dm
     231                            Fsdn = dm
    226232                            break
    227233                    break
    228234            else:
    229                 for dn in Fdatanames:
    230                     if dn in itemkeys:
    231                         Fdn = dn
    232                         for dm in Fcalcnames:
    233                             if dm in itemkeys:
    234                                 Fcdn = dm
    235                                 FcalcPresent = True
    236                                 break
    237                         for dm in Fsignames:
    238                             if dm in itemkeys:
    239                                 Fsdn = dm
    240                                 break
    241                         break
     235                msg = "\nno F or F2 loop value found in file\n"
     236                msg += "A CIF reflection file needs to have at least one of\n"
     237                for dn in F2datanames+Fdatanames:
     238                    msg += dn + ', '
     239                self.errors += msg                       
     240                return False
     241        for dn in phasenames:
     242            if dn in itemkeys:
     243                Phdn = dn
     244                break
     245           
     246        # loop over all reflections
     247        for item in refloop:
     248            F2c = 0.0
     249            sigF2 = 0.0
     250            HKL = []
     251            try:
     252                for i in hklitems[dnIndex][:3+im]: # '_refln[._]index_[hkl]'
     253                    num = itemkeys.get(i)
     254                    try:
     255                        HKL.append(int(item[num]))
     256                    except:
     257                        HKL.append('.')
     258                #h,k,l,tw,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,Ext
     259                if im:
     260                    ref = HKL+[1,0,0,0,1, 0,0,0,0,0, 0,0]
    242261                else:
    243                     msg = "\nno F or F2 loop value found in file\n"
    244                     msg += "A CIF reflection file needs to have at least one of\n"
    245                     for dn in F2datanames+Fdatanames:
    246                         msg += dn + ', '
    247                     self.errors += msg                       
    248                     return False
    249             for dn in phasenames:
    250                 if dn in itemkeys:
    251                     Phdn = dn
    252                     break
    253                
    254             # loop over all reflections
    255             for item in refloop:
    256                 F2c = 0.0
    257                 sigF2 = 0.0
    258                 HKL = []
    259                 try:
    260                     for i in hklitems[dnIndex][:3+im]: # '_refln[._]index_[hkl]'
    261                         num = itemkeys.get(i)
    262                         try:
    263                             HKL.append(int(item[num]))
    264                         except:
    265                             HKL.append('.')
    266                     #h,k,l,tw,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,Ext
    267                     if im:
    268                         ref = HKL+[1,0,0,0,1, 0,0,0,0,0, 0,0]
     262                    ref = HKL+[1,0,0,1,0, 0,0,0,0,0, 0]
     263                if F2dn:
     264                    F2 = item[itemkeys[F2dn]]
     265                    if '(' in F2:
     266                        F2, sigF2 = cif.get_number_with_esd(F2)
     267                        F2 = float(F2)
     268                        sigF2 = float(sigF2)
     269                    elif F2sdn:
     270                        F2 = float(F2)
     271                        sigF2 = float(item[itemkeys[F2sdn]])
    269272                    else:
    270                         ref = HKL+[1,0,0,1,0, 0,0,0,0,0, 0]
    271                     if F2dn:
    272                         F2 = item[itemkeys[F2dn]]
    273                         if '(' in F2:
    274                             F2, sigF2 = cif.get_number_with_esd(F2)
    275                             F2 = float(F2)
    276                             sigF2 = float(sigF2)
    277                         elif F2sdn:
    278                             F2 = float(F2)
    279                             sigF2 = float(item[itemkeys[F2sdn]])
    280                         else:
    281                             F2 = float(F2)
    282                         try:
    283                             if F2cdn:
    284                                 F2c = float(item[itemkeys[F2cdn]])
    285                         except:
    286                             pass
    287                     else:
    288                         F = item[itemkeys[Fdn]]
    289                         if '(' in F:
    290                             F, sig = cif.get_number_with_esd(F)
    291                         elif Fsdn:
    292                             F = float(F)
    293                             sig = float(item[itemkeys[Fsdn]])
    294                         else:
    295                             F = float(F)
    296                             sig = 0.0
    297                         F2 = F**2
    298                         sigF2 = 2.0*F*sig
    299                         try:
    300                             if Fcdn:
    301                                 Fc = float(item[itemkeys[Fcdn]])
    302                                 F2c = Fc*Fc
    303                         except:
    304                             pass
    305                                
    306                     ref[8+im] = F2
    307                     ref[5+im] = F2
    308                     ref[6+im] = sigF2
    309                     ref[9+im] = F2c
    310                     ref[7+im] = F2c
     273                        F2 = float(F2)
    311274                    try:
    312                         if Phdn:
    313                             ref[10+im] = float(item[itemkeys[Phdn]])
     275                        if F2cdn:
     276                            F2c = float(item[itemkeys[F2cdn]])
    314277                    except:
    315278                        pass
     279                else:
     280                    F = item[itemkeys[Fdn]]
     281                    if '(' in F:
     282                        F, sig = cif.get_number_with_esd(F)
     283                    elif Fsdn:
     284                        F = float(F)
     285                        sig = float(item[itemkeys[Fsdn]])
     286                    else:
     287                        F = float(F)
     288                        sig = 0.0
     289                    F2 = F**2
     290                    sigF2 = 2.0*F*sig
     291                    try:
     292                        if Fcdn:
     293                            Fc = float(item[itemkeys[Fcdn]])
     294                            F2c = Fc*Fc
     295                    except:
     296                        pass
     297                           
     298                ref[8+im] = F2
     299                ref[5+im] = F2
     300                ref[6+im] = sigF2
     301                ref[9+im] = F2c
     302                ref[7+im] = F2c
     303                try:
     304                    if Phdn:
     305                        ref[10+im] = float(item[itemkeys[Phdn]])
    316306                except:
    317                     continue # skip over incompletely parsed reflections
    318                 self.RefDict['RefList'].append(ref)
     307                    pass
     308            except:
     309                continue # skip over incompletely parsed reflections
     310            self.RefDict['RefList'].append(ref)
    319311#                self.RefDict['FF'].append({})
    320             self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
    321             self.errors = 'Error during reading of dataset parameters'
    322             Type = 'SXC'
    323             if blk.get('_diffrn_radiation_probe'):
    324                 if blk['_diffrn_radiation_probe'] == 'neutron':
    325                     Type = 'SNC'
    326             elif blk.get('_diffrn_radiation.probe'):
    327                 if blk['_diffrn_radiation.probe'] == 'neutron':
    328                     Type = 'SNC'
    329             self.RefDict['Type'] = Type
    330             self.RefDict['Super'] = im
    331             if blk.get('_diffrn_radiation_wavelength'):
    332                 wave = float(blk['_diffrn_radiation_wavelength'])
    333             elif blk.get('_diffrn_radiation.wavelength'):
    334                 wave = float(blk['_diffrn_radiation.wavelength'])
    335             else:
    336                 wave = 0.70926
    337             self.UpdateParameters(Type=Type,Wave=wave) # histogram type
    338             return True
    339         except Exception as detail:
    340             self.errors += '\n  '+str(detail)
    341             print self.formatName+' read error:'+str(detail) # for testing
    342             import traceback
    343             traceback.print_exc(file=sys.stdout)
    344         return False
     312        self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
     313        self.errors = 'Error during reading of dataset parameters'
     314        Type = 'SXC'
     315        if blk.get('_diffrn_radiation_probe'):
     316            if blk['_diffrn_radiation_probe'] == 'neutron':
     317                Type = 'SNC'
     318        elif blk.get('_diffrn_radiation.probe'):
     319            if blk['_diffrn_radiation.probe'] == 'neutron':
     320                Type = 'SNC'
     321        self.RefDict['Type'] = Type
     322        self.RefDict['Super'] = im
     323        if blk.get('_diffrn_radiation_wavelength'):
     324            wave = float(blk['_diffrn_radiation_wavelength'])
     325        elif blk.get('_diffrn_radiation.wavelength'):
     326            wave = float(blk['_diffrn_radiation.wavelength'])
     327        else:
     328            wave = 0.70926
     329        self.UpdateParameters(Type=Type,Wave=wave) # histogram type
     330        return True
Note: See TracChangeset for help on using the changeset viewer.