source: trunk/exports/G2cif.py @ 1035

Last change on this file since 1035 was 1035, checked in by vondreele, 12 years ago

further adventures in residual reporting in cif files
hId & pId must be taken from least squares run - put in appropriate places & used by G2cif.py

  • Property svn:eol-style set to native
File size: 65.7 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3#G2cif
4########### SVN repository information ###################
5# $Date: 2013-07-22 20:57:37 -0500 (Mon, 22 Jul 2013) $
6# $Author: toby $
7# $Revision: 1006 $
8# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/exports/G2cif.py $
9# $Id: G2cif.py 1006 2013-07-23 01:57:37Z toby $
10########### SVN repository information ###################
11'''Code to export a GSAS-II project as a CIF
12The heavy lifting is done in method export
13'''
14
15# TODO: need a mechanism for editing of instrument names, bond pub flags, templates,...
16
17import datetime as dt
18import os.path
19import sys
20import numpy as np
21import wx
22import GSASIIpath
23GSASIIpath.SetVersionNumber("$Revision: 1006 $")
24import GSASIIIO as G2IO
25#reload(G2IO)
26import GSASIIgrid as G2gd
27import GSASIIstrIO as G2stIO
28#reload(G2stIO)
29#import GSASIImapvars as G2mv
30import GSASIImath as G2mth
31#reload(G2mth)
32import GSASIIlattice as G2lat
33import GSASIIspc as G2spc
34#reload(G2spc)
35import GSASIIphsGUI as G2pg
36#reload(G2pg)
37import GSASIIstrMain as G2stMn
38reload(G2stMn)
39
40DEBUG = True    #True to skip printing of reflection/powder profile lists
41
42def getCallerDocString(): # for development
43    "Return the calling function's doc string"
44    import inspect as ins
45    for item in ins.stack()[1][0].f_code.co_consts:
46        if type(item) is str:
47            return item
48    else:
49        return '?'
50
51class ExportCIF(G2IO.ExportBaseclass):
52    def __init__(self,G2frame):
53        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
54            G2frame=G2frame,
55            formatName = 'full CIF',
56            extension='.cif',
57            longFormatName = 'Export project as CIF'
58            )
59        self.author = ''
60
61    def export(self,mode='full'):
62        '''Export a CIF
63
64        :param str mode: "full" (default) to create a complete CIF of project,
65          "simple" for a simple CIF with only coordinates
66        '''
67   
68        def openCIF(filnam):
69            if DEBUG:
70                self.fp = sys.stdout
71            else:
72                self.fp = open(filnam,'w')
73
74        def closeCIF():
75            if not DEBUG:
76                self.fp.close()
77           
78        def WriteCIFitem(name,value=''):
79            if value:
80                if "\n" in value or len(value)> 70:
81                    if name.strip(): self.fp.write(name+'\n')
82                    self.fp.write('; '+value+'\n')
83                    self.fp.write('; '+'\n')
84                elif " " in value:
85                    if len(name)+len(value) > 65:
86                        self.fp.write(name + '\n   ' + '"' + str(value) + '"'+'\n')
87                    else:
88                        self.fp.write(name + '  ' + '"' + str(value) + '"'+'\n')
89                else:
90                    if len(name)+len(value) > 65:
91                        self.fp.write(name+'\n   ' + value+'\n')
92                    else:
93                        self.fp.write(name+'  ' + value+'\n')
94            else:
95                self.fp.write(name+'\n')
96
97        def WriteAudit():
98            WriteCIFitem('_audit_creation_method',
99                         'created in GSAS-II')
100            WriteCIFitem('_audit_creation_date',self.CIFdate)
101            if self.author:
102                WriteCIFitem('_audit_author_name',self.author)
103            WriteCIFitem('_audit_update_record',
104                         self.CIFdate+'  Initial software-generated CIF')
105
106        def WriteOverall():
107            '''Write out overall refinement information.
108
109            More could be done here, but this is a good start.
110            '''
111            WriteCIFitem('_pd_proc_info_datetime', self.CIFdate)
112            WriteCIFitem('_pd_calc_method', 'Rietveld Refinement')
113            #WriteCIFitem('_refine_ls_shift/su_max',DAT1)
114            #WriteCIFitem('_refine_ls_shift/su_mean',DAT2)
115            WriteCIFitem('_computing_structure_refinement','GSAS-II (Toby & Von Dreele, 2013)')
116            try:
117                vars = str(len(self.OverallParms['Covariance']['varyList']))
118            except:
119                vars = '?'
120            WriteCIFitem('_refine_ls_number_parameters',vars)
121            try:
122                GOF = G2mth.ValEsd(self.OverallParms['Covariance']['Rvals']['GOF'],-0.009)
123            except:
124                GOF = '?'
125            WriteCIFitem('_refine_ls_goodness_of_fit_all',GOF)
126
127            # get restraint info
128            # restraintDict = self.OverallParms.get('Restraints',{})
129            # for i in  self.OverallParms['Constraints']:
130            #     print i
131            #     for j in self.OverallParms['Constraints'][i]:
132            #         print j
133            #WriteCIFitem('_refine_ls_number_restraints',TEXT)
134           
135            # other things to consider reporting
136            # _refine_ls_number_reflns
137            # _refine_ls_goodness_of_fit_obs
138            # _refine_ls_R_factor_all
139            # _refine_ls_R_factor_obs
140            # _refine_ls_wR_factor_all
141            # _refine_ls_wR_factor_obs
142            # _refine_ls_restrained_S_all
143            # _refine_ls_restrained_S_obs
144
145            # include an overall profile r-factor, if there is more than one powder histogram
146            if len(self.powderDict) > 1:
147                WriteCIFitem('\n# OVERALL WEIGHTED R-FACTOR')
148                try:
149                    R = '%.3f'%(self.OverallParms['Covariance']['Rvals']['Rwp'])
150                except:
151                    R = '?'
152                WriteCIFitem('_pd_proc_ls_prof_wR_factor',R)
153                #WriteCIFitem('_pd_proc_ls_prof_R_factor',TEXT(11:20)) # who cares!
154            WriteCIFitem('_refine_ls_matrix_type','full')
155            #WriteCIFitem('_refine_ls_matrix_type','userblocks')
156
157        def WritePubTemplate():
158            '''TODO: insert the publication template ``template_publ.cif`` or some modified
159            version for this project. Store this in the GPX file?
160            '''
161            print getCallerDocString()
162
163        def WritePhaseTemplate():
164            '''TODO: insert the phase template ``template_phase.cif`` or some modified
165            version for this project
166            '''
167            print getCallerDocString()
168
169        def WritePowderTemplate():
170            '''TODO: insert the phase template ``template_instrument.cif`` or some modified
171            version for this project
172            '''
173            print getCallerDocString()
174
175        def WriteSnglXtalTemplate():
176            '''TODO: insert the single-crystal histogram template
177            for this project
178            '''
179            print getCallerDocString()
180
181        def FormatSH(phasenam):
182            'Format a full spherical harmonics texture description as a string'
183            phasedict = self.Phases[phasenam] # pointer to current phase info           
184            pfx = str(phasedict['pId'])+'::'
185            s = ""
186            textureData = phasedict['General']['SH Texture']   
187            if textureData.get('Order'):
188                s += "Spherical Harmonics correction. Order = "+str(textureData['Order'])
189                s += " Model: " + str(textureData['Model']) + "\n    Orientation angles: "
190                for name in ['omega','chi','phi']:
191                    aname = pfx+'SH '+name
192                    s += name + " = "
193                    sig = self.sigDict.get(aname,-0.09)
194                    s += G2mth.ValEsd(self.parmDict[aname],sig)
195                    s += "; "
196                s += "\n"
197                s1 = "    Coefficients:  "
198                for name in textureData['SH Coeff'][1]:
199                    aname = pfx+name
200                    if len(s1) > 60:
201                        s += s1 + "\n"
202                        s1 = "    "
203                    s1 += aname + ' = '
204                    sig = self.sigDict.get(aname,-0.0009)
205                    s1 += G2mth.ValEsd(self.parmDict[aname],sig)
206                    s1 += "; "
207                s += s1
208            return s
209
210        def FormatHAPpo(phasenam):
211            '''return the March-Dollase/SH correction for every
212            histogram in the current phase formatted into a
213            character string
214            '''
215            phasedict = self.Phases[phasenam] # pointer to current phase info           
216            s = ''
217            for histogram in sorted(phasedict['Histograms']):
218                if histogram.startswith("HKLF"): continue # powder only
219                Histogram = self.Histograms.get(histogram)
220                if not Histogram: continue
221                hapData = phasedict['Histograms'][histogram]
222                if hapData['Pref.Ori.'][0] == 'MD':
223                    aname = str(phasedict['pId'])+':'+str(Histogram['hId'])+':MD'
224                    if self.parmDict.get(aname,1.0) != 1.0: continue
225                    sig = self.sigDict.get(aname,-0.009)
226                    if s != "": s += '\n'
227                    s += 'March-Dollase correction'
228                    if len(self.powderDict) > 1:
229                        s += ', histogram '+str(Histogram['hId']+1)
230                    s += ' coef. = ' + G2mth.ValEsd(self.parmDict[aname],sig)
231                    s += ' axis = ' + str(hapData['Pref.Ori.'][3])
232                else: # must be SH
233                    if s != "": s += '\n'
234                    s += 'Simple spherical harmonic correction'
235                    if len(self.powderDict) > 1:
236                        s += ', histogram '+str(Histogram['hId']+1)
237                    s += ' Order = '+str(hapData['Pref.Ori.'][4])+'\n'
238                    s1 = "    Coefficients:  "
239                    for item in hapData['Pref.Ori.'][5]:
240                        print item
241                        aname = str(phasedict['pId'])+':'+str(Histogram['hId'])+':'+item
242                        print aname
243                        if len(s1) > 60:
244                            s += s1 + "\n"
245                            s1 = "    "
246                        s1 += aname + ' = '
247                        sig = self.sigDict.get(aname,-0.0009)
248                        s1 += G2mth.ValEsd(self.parmDict[aname],sig)
249                        s1 += "; "
250                    s += s1
251            return s
252        def FormatBackground(bkg,hId):
253            '''Display the Background information as a descriptive text string.
254           
255            TODO: this needs to be expanded to show the diffuse peak and
256            Debye term information as well. (Bob)
257
258            :returns: the text description (str)
259            '''
260            hfx = ':'+str(hId)+':'
261            fxn, bkgdict = bkg
262            terms = fxn[2]
263            txt = 'Background function: "'+fxn[0]+'" function with '+str(terms)+' terms:\n'
264            l = "    "
265            for i,v in enumerate(fxn[3:]):
266                name = '%sBack:%d'%(hfx,i)
267                sig = self.sigDict.get(name,-0.009)
268                if len(l) > 60:
269                    txt += l + '\n'
270                    l = '    '
271                l += G2mth.ValEsd(v,sig)+', '
272            txt += l
273            if bkgdict['nDebye']:
274                txt += '\n  Background Debye function parameters: A, R, U:'
275                names = ['A:','R:','U:']
276                for i in range(bkgdict['nDebye']):
277                    txt += '\n    '
278                    for j in range(3):
279                        name = hfx+'Debye'+names[j]+str(i)
280                        sig = self.sigDict.get(name,-0.009)
281                        txt += G2mth.ValEsd(bkgdict['debyeTerms'][i][2*j],sig)+', '
282            if bkgdict['nPeaks']:
283                txt += '\n  Background peak parameters: pos, int, sig, gam:'
284                names = ['pos:','int:','sig:','gam:']
285                for i in range(bkgdict['nPeaks']):
286                    txt += '\n    '
287                    for j in range(4):
288                        name = hfx+'BkPk'+names[j]+str(i)
289                        sig = self.sigDict.get(name,-0.009)
290                        txt += G2mth.ValEsd(bkgdict['peaksList'][i][2*j],sig)+', '
291            return txt
292
293        def FormatInstProfile(instparmdict,hId):
294            '''Format the instrumental profile parameters with a
295            string description. Will only be called on PWDR histograms
296            '''
297            s = ''
298            inst = instparmdict[0]
299            hfx = ':'+str(hId)+':'
300            if 'C' in inst['Type'][0]:
301                s = 'Finger-Cox-Jephcoat function parameters U, V, W, X, Y, SH/L:\n'
302                s += '  peak variance(Gauss) = Utan(Th)^2^+Vtan(Th)+W:\n'
303                s += '  peak HW(Lorentz) = X/cos(Th)+Ytan(Th); SH/L = S/L+H/L\n'
304                s += '  U, V, W in (centideg)^2^, X & Y in centideg\n    '
305                for item in ['U','V','W','X','Y','SH/L']:
306                    name = hfx+item
307                    sig = self.sigDict.get(name,-0.009)
308                    s += G2mth.ValEsd(inst[item][1],sig)+', '                   
309            elif 'T' in inst['Type'][0]:    #to be tested after TOF Rietveld done
310                s = 'Von Dreele-Jorgenson-Windsor function parameters\n'+ \
311                    '   alpha, beta-0, beta-1, beta-q, sig-0, sig-1, sig-q, X, Y:\n    '
312                for item in ['alpha','bet-0','bet-1','bet-q','sig-0','sig-1','sig-q','X','Y']:
313                    name = hfx+item
314                    sig = self.sigDict.get(name,-0.009)
315                    s += G2mth.ValEsd(inst[item][1],sig)+', '
316            return s
317
318        def FormatPhaseProfile(phasenam):
319            '''Format the phase-related profile parameters (size/strain)
320            with a string description.
321            return an empty string or None if there are no
322            powder histograms for this phase.
323            '''
324            s = ''
325            phasedict = self.Phases[phasenam] # pointer to current phase info
326            SGData = phasedict['General'] ['SGData']         
327            for histogram in sorted(phasedict['Histograms']):
328                if histogram.startswith("HKLF"): continue # powder only
329                Histogram = self.Histograms.get(histogram)
330                if not Histogram: continue
331                hapData = phasedict['Histograms'][histogram]
332                pId = phasedict['pId']
333                hId = Histogram['hId']
334                phfx = '%d:%d:'%(pId,hId)
335                size = hapData['Size']
336                mustrain = hapData['Mustrain']
337                hstrain = hapData['HStrain']
338                s = '  Crystallite size model "%s" for %s (microns)\n  '%(size[0],phasenam)
339                names = ['Size;i','Size;mx']
340                if 'uniax' in size[0]:
341                    names = ['Size;i','Size;a','Size;mx']
342                    s += 'anisotropic axis is %s\n  '%(str(size[3]))
343                    s += 'parameters: equatorial size, axial size, G/L mix\n    '
344                    for i,item in enumerate(names):
345                        name = phfx+item
346                        sig = self.sigDict.get(name,-0.009)
347                        s += G2mth.ValEsd(size[1][i],sig)+', '
348                elif 'ellip' in size[0]:
349                    s += 'parameters: S11, S22, S33, S12, S13, S23, G/L mix\n    '
350                    for i in range(6):
351                        name = phfx+'Size:'+str(i)
352                        sig = self.sigDict.get(name,-0.009)
353                        s += G2mth.ValEsd(size[4][i],sig)+', '
354                    sig = self.sigDict.get(phfx+'Size;mx',-0.009)
355                    s += G2mth.ValEsd(size[1][2],sig)+', '                                           
356                else:       #isotropic
357                    s += 'parameters: Size, G/L mix\n    '
358                    i = 0
359                    for item in names:
360                        name = phfx+item
361                        sig = self.sigDict.get(name,-0.009)
362                        s += G2mth.ValEsd(size[1][i],sig)+', '
363                        i = 2    #skip the aniso value               
364                s += '\n  Mustrain model "%s" for %s (10^6^)\n  '%(mustrain[0],phasenam)
365                names = ['Mustrain;i','Mustrain;mx']
366                if 'uniax' in mustrain[0]:
367                    names = ['Mustrain;i','Mustrain;a','Mustrain;mx']
368                    s += 'anisotropic axis is %s\n  '%(str(size[3]))
369                    s += 'parameters: equatorial mustrain, axial mustrain, G/L mix\n    '
370                    for i,item in enumerate(names):
371                        name = phfx+item
372                        sig = self.sigDict.get(name,-0.009)
373                        s += G2mth.ValEsd(mustrain[1][i],sig)+', '
374                elif 'general' in mustrain[0]:
375                    names = 'parameters: '
376                    for i,name in enumerate(G2spc.MustrainNames(SGData)):
377                        names += name+', '
378                        if i == 9:
379                            names += '\n  '
380                    names += 'G/L mix\n    '
381                    s += names
382                    txt = ''
383                    for i in range(len(mustrain[4])):
384                        name = phfx+'Mustrain:'+str(i)
385                        sig = self.sigDict.get(name,-0.009)
386                        if len(txt) > 60:
387                            s += txt+'\n    '
388                            txt = ''
389                        txt += G2mth.ValEsd(mustrain[4][i],sig)+', '
390                    s += txt                                           
391                    sig = self.sigDict.get(phfx+'Mustrain;mx',-0.009)
392                    s += G2mth.ValEsd(mustrain[1][2],sig)+', '
393                   
394                else:       #isotropic
395                    s += '  parameters: Mustrain, G/L mix\n    '
396                    i = 0
397                    for item in names:
398                        name = phfx+item
399                        sig = self.sigDict.get(name,-0.009)
400                        s += G2mth.ValEsd(mustrain[1][i],sig)+', '
401                        i = 2    #skip the aniso value               
402                s += '\n  Macrostrain for %s\n'%(phasenam)
403                txt = '  parameters: '
404                names = G2spc.HStrainNames(SGData)
405                for name in names:
406                    txt += name+', '
407                s += txt+'\n    '
408                for i in range(len(names)):
409                    name = phfx+name[i]
410                    sig = self.sigDict.get(name,-0.009)
411                    s += G2mth.ValEsd(hstrain[0][i],sig)+', '
412            return s
413       
414        def FmtAtomType(sym):
415            'Reformat a GSAS-II atom type symbol to match CIF rules'
416            sym = sym.replace('_','') # underscores are not allowed: no isotope designation?
417            # in CIF, oxidation state sign symbols come after, not before
418            if '+' in sym:
419                sym = sym.replace('+','') + '+'
420            elif '-' in sym:
421                sym = sym.replace('-','') + '-'
422            return sym
423           
424        def PutInCol(val,wid):
425            '''Pad a value to >=wid+1 columns by adding spaces at the end. Always
426            adds at least one space
427            '''
428            val = str(val).replace(' ','')
429            if not val: val = '?'
430            fmt = '{:' + str(wid) + '} '
431            return fmt.format(val)
432
433        def MakeUniqueLabel(lbl,labellist):
434            'Make sure that every atom label is unique'
435            lbl = lbl.strip()
436            if not lbl: # deal with a blank label
437                lbl = 'A_1'
438            if lbl not in labellist:
439                labellist.append(lbl)
440                return lbl
441            i = 1
442            prefix = lbl
443            if '_' in lbl:
444                prefix = lbl[:lbl.rfind('_')]
445                suffix = lbl[lbl.rfind('_')+1:]
446                try:
447                    i = int(suffix)+1
448                except:
449                    pass
450            while prefix+'_'+str(i) in labellist:
451                i += 1
452            else:
453                lbl = prefix+'_'+str(i)
454                labellist.append(lbl)
455
456        def WriteAtomsNuclear(phasenam):
457            'Write atom positions to CIF'
458            phasedict = self.Phases[phasenam] # pointer to current phase info
459            General = phasedict['General']
460            cx,ct,cs,cia = General['AtomPtrs']
461            Atoms = phasedict['Atoms']
462            cfrac = cx+3
463            fpfx = str(phasedict['pId'])+'::Afrac:'       
464            for i,at in enumerate(Atoms):
465                fval = self.parmDict.get(fpfx+str(i),at[cfrac])
466                if fval != 0.0:
467                    break
468            else:
469                WriteCIFitem('\n# PHASE HAS NO ATOMS!')
470                return
471               
472            WriteCIFitem('\n# ATOMIC COORDINATES AND DISPLACEMENT PARAMETERS')
473            WriteCIFitem('loop_ '+
474                         '\n\t_atom_site_label'+
475                         '\n\t_atom_site_type_symbol'+
476                         '\n\t_atom_site_fract_x'+
477                         '\n\t_atom_site_fract_y'+
478                         '\n\t_atom_site_fract_z'+
479                         '\n\t_atom_site_occupancy'+
480                         '\n\t_atom_site_adp_type'+
481                         '\n\t_atom_site_U_iso_or_equiv'+
482                         '\n\t_atom_site_symmetry_multiplicity')
483
484            varnames = {cx:'Ax',cx+1:'Ay',cx+2:'Az',cx+3:'Afrac',
485                        cia+1:'AUiso',cia+2:'AU11',cia+3:'AU22',cia+4:'AU33',
486                        cia+5:'AU12',cia+6:'AU13',cia+7:'AU23'}
487            self.labellist = []
488           
489            pfx = str(phasedict['pId'])+'::'
490            # loop over all atoms
491            naniso = 0
492            for i,at in enumerate(Atoms):
493                s = PutInCol(MakeUniqueLabel(at[ct-1],self.labellist),6) # label
494                fval = self.parmDict.get(fpfx+str(i),at[cfrac])
495                if fval == 0.0: continue # ignore any atoms that have a occupancy set to 0 (exact)
496                s += PutInCol(FmtAtomType(at[ct]),4) # type
497                if at[cia] == 'I':
498                    adp = 'Uiso '
499                else:
500                    adp = 'Uani '
501                    naniso += 1
502                    # compute Uequiv crudely
503                    # correct: Defined as "1/3 trace of diagonalized U matrix".
504                    # SEE cell2GS & Uij2Ueqv to GSASIIlattice. Former is needed to make the GS matrix used by the latter.
505                    t = 0.0
506                    for j in (2,3,4):
507                        var = pfx+varnames[cia+j]+":"+str(i)
508                        t += self.parmDict.get(var,at[cia+j])
509                for j in (cx,cx+1,cx+2,cx+3,cia,cia+1):
510                    if j in (cx,cx+1,cx+2):
511                        dig = 11
512                        sigdig = -0.00009
513                    else:
514                        dig = 10
515                        sigdig = -0.009
516                    if j == cia:
517                        s += adp
518                    else:
519                        var = pfx+varnames[j]+":"+str(i)
520                        dvar = pfx+"d"+varnames[j]+":"+str(i)
521                        if dvar not in self.sigDict:
522                            dvar = var
523                        if j == cia+1 and adp == 'Uani ':
524                            val = t/3.
525                            sig = sigdig
526                        else:
527                            #print var,(var in self.parmDict),(var in self.sigDict)
528                            val = self.parmDict.get(var,at[j])
529                            sig = self.sigDict.get(dvar,sigdig)
530                        s += PutInCol(G2mth.ValEsd(val,sig),dig)
531                s += PutInCol(at[cs+1],3)
532                WriteCIFitem(s)
533            if naniso == 0: return
534            # now loop over aniso atoms
535            WriteCIFitem('\nloop_' + '\n\t_atom_site_aniso_label' + 
536                         '\n\t_atom_site_aniso_U_11' + '\n\t_atom_site_aniso_U_12' +
537                         '\n\t_atom_site_aniso_U_13' + '\n\t_atom_site_aniso_U_22' +
538                         '\n\t_atom_site_aniso_U_23' + '\n\t_atom_site_aniso_U_33')
539            for i,at in enumerate(Atoms):
540                fval = self.parmDict.get(fpfx+str(i),at[cfrac])
541                if fval == 0.0: continue # ignore any atoms that have a occupancy set to 0 (exact)
542                if at[cia] == 'I': continue
543                s = PutInCol(self.labellist[i],6) # label
544                for j in (2,3,4,5,6,7):
545                    sigdig = -0.0009
546                    var = pfx+varnames[cia+j]+":"+str(i)
547                    val = self.parmDict.get(var,at[cia+j])
548                    sig = self.sigDict.get(var,sigdig)
549                    s += PutInCol(G2mth.ValEsd(val,sig),11)
550                WriteCIFitem(s)
551
552        def HillSortElements(elmlist):
553            '''Sort elements in "Hill" order: C, H, others, (where others
554            are alphabetical).
555
556            :params list elmlist: a list of element strings
557
558            :returns: a sorted list of element strings
559            '''
560            newlist = []
561            oldlist = elmlist[:]
562            for elm in ('C','H'):
563                if elm in elmlist:
564                    newlist.append(elm)
565                    oldlist.pop(oldlist.index(elm))
566            return newlist+sorted(oldlist)
567
568        def WriteComposition(phasenam):
569            '''determine the composition for the unit cell, crudely determine Z and
570            then compute the composition in formula units
571            '''
572            phasedict = self.Phases[phasenam] # pointer to current phase info
573            General = phasedict['General']
574            Z = General.get('cellZ',0.0)
575            cx,ct,cs,cia = General['AtomPtrs']
576            Atoms = phasedict['Atoms']
577            fpfx = str(phasedict['pId'])+'::Afrac:'       
578            cfrac = cx+3
579            cmult = cs+1
580            compDict = {} # combines H,D & T
581            sitemultlist = []
582            massDict = dict(zip(General['AtomTypes'],General['AtomMass']))
583            cellmass = 0
584            for i,at in enumerate(Atoms):
585                atype = at[ct].strip()
586                if atype.find('-') != -1: atype = atype.split('-')[0]
587                if atype.find('+') != -1: atype = atype.split('+')[0]
588                atype = atype[0].upper()+atype[1:2].lower() # force case conversion
589                if atype == "D" or atype == "D": atype = "H"
590                fvar = fpfx+str(i)
591                fval = self.parmDict.get(fvar,at[cfrac])
592                mult = at[cmult]
593                if not massDict.get(at[ct]):
594                    print 'No mass found for atom type '+at[ct]
595                    print 'Will not compute cell contents for phase '+phasenam
596                    return
597                cellmass += massDict[at[ct]]*mult*fval
598                compDict[atype] = compDict.get(atype,0.0) + mult*fval
599                if fval == 1: sitemultlist.append(mult)
600            if len(compDict.keys()) == 0: return # no elements!
601            if Z < 1: # Z has not been computed or set by user
602                Z = 1
603                for i in range(2,min(sitemultlist)+1):
604                    for m in sitemultlist:
605                        if m % i != 0:
606                            break
607                        else:
608                            Z = i
609                General['cellZ'] = Z # save it
610
611            # when scattering factors are included in the CIF, this needs to be
612            # added to the loop here but only in the one-block case.
613            # For multiblock CIFs, scattering factors go in the histogram
614            # blocks  (for all atoms in all appropriate phases)
615
616            #if oneblock: # add scattering factors for current phase here
617            WriteCIFitem('\nloop_  _atom_type_symbol _atom_type_number_in_cell')
618            formula = ''
619            reload(G2mth)
620            for elem in HillSortElements(compDict.keys()):
621                WriteCIFitem('  ' + PutInCol(elem,4) +
622                             G2mth.ValEsd(compDict[elem],-0.009,True))
623                if formula: formula += " "
624                formula += elem
625                if compDict[elem] == Z: continue
626                formula += G2mth.ValEsd(compDict[elem]/Z,-0.009,True)
627            WriteCIFitem( '\n# Note that Z affects _cell_formula_sum and _weight')
628            WriteCIFitem( '_cell_formula_units_Z',str(Z))
629            WriteCIFitem( '_chemical_formula_sum',formula)
630            WriteCIFitem( '_chemical_formula_weight',
631                          G2mth.ValEsd(cellmass/Z,-0.09,True))
632
633        def WriteDistances(phasenam,SymOpList,offsetList,symOpList,G2oprList):
634            '''Report bond distances and angles for the CIF
635
636            Note that _geom_*_symmetry_* fields are values of form
637            n_klm where n is the symmetry operation in SymOpList (counted
638            starting with 1) and (k-5, l-5, m-5) are translations to add
639            to (x,y,z). See
640            http://www.iucr.org/__data/iucr/cifdic_html/1/cif_core.dic/Igeom_angle_site_symmetry_.html
641
642            TODO: need a method to select publication flags for distances/angles
643            '''
644            phasedict = self.Phases[phasenam] # pointer to current phase info           
645            Atoms = phasedict['Atoms']
646            generalData = phasedict['General']
647            cx,ct,cs,cia = phasedict['General']['AtomPtrs']
648            cn = ct-1
649            fpfx = str(phasedict['pId'])+'::Afrac:'       
650            cfrac = cx+3
651            DisAglData = {}
652            DisAglCtls = {}
653            # create a list of atoms, but skip atoms with zero occupancy
654            xyz = []
655            fpfx = str(phasedict['pId'])+'::Afrac:'       
656            for i,atom in enumerate(Atoms):
657                if self.parmDict.get(fpfx+str(i),atom[cfrac]) == 0.0: continue
658                xyz.append([i,]+atom[cn:cn+2]+atom[cx:cx+3])
659            if 'DisAglCtls' in generalData:
660                DisAglCtls = generalData['DisAglCtls']
661            else:
662                dlg = G2gd.DisAglDialog(self.G2frame,DisAglCtls,generalData)
663                if dlg.ShowModal() == wx.ID_OK:
664                    DisAglCtls = dlg.GetData()
665                    generalData['DisAglCtls'] = DisAglCtls
666                else:
667                    dlg.Destroy()
668                    return
669                dlg.Destroy()
670            DisAglData['OrigAtoms'] = xyz
671            DisAglData['TargAtoms'] = xyz
672            SymOpList,offsetList,symOpList,G2oprList = G2spc.AllOps(
673                generalData['SGData'])
674
675            xpandSGdata = generalData['SGData'].copy()
676            xpandSGdata.update({'SGOps':symOpList,
677                                'SGInv':False,
678                                'SGLatt':'P',
679                                'SGCen':np.array([[0, 0, 0]]),})
680            DisAglData['SGData'] = xpandSGdata
681
682            DisAglData['Cell'] = generalData['Cell'][1:] #+ volume
683            if 'pId' in phasedict:
684                DisAglData['pId'] = phasedict['pId']
685                DisAglData['covData'] = self.OverallParms['Covariance']
686            try:
687                AtomLabels,DistArray,AngArray = G2stMn.RetDistAngle(DisAglCtls,DisAglData)
688            except KeyError:        # inside DistAngle for missing atom types in DisAglCtls
689                print '**** ERROR - try again but do "Reset" to fill in missing atom types ****'
690                   
691            # loop over interatomic distances for this phase
692            WriteCIFitem('\n# MOLECULAR GEOMETRY')
693            WriteCIFitem('loop_' + 
694                         '\n\t_geom_bond_atom_site_label_1' +
695                         '\n\t_geom_bond_atom_site_label_2' + 
696                         '\n\t_geom_bond_distance' + 
697                         '\n\t_geom_bond_site_symmetry_1' + 
698                         '\n\t_geom_bond_site_symmetry_2' + 
699                         '\n\t_geom_bond_publ_flag')
700
701            for i in sorted(AtomLabels.keys()):
702                Dist = DistArray[i]
703                for D in Dist:
704                    line = '  '+PutInCol(AtomLabels[i],6)+PutInCol(AtomLabels[D[0]],6)
705                    sig = D[4]
706                    if sig == 0: sig = -0.00009
707                    line += PutInCol(G2mth.ValEsd(D[3],sig,True),10)
708                    line += "  1_555 "
709                    line += " {:3d}_".format(D[2])
710                    for d in D[1]:
711                        line += "{:1d}".format(d+5)
712                    line += " yes"
713                    WriteCIFitem(line)
714
715            # loop over interatomic angles for this phase
716            WriteCIFitem('\nloop_' + 
717                         '\n\t_geom_angle_atom_site_label_1' + 
718                         '\n\t_geom_angle_atom_site_label_2' + 
719                         '\n\t_geom_angle_atom_site_label_3' + 
720                         '\n\t_geom_angle' + 
721                         '\n\t_geom_angle_site_symmetry_1' +
722                         '\n\t_geom_angle_site_symmetry_2' + 
723                         '\n\t_geom_angle_site_symmetry_3' + 
724                         '\n\t_geom_angle_publ_flag')
725
726            for i in sorted(AtomLabels.keys()):
727                Dist = DistArray[i]
728                for k,j,tup in AngArray[i]:
729                    Dj = Dist[j]
730                    Dk = Dist[k]
731                    line = '  '+PutInCol(AtomLabels[Dj[0]],6)+PutInCol(AtomLabels[i],6)+PutInCol(AtomLabels[Dk[0]],6)
732                    sig = tup[1]
733                    if sig == 0: sig = -0.009
734                    line += PutInCol(G2mth.ValEsd(tup[0],sig,True),10)
735                    line += " {:3d}_".format(Dj[2])
736                    for d in Dj[1]:
737                        line += "{:1d}".format(d+5)
738                    line += "  1_555 "
739                    line += " {:3d}_".format(Dk[2])
740                    for d in Dk[1]:
741                        line += "{:1d}".format(d+5)
742                    line += " yes"
743                    WriteCIFitem(line)
744
745        def WritePhaseInfo(phasenam):
746            WriteCIFitem('\n# phase info for '+str(phasenam) + ' follows')
747            phasedict = self.Phases[phasenam] # pointer to current phase info           
748            WriteCIFitem('_pd_phase_name', phasenam)
749            pfx = str(phasedict['pId'])+'::'
750            A,sigA = G2stIO.cellFill(pfx,phasedict['General']['SGData'],self.parmDict,self.sigDict)
751            cellSig = G2stIO.getCellEsd(pfx,
752                                       phasedict['General']['SGData'],A,
753                                       self.OverallParms['Covariance'])  # returns 7 vals, includes sigVol
754            cellList = G2lat.A2cell(A) + (G2lat.calc_V(A),)
755            defsigL = 3*[-0.00001] + 3*[-0.001] + [-0.01] # significance to use when no sigma
756            names = ['length_a','length_b','length_c',
757                     'angle_alpha','angle_beta ','angle_gamma',
758                     'volume']
759            prevsig = 0
760            for lbl,defsig,val,sig in zip(names,defsigL,cellList,cellSig):
761                if sig:
762                    txt = G2mth.ValEsd(val,sig)
763                    prevsig = -sig # use this as the significance for next value
764                else:
765                    txt = G2mth.ValEsd(val,min(defsig,prevsig),True)
766                WriteCIFitem('_cell_'+lbl,txt)
767                   
768            WriteCIFitem('_symmetry_cell_setting',
769                         phasedict['General']['SGData']['SGSys'])
770
771            spacegroup = phasedict['General']['SGData']['SpGrp'].strip()
772            # regularize capitalization and remove trailing H/R
773            spacegroup = spacegroup[0].upper() + spacegroup[1:].lower().rstrip('rh ')
774            WriteCIFitem('_symmetry_space_group_name_H-M',spacegroup)
775
776            # generate symmetry operations including centering and center of symmetry
777            SymOpList,offsetList,symOpList,G2oprList = G2spc.AllOps(
778                phasedict['General']['SGData'])
779            WriteCIFitem('loop_\n    _space_group_symop_id\n    _space_group_symop_operation_xyz')
780            for i,op in enumerate(SymOpList,start=1):
781                WriteCIFitem('   {:3d}  {:}'.format(i,op.lower()))
782
783            # loop over histogram(s) used in this phase
784            if not oneblock and not self.quickmode:
785                # report pointers to the histograms used in this phase
786                histlist = []
787                for hist in self.Phases[phasenam]['Histograms']:
788                    if self.Phases[phasenam]['Histograms'][hist]['Use']:
789                        if phasebyhistDict.get(hist):
790                            phasebyhistDict[hist].append(phasenam)
791                        else:
792                            phasebyhistDict[hist] = [phasenam,]
793                        blockid = datablockidDict.get(hist)
794                        if not blockid:
795                            print "Internal error: no block for data. Phase "+str(
796                                phasenam)+" histogram "+str(hist)
797                            histlist = []
798                            break
799                        histlist.append(blockid)
800
801                if len(histlist) == 0:
802                    WriteCIFitem('# Note: phase has no associated data')
803                else:
804                    WriteCIFitem('loop_  _pd_block_diffractogram_id')
805
806            # report atom params
807            if phasedict['General']['Type'] == 'nuclear':        #this needs macromolecular variant, etc!
808                WriteAtomsNuclear(phasenam)
809            else:
810                raise Exception,"no export for mm coordinates implemented"
811            # report cell contents
812            WriteComposition(phasenam)
813            if not self.quickmode:      # report distances and angles
814                WriteDistances(phasenam,SymOpList,offsetList,symOpList,G2oprList)
815               
816        def Yfmt(ndec,val):
817            'Format intensity values'
818            out = ("{:."+str(ndec)+"f}").format(val)
819            out = out.rstrip('0')  # strip zeros to right of decimal
820            return out.rstrip('.')  # and decimal place when not needed
821           
822        def WriteReflStat(refcount,hklmin,hklmax,dmin,dmax,nRefSets=1):
823            WriteCIFitem('_reflns_number_total', str(refcount))
824            if hklmin is not None and nRefSets == 1: # hkl range has no meaning with multiple phases
825                WriteCIFitem('_reflns_limit_h_min', str(int(hklmin[0])))
826                WriteCIFitem('_reflns_limit_h_max', str(int(hklmax[0])))
827                WriteCIFitem('_reflns_limit_k_min', str(int(hklmin[1])))
828                WriteCIFitem('_reflns_limit_k_max', str(int(hklmax[1])))
829                WriteCIFitem('_reflns_limit_l_min', str(int(hklmin[2])))
830                WriteCIFitem('_reflns_limit_l_max', str(int(hklmax[2])))
831            if hklmin is not None:
832                WriteCIFitem('_reflns_d_resolution_low', G2mth.ValEsd(dmax,-0.0009))
833                WriteCIFitem('_reflns_d_resolution_high', G2mth.ValEsd(dmin,-0.009))
834
835        def WritePowderData(histlbl):
836            histblk = self.Histograms[histlbl]
837            inst = histblk['Instrument Parameters'][0]
838            hId = histblk['hId']
839            pfx = ':' + str(hId) + ':'
840           
841            if 'Lam1' in inst:
842                ratio = self.parmDict.get('I(L2)/I(L1)',inst['I(L2)/I(L1)'][1])
843                sratio = self.sigDict.get('I(L2)/I(L1)',-0.0009)
844                lam1 = self.parmDict.get('Lam1',inst['Lam1'][1])
845                slam1 = self.sigDict.get('Lam1',-0.00009)
846                lam2 = self.parmDict.get('Lam2',inst['Lam2'][1])
847                slam2 = self.sigDict.get('Lam2',-0.00009)
848                # always assume Ka1 & Ka2 if two wavelengths are present
849                WriteCIFitem('loop_' + 
850                             '\n\t_diffrn_radiation_wavelength' +
851                             '\n\t_diffrn_radiation_wavelength_wt' + 
852                             '\n\t_diffrn_radiation_type' + 
853                             '\n\t_diffrn_radiation_wavelength_id')
854                WriteCIFitem('  ' + PutInCol(G2mth.ValEsd(lam1,slam1),15)+
855                             PutInCol('1.0',15) + 
856                             PutInCol('K\\a~1~',10) + 
857                             PutInCol('1',5))
858                WriteCIFitem('  ' + PutInCol(G2mth.ValEsd(lam2,slam2),15)+
859                             PutInCol(G2mth.ValEsd(ratio,sratio),15)+
860                             PutInCol('K\\a~2~',10) + 
861                             PutInCol('2',5))               
862            else:
863                lam1 = self.parmDict.get('Lam',inst['Lam'][1])
864                slam1 = self.sigDict.get('Lam',-0.00009)
865                WriteCIFitem('_diffrn_radiation_wavelength',G2mth.ValEsd(lam1,slam1))
866
867            if not oneblock:
868                if not phasebyhistDict.get(histlbl):
869                    WriteCIFitem('\n# No phases associated with this data set')
870                else:
871                    WriteCIFitem('\n# PHASE TABLE')
872                    WriteCIFitem('loop_' +
873                                 '\n\t_pd_phase_id' + 
874                                 '\n\t_pd_phase_block_id' + 
875                                 '\n\t_pd_phase_mass_%' +
876                                 '\n\t_refine_ls_R_F_factor' +
877                                 '\n\t_refine_ls_R_Fsqd_factor')
878                    wtFrSum = 0.
879                    for phasenam in phasebyhistDict.get(histlbl):
880                        hapData = self.Phases[phasenam]['Histograms'][histlbl]
881                        General = self.Phases[phasenam]['General']
882                        wtFrSum += hapData['Scale'][0]*General['Mass']
883
884                    for phasenam in phasebyhistDict.get(histlbl):
885                        hapData = self.Phases[phasenam]['Histograms'][histlbl]
886                        General = self.Phases[phasenam]['General']
887                        wtFr = hapData['Scale'][0]*General['Mass']/wtFrSum
888                        pfx = str(self.Phases[phasenam]['pId'])+':'+str(hId)+':'
889                        if pfx+'Scale' in self.sigDict:
890                            sig = self.sigDict[pfx+'Scale']*wtFr/hapData['Scale'][0]
891                        else:
892                            sig = -0.0001
893                        WriteCIFitem(
894                            '  '+
895                            str(self.Phases[phasenam]['pId']) +
896                            '  '+datablockidDict[phasenam]+
897                            '  '+G2mth.ValEsd(wtFr,sig) +
898                            '  '+G2mth.ValEsd(histblk[pfx+'Rf'],-.009)
899                            '  '+G2mth.ValEsd(histblk[pfx+'Rf^2'],-.009)
900                            )
901
902            # TODO: this will need help from Bob
903            # WriteCIFitem('_pd_proc_ls_prof_R_factor','?')
904            WriteCIFitem('_pd_proc_ls_prof_wR_factor','%.3f'%(histblk['wR']))
905            WriteCIFitem('_pd_proc_ls_prof_wR_expected','?')
906
907            if histblk['Instrument Parameters'][0]['Type'][1][1] == 'X':
908                WriteCIFitem('_diffrn_radiation_probe','x-ray')
909                pola = histblk['Instrument Parameters'][0].get('Polariz.')
910                if pola:
911                    pfx = ':' + str(hId) + ':'
912                    sig = self.sigDict.get(pfx+'Polariz.',-0.0009)
913                    txt = G2mth.ValEsd(pola[1],sig)
914                    WriteCIFitem('_diffrn_radiation_polarisn_ratio',txt)
915            elif histblk['Instrument Parameters'][0]['Type'][1][1] == 'N':
916                WriteCIFitem('_diffrn_radiation_probe','neutron')
917            # TOF (note that this may not be defined)
918            #if histblk['Instrument Parameters'][0]['Type'][1][2] == 'T':
919            #    WriteCIFitem('_pd_meas_2theta_fixed',text)
920           
921
922            # TODO: this will need help from Bob
923            #if not oneblock:
924            #WriteCIFitem('\n# SCATTERING FACTOR INFO')
925            #WriteCIFitem('loop_  _atom_type_symbol')
926            #if histblk['Instrument Parameters'][0]['Type'][1][1] == 'X':
927            #    WriteCIFitem('      _atom_type_scat_dispersion_real')
928            #    WriteCIFitem('      _atom_type_scat_dispersion_imag')
929            #    for lbl in ('a1','a2','a3', 'a4', 'b1', 'b2', 'b3', 'b4', 'c'):
930            #        WriteCIFitem('      _atom_type_scat_Cromer_Mann_'+lbl)
931            #elif histblk['Instrument Parameters'][0]['Type'][1][1] == 'N':
932            #    WriteCIFitem('      _atom_type_scat_length_neutron')
933            #WriteCIFitem('      _atom_type_scat_source')
934
935            WriteCIFitem('_pd_proc_ls_background_function',FormatBackground(histblk['Background'],histblk['hId']))
936
937            # TODO: this will need help from Bob
938            #WriteCIFitem('_exptl_absorpt_process_details','?')
939            #WriteCIFitem('_exptl_absorpt_correction_T_min','?')
940            #WriteCIFitem('_exptl_absorpt_correction_T_max','?')
941            #C extinction
942            #WRITE(IUCIF,'(A)') '# Extinction correction'
943            #CALL WRVAL(IUCIF,'_gsas_exptl_extinct_corr_T_min',TEXT(1:10))
944            #CALL WRVAL(IUCIF,'_gsas_exptl_extinct_corr_T_max',TEXT(11:20))
945
946            if not oneblock:                 # instrumental profile terms go here
947                WriteCIFitem('_pd_proc_ls_profile_function', 
948                    FormatInstProfile(histblk["Instrument Parameters"],histblk['hId']))
949
950            #refprx = '_refln.' # mm
951            refprx = '_refln_' # normal
952            WriteCIFitem('\n# STRUCTURE FACTOR TABLE')           
953            # compute maximum intensity reflection
954            Imax = 0
955            for phasenam in histblk['Reflection Lists']:
956                scale = self.Phases[phasenam]['Histograms'][histlbl]['Scale'][0]
957                Icorr = np.array([refl[13] for refl in histblk['Reflection Lists'][phasenam]])
958                FO2 = np.array([refl[8] for refl in histblk['Reflection Lists'][phasenam]])
959                I100 = scale*FO2*Icorr
960                Imax = max(Imax,max(I100))
961
962            WriteCIFitem('loop_')
963            if len(histblk['Reflection Lists'].keys()) > 1:
964                WriteCIFitem('\t_pd_refln_phase_id')
965            WriteCIFitem('\t' + refprx + 'index_h' + 
966                         '\n\t' + refprx + 'index_k' + 
967                         '\n\t' + refprx + 'index_l' + 
968                         '\n\t' + refprx + 'F_squared_meas' + 
969                         '\n\t' + refprx + 'F_squared_calc' + 
970                         '\n\t' + refprx + 'phase_calc' + 
971                         '\n\t_pd_refln_d_spacing')
972            if Imax > 0:
973                WriteCIFitem('\t_gsas_i100_meas')
974
975            refcount = 0
976            hklmin = None
977            hklmax = None
978            dmax = None
979            dmin = None
980            for phasenam in histblk['Reflection Lists']:
981                scale = self.Phases[phasenam]['Histograms'][histlbl]['Scale'][0]
982                phaseid = self.Phases[phasenam]['pId']
983                refcount += len(histblk['Reflection Lists'][phasenam])
984                for ref in histblk['Reflection Lists'][phasenam]:
985                    if DEBUG:
986                        print 'DEBUG: skip reflection list'
987                        break
988                    if hklmin is None:
989                        hklmin = ref[0:3]
990                        hklmax = ref[0:3]
991                        dmax = dmin = ref[4]
992                    if len(histblk['Reflection Lists'].keys()) > 1:
993                        s = PutInCol(phaseid,2)
994                    else:
995                        s = ""
996                    for i,hkl in enumerate(ref[0:3]):
997                        hklmax[i] = max(hkl,hklmax[i])
998                        hklmin[i] = min(hkl,hklmin[i])
999                        s += PutInCol(int(hkl),4)
1000                    for I in ref[8:10]:
1001                        s += PutInCol(G2mth.ValEsd(I,-0.0009),10)
1002                    s += PutInCol(G2mth.ValEsd(ref[10],-0.9),7)
1003                    dmax = max(dmax,ref[4])
1004                    dmin = min(dmin,ref[4])
1005                    s += PutInCol(G2mth.ValEsd(ref[4],-0.009),8)
1006                    if Imax > 0:
1007                        I100 = 100.*scale*ref[8]*ref[13]/Imax
1008                        s += PutInCol(G2mth.ValEsd(I100,-0.09),6)
1009                    WriteCIFitem("  "+s)
1010
1011            WriteReflStat(refcount,hklmin,hklmax,dmin,dmax,len(histblk['Reflection Lists']))
1012            WriteCIFitem('\n# POWDER DATA TABLE')
1013            # is data fixed step? If the step varies by <0.01% treat as fixed step
1014            steps = histblk['Data'][0][1:] - histblk['Data'][0][:-1]
1015            if abs(max(steps)-min(steps)) > abs(max(steps))/10000.:
1016                fixedstep = False
1017            else:
1018                fixedstep = True
1019
1020            if fixedstep: # and not TOF
1021                WriteCIFitem('_pd_meas_2theta_range_min', G2mth.ValEsd(histblk['Data'][0][0],-0.00009))
1022                WriteCIFitem('_pd_meas_2theta_range_max', G2mth.ValEsd(histblk['Data'][0][-1],-0.00009))
1023                WriteCIFitem('_pd_meas_2theta_range_inc', G2mth.ValEsd(steps.sum()/len(steps),-0.00009))
1024                # zero correct, if defined
1025                zero = None
1026                zerolst = histblk['Instrument Parameters'][0].get('Zero')
1027                if zerolst: zero = zerolst[1]
1028                zero = self.parmDict.get('Zero',zero)
1029                if zero:
1030                    WriteCIFitem('_pd_proc_2theta_range_min', G2mth.ValEsd(histblk['Data'][0][0]-zero,-0.00009))
1031                    WriteCIFitem('_pd_proc_2theta_range_max', G2mth.ValEsd(histblk['Data'][0][-1]-zero,-0.00009))
1032                    WriteCIFitem('_pd_proc_2theta_range_inc', G2mth.ValEsd(steps.sum()/len(steps),-0.00009))
1033               
1034            if zero:
1035                WriteCIFitem('_pd_proc_number_of_points', str(len(histblk['Data'][0])))
1036            else:
1037                WriteCIFitem('_pd_meas_number_of_points', str(len(histblk['Data'][0])))
1038            WriteCIFitem('\nloop_')
1039            #            WriteCIFitem('\t_pd_proc_d_spacing') # need easy way to get this
1040            if not fixedstep:
1041                if zero:
1042                    WriteCIFitem('\t_pd_proc_2theta_corrected')
1043                else:
1044                    WriteCIFitem('\t_pd_meas_2theta_scan')
1045            # at least for now, always report weights.
1046            #if countsdata:
1047            #    WriteCIFitem('\t_pd_meas_counts_total')
1048            #else:
1049            WriteCIFitem('\t_pd_meas_intensity_total')
1050            WriteCIFitem('\t_pd_calc_intensity_total')
1051            WriteCIFitem('\t_pd_proc_intensity_bkg_calc')
1052            WriteCIFitem('\t_pd_proc_ls_weight')
1053            maxY = max(histblk['Data'][1].max(),histblk['Data'][3].max())
1054            if maxY < 0: maxY *= -10 # this should never happen, but...
1055            ndec = max(0,10-int(np.log10(maxY))-1) # 10 sig figs should be enough
1056            maxSU = histblk['Data'][2].max()
1057            if maxSU < 0: maxSU *= -1 # this should never happen, but...
1058            ndecSU = max(0,8-int(np.log10(maxSU))-1) # 8 sig figs should be enough
1059            lowlim,highlim = histblk['Limits'][1]
1060
1061            if DEBUG:
1062                print 'DEBUG: skip profile list'
1063            else:   
1064                for x,yobs,yw,ycalc,ybkg in zip(histblk['Data'][0],
1065                                                histblk['Data'][1],
1066                                                histblk['Data'][2],
1067                                                histblk['Data'][3],
1068                                                histblk['Data'][4]):
1069                    if lowlim <= x <= highlim:
1070                        pass
1071                    else:
1072                        yw = 0.0 # show the point is not in use
1073   
1074                    if fixedstep:
1075                        s = ""
1076                    else:
1077                        s = PutInCol(G2mth.ValEsd(x-zero,-0.00009),10)
1078                    s += PutInCol(Yfmt(ndec,yobs),12)
1079                    s += PutInCol(Yfmt(ndec,ycalc),12)
1080                    s += PutInCol(Yfmt(ndec,ybkg),11)
1081                    s += PutInCol(Yfmt(ndecSU,yw),9)
1082                    WriteCIFitem("  "+s)
1083
1084        def WriteSingleXtalData(histlbl):
1085            histblk = self.Histograms[histlbl]
1086            #refprx = '_refln.' # mm
1087            refprx = '_refln_' # normal
1088
1089            WriteCIFitem('\n# STRUCTURE FACTOR TABLE')           
1090            WriteCIFitem('loop_' + 
1091                         '\n\t' + refprx + 'index_h' + 
1092                         '\n\t' + refprx + 'index_k' + 
1093                         '\n\t' + refprx + 'index_l' +
1094                         '\n\t' + refprx + 'F_squared_meas' + 
1095                         '\n\t' + refprx + 'F_squared_sigma' + 
1096                         '\n\t' + refprx + 'F_squared_calc' + 
1097                         '\n\t' + refprx + 'phase_calc'
1098                         )
1099
1100            hklmin = None
1101            hklmax = None
1102            dmax = None
1103            dmin = None
1104            refcount = len(histblk['Data'])
1105            for ref in histblk['Data']:
1106                s = "  "
1107                if hklmin is None:
1108                    hklmin = ref[0:3]
1109                    hklmax = ref[0:3]
1110                    dmax = dmin = ref[4]
1111                for i,hkl in enumerate(ref[0:3]):
1112                    hklmax[i] = max(hkl,hklmax[i])
1113                    hklmin[i] = min(hkl,hklmin[i])
1114                    s += PutInCol(int(hkl),4)
1115                sig = ref[6] * ref[8] / ref[5]
1116                s += PutInCol(G2mth.ValEsd(ref[8],-abs(sig/10)),12)
1117                s += PutInCol(G2mth.ValEsd(sig,-abs(sig)/10.),10)
1118                s += PutInCol(G2mth.ValEsd(ref[9],-abs(sig/10)),12)
1119                s += PutInCol(G2mth.ValEsd(ref[10],-0.9),7)
1120                dmax = max(dmax,ref[4])
1121                dmin = min(dmin,ref[4])
1122                WriteCIFitem(s)
1123            WriteReflStat(refcount,hklmin,hklmax,dmin,dmax)
1124
1125        #============================================================
1126        # the export process starts here
1127        # load all of the tree into a set of dicts
1128        self.loadTree()
1129        # create a dict with refined values and their uncertainties
1130        self.loadParmDict()
1131
1132        # Someday: get restraint & constraint info
1133        #restraintDict = self.OverallParms.get('Restraints',{})
1134        #for i in  self.OverallParms['Constraints']:
1135        #    print i
1136        #    for j in self.OverallParms['Constraints'][i]:
1137        #        print j
1138
1139        self.CIFdate = dt.datetime.strftime(dt.datetime.now(),"%Y-%m-%dT%H:%M")
1140        # index powder and single crystal histograms
1141        self.powderDict = {}
1142        self.xtalDict = {}
1143        for hist in self.Histograms:
1144            i = self.Histograms[hist]['hId']
1145            if hist.startswith("PWDR"): 
1146                self.powderDict[i] = hist
1147            elif hist.startswith("HKLF"): 
1148                self.xtalDict[i] = hist
1149        # is there anything to export?
1150        if len(self.Phases) + len(self.powderDict) + len(self.xtalDict) == 0: 
1151            self.G2frame.ErrorDialog(
1152                'Empty project',
1153                'No data or phases to include in CIF')
1154            return
1155        # is there a file name defined?
1156        self.CIFname = os.path.splitext(
1157            os.path.split(self.G2frame.GSASprojectfile)[1]
1158            )[0]
1159        self.CIFname = self.CIFname.replace(' ','')
1160        if not self.CIFname:
1161            self.G2frame.ErrorDialog(
1162                'No GPX name',
1163                'Please save the project to provide a name')
1164            return
1165        # test for quick CIF mode or no data
1166        self.quickmode = False
1167        phasenam = phasenum = None # include all phases
1168        if mode != "full" or len(self.powderDict) + len(self.xtalDict) == 0:
1169            self.quickmode = True
1170            oneblock = True
1171            if len(self.Phases) == 0:
1172                self.G2frame.ErrorDialog(
1173                    'No phase present',
1174                    'Cannot create a coordinates CIF with no phases')
1175                return
1176            elif len(self.Phases) > 1: # quick mode: choose one phase
1177                choices = sorted(self.Phases.keys())
1178                phasenum = G2gd.ItemSelector(choices,self.G2frame)
1179                if phasenum is None: return
1180                phasenam = choices[phasenum]
1181        # will this require a multiblock CIF?
1182        elif len(self.Phases) > 1:
1183            oneblock = False
1184        elif len(self.powderDict) + len(self.xtalDict) > 1:
1185            oneblock = False
1186        else: # one phase, one dataset, Full CIF
1187            oneblock = True
1188
1189        # make sure needed infomation is present
1190        # get CIF author name -- required for full CIFs
1191        try:
1192            self.author = self.OverallParms['Controls'].get("Author",'').strip()
1193        except KeyError:
1194            pass
1195        while not (self.author or self.quickmode):
1196            dlg = G2gd.SingleStringDialog(self.G2frame,'Get CIF Author','Provide CIF Author name (Last, First)')
1197            if not dlg.Show(): return # cancel was pressed
1198            self.author = dlg.GetValue()
1199            dlg.Destroy()
1200        try:
1201            self.OverallParms['Controls']["Author"] = self.author # save for future
1202        except KeyError:
1203            pass
1204        self.shortauthorname = self.author.replace(',','').replace(' ','')[:20]
1205
1206        # check the instrument name for every histogram
1207        if not self.quickmode:
1208            dictlist = []
1209            keylist = []
1210            lbllist = []
1211            invalid = 0
1212            key3 = 'InstrName'
1213            for hist in self.Histograms:
1214                if hist.startswith("PWDR"): 
1215                    key2 = "Sample Parameters"
1216                    d = self.Histograms[hist][key2]
1217                elif hist.startswith("HKLF"): 
1218                    key2 = "Instrument Parameters"
1219                    d = self.Histograms[hist][key2][0]
1220                   
1221                lbllist.append(hist)
1222                dictlist.append(d)
1223                keylist.append(key3)
1224                instrname = d.get(key3)
1225                if instrname is None:
1226                    d[key3] = ''
1227                    invalid += 1
1228                elif instrname.strip() == '':
1229                    invalid += 1
1230            if invalid:
1231                msg = ""
1232                if invalid > 3: msg = (
1233                    "\n\nNote: it may be faster to set the name for\n"
1234                    "one histogram for each instrument and use the\n"
1235                    "File/Copy option to duplicate the name"
1236                    )
1237                if not G2gd.CallScrolledMultiEditor(
1238                    self.G2frame,dictlist,keylist,
1239                    prelbl=range(1,len(dictlist)+1),
1240                    postlbl=lbllist,
1241                    title='Instrument names',
1242                    header="Edit instrument names. Note that a non-blank\nname is required for all histograms"+msg,
1243                    ): return
1244
1245        if oneblock and not self.quickmode:
1246            # select a dataset to use (there should only be one set in one block,
1247            # but take whatever comes 1st
1248            for hist in self.Histograms:
1249                histblk = self.Histograms[hist]
1250                if hist.startswith("PWDR"): 
1251                    instnam = histblk["Sample Parameters"]['InstrName']
1252                    break # ignore all but 1st data histogram
1253                elif hist.startswith("HKLF"): 
1254                    instnam = histblk["Instrument Parameters"][0]['InstrName']
1255                    break # ignore all but 1st data histogram
1256        if self.quickmode:
1257            fil = self.askSaveFile()
1258        else:
1259            fil = self.defSaveFile()
1260        if not fil: return
1261        openCIF(fil)
1262        #======================================================================
1263        # Start writing the CIF - single block
1264        #======================================================================
1265        if oneblock:
1266            WriteCIFitem('data_'+self.CIFname)
1267            if phasenam is None: # if not already selected, select the first phase (should be one)
1268                phasenam = self.Phases.keys()[0]
1269            #print 'phasenam',phasenam
1270            phaseblk = self.Phases[phasenam] # pointer to current phase info
1271            if not self.quickmode:
1272                instnam = instnam.replace(' ','')
1273                WriteCIFitem('_pd_block_id',
1274                             str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
1275                             str(self.shortauthorname) + "|" + instnam)
1276                WriteAudit()
1277                WritePubTemplate()
1278                WriteOverall()
1279                WritePhaseTemplate()
1280            # report the phase info
1281            WritePhaseInfo(phasenam)
1282            if hist.startswith("PWDR") and not self.quickmode:
1283                # preferred orientation
1284                SH = FormatSH(phasenam)
1285                MD = FormatHAPpo(phasenam)
1286                if SH and MD:
1287                    WriteCIFitem('_pd_proc_ls_pref_orient_corr', SH + '\n' + MD)
1288                elif SH or MD:
1289                    WriteCIFitem('_pd_proc_ls_pref_orient_corr', SH + MD)
1290                else:
1291                    WriteCIFitem('_pd_proc_ls_pref_orient_corr', 'none')
1292                    # report profile, since one-block: include both histogram and phase info
1293                WriteCIFitem('_pd_proc_ls_profile_function',
1294                    FormatInstProfile(histblk["Instrument Parameters"],histblk['hId'])
1295                    +'\n'+FormatPhaseProfile(phasenam))
1296                WritePowderTemplate()
1297                WritePowderData(hist)
1298            elif hist.startswith("HKLF") and not self.quickmode:
1299                WriteSnglXtalTemplate()
1300                WriteSingleXtalData(hist)
1301        else:
1302        #======================================================================
1303        # Start writing the CIF - multiblock
1304        #======================================================================
1305            # publication info
1306            WriteCIFitem('\ndata_'+self.CIFname+'_publ')
1307            WriteAudit()
1308            WriteCIFitem('_pd_block_id',
1309                         str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
1310                         str(self.shortauthorname) + "|Overall")
1311            WritePubTemplate()
1312            # overall info
1313            WriteCIFitem('data_'+str(self.CIFname)+'_overall')
1314            WriteOverall()
1315            #============================================================
1316            WriteCIFitem('# POINTERS TO PHASE AND HISTOGRAM BLOCKS')
1317            datablockidDict = {} # save block names here -- N.B. check for conflicts between phase & hist names (unlikely!)
1318            # loop over phase blocks
1319            if len(self.Phases) > 1:
1320                loopprefix = ''
1321                WriteCIFitem('loop_   _pd_phase_block_id')
1322            else:
1323                loopprefix = '_pd_phase_block_id'
1324           
1325            for phasenam in sorted(self.Phases.keys()):
1326                i = self.Phases[phasenam]['pId']
1327                datablockidDict[phasenam] = (str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
1328                             'phase_'+ str(i) + '|' + str(self.shortauthorname))
1329                WriteCIFitem(loopprefix,datablockidDict[phasenam])
1330            # loop over data blocks
1331            if len(self.powderDict) + len(self.xtalDict) > 1:
1332                loopprefix = ''
1333                WriteCIFitem('loop_   _pd_block_diffractogram_id')
1334            else:
1335                loopprefix = '_pd_block_diffractogram_id'
1336            for i in sorted(self.powderDict.keys()):
1337                hist = self.powderDict[i]
1338                histblk = self.Histograms[hist]
1339                instnam = histblk["Sample Parameters"]['InstrName']
1340                instnam = instnam.replace(' ','')
1341                i = histblk['hId']
1342                datablockidDict[hist] = (str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
1343                                         str(self.shortauthorname) + "|" +
1344                                         instnam + "_hist_"+str(i))
1345                WriteCIFitem(loopprefix,datablockidDict[hist])
1346            for i in sorted(self.xtalDict.keys()):
1347                hist = self.xtalDict[i]
1348                histblk = self.Histograms[hist]
1349                instnam = histblk["Instrument Parameters"][0]['InstrName']
1350                instnam = instnam.replace(' ','')
1351                i = histblk['hId']
1352                datablockidDict[hist] = (str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
1353                                         str(self.shortauthorname) + "|" +
1354                                         instnam + "_hist_"+str(i))
1355                WriteCIFitem(loopprefix,datablockidDict[hist])
1356            #============================================================
1357            # loop over phases, exporting them
1358            phasebyhistDict = {} # create a cross-reference to phases by histogram
1359            for j,phasenam in enumerate(sorted(self.Phases.keys())):
1360                i = self.Phases[phasenam]['pId']
1361                WriteCIFitem('\ndata_'+self.CIFname+"_phase_"+str(i))
1362                print "debug, processing ",phasenam
1363                WriteCIFitem('# Information for phase '+str(i))
1364                WriteCIFitem('_pd_block_id',datablockidDict[phasenam])
1365                # report the phase
1366                WritePhaseTemplate()
1367                WritePhaseInfo(phasenam)
1368                # preferred orientation
1369                SH = FormatSH(phasenam)
1370                MD = FormatHAPpo(phasenam)
1371                if SH and MD:
1372                    WriteCIFitem('_pd_proc_ls_pref_orient_corr', SH + '\n' + MD)
1373                elif SH or MD:
1374                    WriteCIFitem('_pd_proc_ls_pref_orient_corr', SH + MD)
1375                else:
1376                    WriteCIFitem('_pd_proc_ls_pref_orient_corr', 'none')
1377                # report sample profile terms
1378                PP = FormatPhaseProfile(phasenam)
1379                if PP:
1380                    WriteCIFitem('_pd_proc_ls_profile_function',PP)
1381                   
1382            #============================================================
1383            # loop over histograms, exporting them
1384            for i in sorted(self.powderDict.keys()):
1385                hist = self.powderDict[i]
1386                histblk = self.Histograms[hist]
1387                if hist.startswith("PWDR"): 
1388                    WriteCIFitem('\ndata_'+self.CIFname+"_pwd_"+str(i))
1389                    #instnam = histblk["Sample Parameters"]['InstrName']
1390                    # report instrumental profile terms
1391                    WriteCIFitem('_pd_proc_ls_profile_function',
1392                        FormatInstProfile(histblk["Instrument Parameters"],histblk['hId']))
1393                    WriteCIFitem('# Information for histogram '+str(i)+': '+hist)
1394                    WriteCIFitem('_pd_block_id',datablockidDict[hist])
1395                    WritePowderTemplate()
1396                    WritePowderData(hist)
1397            for i in sorted(self.xtalDict.keys()):
1398                hist = self.xtalDict[i]
1399                histblk = self.Histograms[hist]
1400                if hist.startswith("HKLF"): 
1401                    WriteCIFitem('\ndata_'+self.CIFname+"_sx_"+str(i))
1402                    #instnam = histblk["Instrument Parameters"][0]['InstrName']
1403                    WriteCIFitem('# Information for histogram '+str(i)+': '+hist)
1404                    WriteCIFitem('_pd_block_id',datablockidDict[hist])
1405                    WriteSnglXtalTemplate()
1406                    WriteSingleXtalData(hist)
1407
1408        WriteCIFitem('#--' + 15*'eof--' + '#')
1409        closeCIF()
Note: See TracBrowser for help on using the repository browser.