Ignore:
Timestamp:
Nov 6, 2022 12:25:48 PM (7 months ago)
Author:
toby
Message:

misc docs; new project exporter

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/exports/G2export_Bracket.py

    • Property svn:eol-style set to native
    • Property svn:keywords set to Date Author Revision URL Id
    r5241 r5365  
    22# -*- coding: utf-8 -*-
    33########### SVN repository information ###################
    4 # $Date: 2021-04-04 08:00:26 +1000 (Sun, 04 Apr 2021) $
    5 # $Author: toby $
    6 # $Revision: 4874 $
    7 # $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/exports/G2export_JSON.py $
    8 # $Id: G2export_JSON.py 4874 2021-04-03 22:00:26Z toby $
     4# $Date$
     5# $Author$
     6# $Revision$
     7# $URL$
     8# $Id$
    99########### SVN repository information ###################
    1010
    11 # This module was written by Conrad Gillard. For any enquiries please contact conrad.gillard@gmail.com
     11# This module initially written by Conrad Gillard. For any enquiries please contact conrad.gillard@gmail.com
     12# Export3col exporter adapted from Exportbracket by BHT
    1213from __future__ import division, print_function
    1314import wx
    1415import GSASIIpath
    15 GSASIIpath.SetVersionNumber("$Revision: 4874 $")
     16GSASIIpath.SetVersionNumber("$Revision$")
    1617import GSASIIIO as G2IO
    1718from collections import OrderedDict
     
    206207            wx.EndBusyCursor()
    207208        self.CloseFile()
     209
     210
     211class Export3col(G2IO.ExportBaseclass):
     212    '''Enables export of parameters that are commonly needed for publications, with esds
     213    in a separate column
     214    '''
     215
     216    def __init__(self, G2frame):
     217        G2IO.ExportBaseclass.__init__(self,G2frame=G2frame,formatName='common prm CSV',
     218            extension='.csv',longFormatName='Export commonly needed parameters with s.u. in a separate column')
     219        self.exporttype = ['project']
     220
     221    def ValEsd2col(self, param, param_sig):
     222        '''Return two values with the formated value as the first number and the
     223        standard uncertainty (if provided) as the second value.
     224        '''
     225        col1 = ValEsd(param, -abs(param_sig))
     226        col2 = ''
     227        if param_sig > 0:
     228            col2 = ValEsd(param_sig, -param_sig/100)
     229        return col1,col2           
     230       
     231    def Exporter(self, event=None):
     232       
     233        # Define function to extract parameter and sigma from covariances, for later use
     234        def GetParamSig(phase_num, hist_num, keyword, display_name):
     235            param_index = None
     236            try:
     237                param_index = self.OverallParms['Covariance']['varyList'].index(phase_num + ':' + hist_num + keyword)
     238            except:
     239                pass
     240            if param_index is not None:
     241                param = self.OverallParms['Covariance']['variables'][param_index]
     242                # Extract parameter uncertainty
     243                param_sig = self.OverallParms['Covariance']['sig'][param_index]
     244                # Create dictionary entry containing parameter and sigma in bracket notation
     245                model_parameters[display_name] = self.ValEsd2col(param, param_sig)
     246
     247        # # set up for export
     248        self.InitExport(event)
     249        if self.ExportSelect(): return  # set export parameters; get file name
     250        self.OpenFile()
     251        wx.BeginBusyCursor()
     252
     253        # Export model parameters in bracket notation
     254        try:
     255            # Initialise ordered dictionary to hold model parameters and uncertainties
     256            model_parameters = OrderedDict()
     257
     258            # load all of the tree into a set of dicts
     259            self.loadTree()
     260            # create a dict with refined values and their uncertainties
     261            self.loadParmDict()
     262
     263            # Initialise phase counter, for later use
     264            phase_num = 0
     265            # Extract lattice parameters and uncertainties, and convert to bracket notation
     266            for phasedict in self.Phases.items():
     267                phasenam = phasedict[0]
     268                cellList, cellSig = self.GetCell(phasenam)
     269                # Initialise lattice parameter letter
     270                lp_letter = "a"
     271                for i in range(0, len(cellList)):
     272                # for cell in cellList:
     273                    if cellSig[i] > 0:
     274                        # Formulate lattice parameter
     275                        model_parameters[phasenam + " " + lp_letter + " (Ã
     276)"] = self.ValEsd2col(cellList[i], cellSig[i])
     277                        # Increment lattice parameter letter
     278                        lp_letter = chr(ord(lp_letter[0]) + 1)
     279                    else:
     280                        break
     281
     282                # Get phase and weight fractions uncertainties, if they have been refined
     283                for hist_num,hist_name in enumerate(self.Histograms):
     284                    try:
     285                        # Get phase fraction uncertainty, if phase fractions have been refined
     286                        phasefrac_unc = self.sigDict[str(phase_num) + ':' + str(hist_num) + ':Scale']
     287                        # Get name of histogram associated with this phase, for later use
     288                        #hist_name = list(self.Histograms.keys())[hist_num]
     289                        # Extract phase fraction value
     290                        phasefrac = phasedict[1]['Histograms'][hist_name]['Scale'][0]
     291                        # Write phase if there is more than one histogram, specify which one
     292                        if len(self.Histograms) > 1:
     293                            model_parameters[phasenam + " Phase Fraction in: " + hist_name] = (
     294                                self.ValEsd2col(phasefrac, phasefrac_unc))
     295                        # If there is only one histogram, no need to specify which histogram the fraction is based on
     296                        else:
     297                            model_parameters[phasenam + " Phase Fraction"] = self.ValEsd2col(phasefrac, phasefrac_unc)
     298                    except:
     299                        pass
     300
     301                    try:
     302                        var = str(phase_num) + ':' + str(hist_num) + ':WgtFrac'
     303                        depSigDict = self.OverallParms['Covariance'].get('depSigDict',{})
     304                        weight_frac,weight_frac_unc = depSigDict.get(var,[0,None])
     305
     306                        # Write phase + weight fractions in bracket notation to dictionary, to be exported as a CSV
     307                        # If there is more than one histogram, specify which one the fraction is based on
     308                        if len(self.Histograms) > 1:
     309                            model_parameters[phasenam + " Weight Fraction in: " + hist_name] = (
     310                                self.ValEsd2col(weight_frac, weight_frac_unc))
     311                        # If there is only one histogram, no need to specify which histogram the fraction is based on
     312                        else:
     313                            model_parameters[phasenam + " Weight Fraction"] = self.ValEsd2col(weight_frac, weight_frac_unc)
     314                    except:
     315                        pass
     316
     317                    # Get preferred orientation details for phase, if refined
     318                    try:
     319                        pref_orr_props = phasedict[1]['Histograms'][hist_name]['Pref.Ori.']
     320                        # Check if March Dollase has been refined
     321                        if pref_orr_props[2] and pref_orr_props[0] == "MD":
     322                           # If so, first extract MD axis and write to dictionary to be exported
     323                           MD_axis = "\'" + ''.join(map(str, pref_orr_props[3]))
     324                           model_parameters[phasenam + " March Dollase Axis"] = (MD_axis,'')
     325                           # Next, extract MD ratio
     326                           MD_ratio = pref_orr_props[1]
     327                           MD_sig = self.sigDict[str(phase_num)+":" + str(hist_num) + ":MD"]
     328                           # Formulate MD ratio in bracket notation
     329                           MD_bracket = self.ValEsd2col(MD_ratio, MD_sig)
     330                           # Write MD ratio to dictionary to be exported
     331                           model_parameters[phasenam + " March Dollase Ratio"] = (MD_bracket,'')
     332                    except:
     333                        pass
     334                # Increment phase number counter
     335                phase_num += 1
     336
     337# Extract sample displacements, zero offset and D(ij)s (if refined)
     338            for i,hist_name in enumerate(self.Histograms):
     339                hist_num = str(i)
     340                # Extract zero offset, if refined
     341                GetParamSig("", hist_num, ':Zero', "Zero Offset")
     342                # Extract Bragg-Brentano sample displacement, if refined
     343                GetParamSig("", hist_num, ':Shift', "Sample Displacement (micron)")
     344                # Extract Debye-Scherrer sample X displacement, if refined
     345                GetParamSig("", hist_num, ':DisplaceX', "Sample X Displacement (micron)")
     346                # Extract Debye-Scherrer sample Y displacement, if refined
     347                GetParamSig("", hist_num, ':DisplaceY', "Sample Y Displacement (micron)")
     348                # Extract hydrostatic strains, if refined
     349                for phase_num,phase_name in enumerate(self.Phases):
     350                    for d_i in range(1, 4):
     351                        for d_j in range(1, 4):
     352                            GetParamSig(str(phase_num), hist_num, ':D' + str(d_i) + str(d_j),
     353                                        phase_name + ' D' + str(d_i) + str(d_j))
     354
     355                # Extract atomic parameters, if refined
     356                for phase_num,phase_name in enumerate(self.Phases):
     357                    # atom_list = list(self.Phases.values())[phase_num]["Atoms"]
     358                    atom_list = self.Phases[phase_name]["Atoms"] #  same as above?
     359                    for atom_num,atom in enumerate(atom_list):
     360                        # Extract isotropic thermal parameters, if refined
     361                        GetParamSig(str(phase_num), ':', 'AUiso:' + str(atom_num),
     362                                    phase_name + ' ' + atom[0] + ' Uiso')
     363                        # Extract anisotropic thermal parameters (Uijs), if refined
     364                        for Ui in range(1, 4):
     365                            for Uj in range(1, 4):
     366                                GetParamSig(str(phase_num), ':', 'AU' + str(Ui) + str(Uj) + ':' + str(atom_num),
     367                                            phase_name + ' ' + atom[0] + ' U' + str(Ui) + str(Uj))
     368                        # Extract fractional occupancies, if refined
     369                        GetParamSig(str(phase_num), ':', 'Afrac:' + str(atom_num),
     370                                    phase_name + ' ' + atom[0] + ' Occupancy')
     371                        # Extract atom X Y Z, if refined
     372                        for atom_axis in ('x', 'y', 'z'):
     373                            variable_code = str(phase_num) + ':' + ':' + 'dA' + atom_axis + ':' + str(atom_num)
     374                            # Get sigma, if refined
     375                            try:
     376                                param_index = self.OverallParms['Covariance']['varyList'].index(variable_code)
     377                                # Extract uncertainty
     378                                atom_axis_sig = self.OverallParms['Covariance']['sig'][param_index]
     379                                # Extract value
     380                                atom_axis_val = list(self.Phases.values())[phase_num]["Atoms"][atom_num][ord(atom_axis)-117]
     381                                # Convert to bracket notation and add to dictionary, which will be exported as a CSV
     382                                model_parameters[phase_name + ' ' + atom[0] + ' ' + atom_axis] = \
     383                                    self.ValEsd2col(atom_axis_val, atom_axis_sig)
     384                            except: pass
     385
     386            # Extract rWp
     387            rWP = self.OverallParms['Covariance']['Rvals']['Rwp']
     388            # Write to dictionary to be printed, rounding to 3 significant figures for readability
     389            model_parameters["wR"] = (ValEsd(rWP, -0.1) + '%', '')
     390
     391            # Write to CSV
     392            for name in model_parameters:
     393                self.Write('{:}, {:}, {:}'.format(name,*model_parameters[name]))
     394
     395        finally:
     396            wx.EndBusyCursor()
     397        self.CloseFile()
     398       
Note: See TracChangeset for help on using the changeset viewer.