Exemplo n.º 1
0
def run_gsasii_test_2():
    import os, sys
    sys.path.insert(0, '/Users/lrebuffi/Documents/Workspace/Wonder/GSAS-II-WONDER-OSX/GSAS-II-WONDER')  # needed to "find" GSAS-II modules

    datadir = "/Users/lrebuffi/Documents/Workspace/Wonder/GSAS-TEST"

    import GSASIIscriptable as G2sc

    PathWrap = lambda fil: os.path.join(datadir, fil)
    gpx = G2sc.G2Project(newgpx=PathWrap('pkfit.gpx'))
    hist = gpx.add_powder_histogram(PathWrap('FAP.XRA'), PathWrap('INST_XRY.PRM'),
                                    fmthint='GSAS powder')
    hist.set_refinements({'Limits': [16., 24.],
                          'Background': {"no. coeffs": 2, 'type': 'chebyschev-1', 'refine': True}
                          })
    peak1 = hist.add_peak(1, ttheta=16.8)
    peak2 = hist.add_peak(1, ttheta=18.9)
    peak3 = hist.add_peak(1, ttheta=21.8)
    peak4 = hist.add_peak(1, ttheta=22.9)
    hist.set_peakFlags(area=True)
    hist.refine_peaks()
    hist.set_peakFlags(area=True, pos=True)
    hist.refine_peaks()
    hist.set_peakFlags(area=True, pos=True, sig=True, gam=True)
    hist.refine_peaks()
    print('peak positions: ', [i[0] for i in hist.PeakList])
    for i in range(len(hist.Peaks['peaks'])):
        print('peak', i, 'pos=', hist.Peaks['peaks'][i][0], 'sig=', hist.Peaks['sigDict']['pos' + str(i)])
    hist.Export_peaks('pkfit.txt')

    return hist
Exemplo n.º 2
0
    def _initialise_GSAS(self):
        """
        Initialise a GSAS project object with a spectrum and an instrument parameter file
        :return: GSAS project object
        """
        gsas_path = self.getPropertyValue(self.PROP_PATH_TO_GSASII)
        sys.path.append(gsas_path)
        try:
            global GSASII
            global GSASIIlattice
            global GSASIIspc
            global GSASIImath
            import GSASIIscriptable as GSASII
            import GSASIIlattice
            import GSASIIspc
            import GSASIImath
        except ImportError:
            error_msg = "Could not import GSAS-II. Are you sure it's installed at {}?".format(gsas_path)
            logger.error(error_msg)
            raise ImportError(error_msg)

        gsas_proj_path = self.getPropertyValue(self.PROP_GSAS_PROJ_PATH)
        gsas_proj = GSASII.G2Project(filename=gsas_proj_path)

        spectrum = self._extract_spectrum_from_workspace()
        spectrum_path = self._save_temporary_fxye(spectrum=spectrum)

        inst_param_path = self.getPropertyValue(self.PROP_PATH_TO_INST_PARAMS)
        gsas_proj.add_powder_histogram(datafile=spectrum_path, iparams=inst_param_path, fmthint="xye")

        self._remove_temporary_fxye(spectrum_path=spectrum_path)

        return gsas_proj
Exemplo n.º 3
0
    def initialize(self):

        # create a GSAS-II project
        self.gpx = gsasii.G2Project(newgpx="{}.gpx".format(self.name))

        # add histograms
        for det in self.detectors:
            self.gpx.add_powder_histogram(det.data_file, det.detector_file)

        # add phases
        for phase in self.phases:
            self.gpx.add_phase(phase.phase_file,
                               phase.phase_label,
                               histograms=self.gpx.histograms())

        # turn on background refinement
        args = {
            "Background": {
                "no. coeffs": 3,
                "refine": True,
            }
        }
        for hist in self.gpx.histograms():
            hist.set_refinements(args)

        # refine
        self.gpx.do_refinements([{}])
        self.gpx.save("step_1.gpx")
    def __init__(self,
                 cif_file,
                 wavelength,
                 twotheta_min=0.0,
                 twotheta_max=180.0):
        self.__data = {}

        GSASII_MODE = QSettings().value("output/wonder-default-gsasii-mode",
                                        GSASII_MODE_ONLINE, int)

        if GSASII_MODE == GSASII_MODE_ONLINE:
            gpx = G2sc.G2Project(newgpx=project_file)
            gpx.add_phase(cif_file, phasename="wonder_phase", fmthint='CIF')

            hist1 = gpx.add_simulated_powder_histogram(
                "wonder_histo",
                self.create_temp_prm_file(wavelength),
                twotheta_min,
                twotheta_max,
                0.01,
                phases=gpx.phases())

            gpx.data['Controls']['data'][
                'max cyc'] = 0  # refinement not needed
            gpx.do_refinements([{}])

            gsasii_data = hist1.reflections()["wonder_phase"]["RefList"]

            for item in gsasii_data:
                entry = GSASIIReflectionData(item[0], item[1], item[2],
                                             item[5], item[3], item[9])
                self.__data[entry.get_key()] = entry

        elif GSASII_MODE == GSASII_MODE_EXTERNAL:
            try:
                pipe = subprocess.Popen([
                    sys.executable,
                    self.create_python_script(
                        gsasii_dirname, gsasii_temp_dir,
                        os.path.join(gsasii_temp_dir, "gsasii_data.dat"),
                        project_file, cif_file,
                        self.create_temp_prm_file(wavelength), twotheta_min,
                        twotheta_max)
                ],
                                        stdout=subprocess.PIPE)

                gsasii_data = pickle.loads(pipe.stdout.read())
            except CalledProcessError as error:
                raise Exception(
                    "Failed to call GSAS-II: " +
                    ''.join(traceback.format_tb(error.__traceback__)))

            for item in gsasii_data:
                entry = GSASIIReflectionData(item[0], item[1], item[2],
                                             item[5], item[3], item[9])
                self.__data[entry.get_key()] = entry
Exemplo n.º 5
0
 def checkPDFselection():
     'Read PDF entry from input GPX file & show in GUI'
     pdfEntry = self.pdfSel.GetStringSelection()
     if not self.pdfList:
         self.params['ComputePDF'] = False
         lbl4b.Enable(False)
         return
     else:
         lbl4b.Enable(True)
     if pdfEntry not in [i.name for i in self.pdfList]:
         # strange something -- not selected
         self.pdfSel.SetSelection(0)
         pdfEntry = self.pdfSel.GetStringSelection()
     if self.gpxInp is None or self.gpxInp.filename != self.gpxin[3]:
         self.gpxInp = G2sc.G2Project(self.gpxin[3])
     try:
         PDFobj = self.gpxInp.pdf(pdfEntry)
     except KeyError:
         print("PDF entry not found: {}".format(pdfEntry))
         return
     histNames = [i.name for i in self.histList]
     for i, lbl in enumerate(
         ('Sample Bkg.', 'Container', 'Container Bkg.')):
         self.pbkg[i][4].SetValue(
             str(PDFobj.data['PDF Controls'][lbl]['Mult']))
         self.pbkg[i][6] = PDFobj.data['PDF Controls'][lbl]['Mult']
         try:
             i = 1 + histNames.index(
                 PDFobj.data['PDF Controls'][lbl]['Name'])
             self.pbkg[i][1].SetSelection(i)
         except ValueError:
             i = 0
             self.pbkg[i][1].SetSelection(0)
             if PDFobj.data['PDF Controls'][lbl]['Name']:
                 print('PDF {} hist entry {} not found'.format(
                     lbl, PDFobj.data['PDF Controls'][lbl]['Name']))
                 PDFobj.data['PDF Controls'][lbl]['Name'] = ''
     self.formula = ''
     for el in PDFobj.data['PDF Controls']['ElList']:
         i = PDFobj.data['PDF Controls']['ElList'][el]['FormulaNo']
         if i <= 0:
             continue
         elif i == 1:
             if self.formula: self.formula += ' '
             self.formula += '{}'.format(el)
         else:
             if self.formula: self.formula += ' '
             self.formula += '{}({:.1f})'.format(el, i)
     if not self.formula:
         self.formula = 'Error: no chemical formula'
     lbl5b.SetLabel(self.formula)
     TestInput()
Exemplo n.º 6
0
 def gpx(self):
     """Create a GSAS-II GPX project file.
     
     This file is necessary for further GSAS refinement operations.
     
     """
     if self._gpx is None:
         # Check if an existing file should be used
         gpx_fname = self.file_root + '.gpx'
         if os.path.exists(gpx_fname):
             gpx_kw = dict(gpxfile=gpx_fname)
         else:
             gpx_kw = dict(newgpx=gpx_fname)
         # Create the GPX project file
         self._gpx = gsas.G2Project(**gpx_kw)
         # Make any necessary parent directories
         dir_, fname = os.path.split(self._gpx.filename)
         if not os.path.exists(dir_):
             os.makedirs(dir_)
         # Save the newly created GPX file
         self._gpx.save()
     return self._gpx
Exemplo n.º 7
0
 def SetGPXInputFile():
     gpx = G2sc.G2Project(self.gpxin[3])
     self.imgList = gpx.images()
     self.histList = gpx.histograms()
     self.pdfList = gpx.pdfs()
     if not self.imgList:
         G2G.G2MessageBox(
             self, 'Error: no images in {}.'.format(self.gpxin[3]))
         return
     self.gpxin[1].SetValue(self.gpxin[3])
     self.imprm[1].Clear()
     self.imprm[1].AppendItems([i.name for i in self.imgList])
     if len(self.imgList) == 1:
         self.imprm[1].SetSelection(0)
     self.maskfl[1].Clear()
     self.maskfl[1].AppendItems([''] + [i.name for i in self.imgList])
     for i in range(3):
         self.pbkg[i][1].Clear()
         self.pbkg[i][1].AppendItems([''] +
                                     [i.name for i in self.histList])
     self.pdfSel.Clear()
     self.pdfSel.AppendItems([i.name for i in self.pdfList])
     showPDFctrls(None)
Exemplo n.º 8
0
def ProcessImage(newImage, imgprms, mskprms, xydata, PDFdict, InterpVals,
                 calcModes, outputModes):
    '''Process one image that is read from file newImage and is integrated into 
    one or more diffraction patterns and optionally each diffraction pattern can 
    be transformed into a pair distribution function.

    :param str newImage: file name (full path) for input image
    :param dict imgprms: dict with some nested lists & dicts describing the image
      settings and integration parameters
    :param dict mskprms: dict with areas of image to be masked
    :param dict xydata: contains histogram information with about background 
      contributions, used for PDF computation (used if ComputePDF is True)
    :param PDFdict: contains PDF parameters (used if ComputePDF is True)
    :param InterpVals: contains interpolation table (used if TableMode is True)
    :param tuple calcModes: set of values for which computations are 
      performed and how
    :param tuple outputModes: determines which files are written and where
    '''
    (TableMode, ComputePDF, SeparateDir, optPDF) = calcModes
    (outputSelect, PDFformats, fmtlist, outdir,
     multipleFmtChoices) = outputModes
    if SeparateDir:
        savedir = os.path.join(outdir, 'gpx')
        if not os.path.exists(savedir): os.makedirs(savedir)
    else:
        savedir = outdir
    outgpx = os.path.join(
        savedir,
        os.path.split(os.path.splitext(newImage)[0] + '.gpx')[1])
    gpxout = G2sc.G2Project(filename=outgpx)
    print('creating', gpxout.filename)
    # looped because a file can contain multiple images
    if TableMode:  # look up parameter values from table
        imgprms, mskprms = LookupFromTable(
            im.data['Image Controls'].get('setdist'), InterpVals)
    for im in gpxout.add_image(newImage):
        # apply image parameters
        im.setControls(imgprms)
        setdist = '{:.2f}'.format(
            im.getControls()
            ['setdist'])  # ignore differences in position less than 0.01 mm
        if setdist not in MapCache['distanceList']:
            if mskprms:
                im.setMasks(mskprms)
            else:
                im.initMasks()
            MapCache['distanceList'].append(setdist)
            MapCache['maskMap'][setdist] = G2sc.calcMaskMap(
                im.getControls(), im.getMasks())
            MapCache['ThetaAzimMap'][setdist] = G2sc.calcThetaAzimMap(
                im.getControls())
#        else: # debug
#            print('*** reusing',setdist)
#if mskprms:
#    im.setMasks(mskprms)
#else:
#    im.initMasks()
        hists = im.Integrate(MaskMap=MapCache['maskMap'][setdist],
                             ThetaAzimMap=MapCache['ThetaAzimMap'][setdist])
        # write requested files
        for dfmt in fmtlist:
            fmt = dfmt[1:]
            if not outputSelect[fmt]: continue
            if fmtlist[dfmt] is None: continue
            hint = ''
            if fmt in multipleFmtChoices:
                hint = multipleFmtChoices[fmt]
            if SeparateDir:
                savedir = os.path.join(outdir, fmt)
            else:
                savedir = outdir
            if not os.path.exists(savedir): os.makedirs(savedir)
            # loop over created histgrams (multiple if caked), writing them as requested
            for i, h in enumerate(hists):
                fname = h.name[5:].replace(' ', '_')
                #if len(hists) > 1:
                #GSASIIpath.IPyBreak_base()
                try:
                    fil = os.path.join(savedir, fname)
                    print('Wrote', h.Export(fil, dfmt, hint))
                except Exception as msg:
                    print('Failed to write {} as {}. Error msg\n{}'.format(
                        fname, dfmt, msg))
        if ComputePDF:  # compute PDF
            for h in hists:
                pdf = gpxout.copy_PDF(PDFdict, h)
                pdf.data['PDF Controls']['Sample']['Name'] = h.name
                xydata['Sample'] = h.data['data']
                fname = h.name[5:].replace(' ', '_')
                limits = h.data['Limits'][1]
                inst = h.data['Instrument Parameters'][0]
                pdf.calculate(copy.deepcopy(xydata), limits, inst)
                if optPDF:
                    for i in range(5):
                        if pdf.optimize(True, 5, copy.deepcopy(xydata), limits,
                                        inst):
                            break
                    pdf.calculate(copy.deepcopy(xydata), limits, inst)
                for fmt in PDFformats:
                    if not outputSelect[fmt]: continue
                    if SeparateDir:
                        savedir = os.path.join(
                            outdir,
                            fmt.replace("(", "_").replace(")", ""))
                    else:
                        savedir = outdir
                    pdf.export(os.path.join(savedir, fname), fmt)
    if outputSelect.get('gpx'):
        gpxout.save()
    else:
        del gpxout
Exemplo n.º 9
0
    def OnTimerLoop(self, event):
        '''A method that is called every :meth:`PollTime` seconds that is
        used to check for new files and process them. Integrates new images.
        Also optionally sets up and computes PDF. 
        This is called only after the "Start" button is pressed (then its label reads "Pause").
        '''

        if GSASIIpath.GetConfigValue('debug'):
            import datetime
            print("DBG_Timer tick at {:%d %b %Y %H:%M:%S}\n".format(
                datetime.datetime.now()))
        if self.PreventTimerReEntry: return
        self.PreventTimerReEntry = True
        self.ShowMatchingFiles(None)
        if not self.currImageList:
            self.PreventTimerReEntry = False
            return
        updateList = False

        # get input for integration
        imgprms = mskprms = None
        if not self.params['TableMode']:
            # read in image controls/masks, used below in loop. In Table mode
            # we will get this image-by image.
            gpxinp = G2sc.G2Project(self.gpxin[3])
            print('reading template project', gpxinp.filename)
            img = gpxinp.image(self.imprm[1].GetStringSelection())
            imgprms = img.getControls(True)
            if self.maskfl[1].GetStringSelection().strip():
                img = gpxinp.image(self.maskfl[1].GetStringSelection())
                mskprms = img.getMasks()
        # setup shared input for PDF computation (for now will not be table mode)
        xydata = {}
        if self.params['ComputePDF']:
            pdfEntry = self.pdfSel.GetStringSelection()
            try:
                PDFobj = gpxinp.pdf(pdfEntry)
            except KeyError:
                print("PDF entry not found: {}".format(pdfEntry))
            # update with GUI input
            for i, lbl in enumerate(
                ('Sample Bkg.', 'Container', 'Container Bkg.')):
                name = self.pbkg[i][1].GetStringSelection()
                try:
                    xydata[lbl] = gpxinp.histogram(name).data['data']
                except AttributeError:
                    pass
                PDFobj.data['PDF Controls'][lbl]['Mult'] = self.pbkg[i][6]
                PDFobj.data['PDF Controls'][lbl]['Name'] = name
        else:
            PDFobj = None
        if self.MPpool:
            self.MPpool.imap_unordered(
                ProcessImageMP, self.ArgGen(PDFobj, imgprms, mskprms, xydata))
        else:
            for intArgs in self.ArgGen(PDFobj, imgprms, mskprms, xydata):
                newImage = intArgs[0]
                print('processing ', newImage)
                ProcessImage(*intArgs)
                updateList = True
        for newImage in self.currImageList:
            self.ProcessedList.append(newImage)
        if updateList: self.ShowMatchingFiles(None)
        self.PreventTimerReEntry = False
        self.Raise()
def generate_sulfur_pdf(inputs=[]):

    import sys
    sys.path.append(inputs[1])

    def generate_charts(data, prefix, dest, xlabel, ylabel, volume):
        import plotly.graph_objects as go
        import plotly

        import numpy as np

        x, y = np.loadtxt(data, unpack=True)

        layout = go.Layout(
            title=prefix,
            xaxis=dict(
                title=xlabel
            ),
            yaxis=dict(
                title=ylabel
            ))

        fig = go.Figure(layout=layout, layout_xaxis_range=[0, 20], layout_yaxis_range=[-20, 20])
        rho = 1.0

        if ylabel == 'S(Q)':
            fig.add_shape(type='line',
                        x0=min(x),
                        y0=1,
                        x1=max(x),
                        y1=1,
                        line_dash="dash",
                        line=dict(color='Red'))

        if ylabel == 'G(R)':
            fig.add_shape(type='line',
                        x0=min(x),
                        y0=0,
                        x1=max(x),
                        y1=0,
                        line_dash="dash",
                        line=dict(color='Blue'))

            noa = 1 # Get from gpx PDF controls sample information->element
            #volume = 13.306 # Get from Sample information->formula volume
            fig.add_trace(go.Scatter(x=x[:250], y=-4*3.142*x*noa/volume,
                                name="Atomic Density Line",line=dict(color='Green')))

        line = dict(color="#ffe476")
        scatter = go.Scatter(x=x, y=y,
                             mode='lines',
                             line=dict(color="#003865"),
                             name='Sulfur')

        fig.add_trace(scatter)
        data = [scatter]
        div = plotly.offline.plot(data, include_plotlyjs=False, output_type='div')
        fig.write_html(dest + "/" + prefix + ".html")


    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.pyplot import axhline
    from matplotlib.axis import Axis
    import GSASIIscriptable as G2sc

    data = inputs[0]
    config = inputs[2]
    
    # Create workflow GSAS2 project
    gpx = G2sc.G2Project(data['filename'])
    sulfurImageFile = os.path.abspath(data['images']['Sulfur'])
    print(sulfurImageFile)
    # Get project images
    ceo2Image = gpx.images()[0]
    capillaryImage = gpx.images()[1]
    sulfurImage = gpx.images()[2]

    # Export sulfur image control settings so we can apply it to newly added images
    sulfurControlFile = os.path.abspath(data['export']['prefix']+'.imctrl')
    sulfurImage.saveControls(sulfurControlFile)

    # Apply sulfur image control settings to newly loaded sulfur image
    imageList = gpx.add_image(sulfurImageFile)
    newSulfurImage = imageList[0]
    newSulfurImage.loadControls(sulfurControlFile)

    sulfurPWDRList = newSulfurImage.Integrate()
    capillaryPWDRList = capillaryImage.Integrate()

    print("PDFs",gpx.pdfs())
    pdf =  gpx.pdfs()[0]  

    if config is not None:
        pdf.data['PDF Controls'].update(config)
        pdf.data['PDF Controls']['Container']['Name'] = capillaryPWDRList[0].name

    for i in range(5):
        if pdf.optimize():
            break

    pdf.calculate()

    pdf.export(data['export']['prefix'], 'I(Q), S(Q), F(Q), G(r)')

    gpx.save()

    x, y = np.loadtxt(data['export']['prefix'] + '.gr', unpack=True)

    plt.plot(x, y, label='Sulfur')
    fig = plt.figure(1)

    plt.title('Sulfur G(R)')
    plt.xlabel('x')
    plt.ylabel('y')

    axes = plt.gca()

    plt.xlim(data['limits']['xlim'])
    plt.ylim(data['limits']['ylim'])

    plt.savefig(data['outputfig'])
    os.makedirs(data['datadir'] + "/charts", exist_ok=True)
    volume = pdf.data['PDF Controls']['Form Vol']
    generate_charts(data['export']['prefix'] + '.gr', os.path.basename(data['export']['prefix']) + "-gr", data['datadir'] + "/charts", "Angstroms", "G(R)", volume)

    x, y = np.loadtxt(data['export']['prefix'] + '.sq', unpack=True)

    plt.plot(x, y, label='Sulfur')
    fig = plt.figure(1)

    plt.title('Sulfur S(Q)')
    plt.xlabel('x')
    plt.ylabel('y')

    axes = plt.gca()

    plt.xlim(data['limits']['xlim'])
    plt.ylim(data['limits']['ylim'])

    plt.savefig(data['outputfig'])
    os.makedirs(data['datadir'] + "/charts", exist_ok=True)
    generate_charts(data['export']['prefix'] + '.sq', os.path.basename(data['export']['prefix']) + "-sq", data['datadir'] + "/charts", "Inverse Angstroms", "S(Q)", volume)

    return True
Exemplo n.º 11
0
def import_refinements_gsas2(refinement_gpx,
                             hdf_groupname,
                             hdf_filename=DEFAULT_HDF_FILENAME,
                             gsas_path=DEFAULT_GSAS_PATH):
    # Try and import
    try:
        gsas
    except NameError:
        sys.path.append(str(Path(gsas_path).expanduser()))
        import GSASIIscriptable as gsas
    # Open the GPX project file
    project = gsas.G2Project(refinement_gpx)
    seq = project.seqref()
    enums = ['x', 'yobs', 'yweight', 'ycalc', 'background', 'residual']
    results = {k: [] for k in enums}
    param_rows = []
    filename_re = re.compile('(?:PWDR )?(.*)')
    phases = project.phases()
    histograms = project.histograms()
    for pattern in tqdm(histograms, desc="Importing"):
        # Extract the data
        data_list = pattern.data['data'][1]
        for key in enums:
            results[key].append(data_list[enums.index(key)])
        # Extract the refined parameters
        histname = pattern.data['data'][-1]
        sample_params = pattern.data['Sample Parameters']
        residuals = pattern.data['data'][0].get('Residuals', {})
        params = {
            'name': filename_re.match(pattern.data['data'][-1]).group(1),
            'displacement': sample_params['DisplaceX'][0],
            'pattern_scale': sample_params['Scale'][0],
            'absorption': sample_params['Absorption'][0],
            'wR': residuals.get('wR', np.nan),
        }
        # Get phase-histogram parameters
        for phase in phases:
            pid = phase['pId']
            params.update(_extract_cell_params(seq, pid, pattern.name))
            params.update(_extract_atom_params(seq, pid, pattern.name))
            try:
                hap_values = phase.getHAPvalues(pattern)
            except KeyError:
                continue
            params.update(_extract_hap_sizes(hap_values, pid))
            params.update(_extract_hap_strains(hap_values, pid))
            params.update(_extract_phase_weight(hap_values, phase, pid))
            params[f"{pid}:*:Scale"] = hap_values['Scale'][0]
        # Add overall weight fractions for the phases
        total_weight = np.nansum(
            [v for k, v in params.items() if k[-3:] == 'Wgt'])
        fracs = {
            f"{k}Frac": v / total_weight
            for k, v in params.items() if k[-3:] == 'Wgt'
        }
        params.update(fracs)
        # Add to the list of imported histograms
        param_rows.append(params)
    # Convert the data to numpy arrays
    for key in enums:
        results[key] = np.asarray(results[key])
    # Convert the refined parameters to a pandas dataframe
    metadata = pd.DataFrame.from_dict(param_rows, orient='columns')
    # Save to disk
    metadata.to_hdf(hdf_filename,
                    key=os.path.join(hdf_groupname, 'refinements',
                                     'parameters'))
    with h5py.File(hdf_filename, mode='a') as h5fp:
        base_grp = h5fp[hdf_groupname]
        for key in enums:
            ds_name = os.path.join('refinements', key)
            if ds_name in base_grp:
                del base_grp[ds_name]
            base_grp.create_dataset(ds_name, data=results[key])
Exemplo n.º 12
0
def generate_sulfur_pdf(inputs=[]):

    def generate_charts(data, prefix, dest, xlabel, ylabel):
        import plotly.graph_objects as go
        import plotly

        import numpy as np

        x, y = np.loadtxt(data, unpack=True)

        layout = go.Layout(
            title=prefix,
            xaxis=dict(
                title=xlabel
            ),
            yaxis=dict(
                title=ylabel
            ))
        # Create traces
        fig = go.Figure(layout=layout, layout_xaxis_range=[0, 20])
        line = dict(color="#ffe476")
        scatter = go.Scatter(x=x, y=y,
                             mode='lines',
                             line=dict(color="#003865"),
                             name='lines')
        fig.add_trace(scatter)
        data = [scatter]
        div = plotly.offline.plot(data, include_plotlyjs=False, output_type='div')
        fig.write_html(dest + "/" + prefix + ".html")

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.axis import Axis
    import GSASIIscriptable as G2sc

    data = inputs[0]

    filename = data['filename']
    ceo2ImageFile = data['images']['CeO2']
    ceo2ControlFile = data['controls']['CeO2']
    capillaryImageFile = data['images']['Capillary']
    capillaryControlFile = data['controls']['Capillary']
    sulfurImageFile = data['images']['Sulfur']
    sulfurControlFile = data['controls']['Sulfur']

    # Create workflow GSAS2 project
    gpx = G2sc.G2Project(filename=filename)

    # Load tif images
    gpx.add_image(ceo2ImageFile)
    gpx.add_image(capillaryImageFile)
    gpx.add_image(sulfurImageFile)

    ceo2Image = gpx.images()[0]
    capillaryImage = gpx.images()[1]
    sulfurImage = gpx.images()[2]

    ceo2Image.loadControls(ceo2ControlFile)
    capillaryImage.loadControls(capillaryControlFile)
    sulfurImage.loadControls(sulfurControlFile)

    sulfurPWDRList = sulfurImage.Integrate()
    capillaryPWDRList = capillaryImage.Integrate()

    sulfurPWDRList[0].SaveProfile('pwdr_Sulfur')
    capillaryPWDRList[0].SaveProfile('pwdr_Capillary')

    sulfurPowerFile = data['powders']['Sulfur']

    print(sulfurPWDRList)

    pdf = gpx.add_PDF(sulfurPowerFile, 0)

    pdf.set_formula(['S', 1])
    pdf.data['PDF Controls']['Container']['Name'] = capillaryPWDRList[0].name
    pdf.data['PDF Controls']['Container']['Mult'] = -0.988
    pdf.data['PDF Controls']['Form Vol'] = 13.306
    pdf.data['PDF Controls']['Geometry'] = 'Cylinder'
    pdf.data['PDF Controls']['DetType'] = 'Area Detector'

    pdf.data['PDF Controls']['ObliqCoeff'] = 0.2

    pdf.data['PDF Controls']['Flat Bkg'] = 5081
    pdf.data['PDF Controls']['BackRatio'] = 1.0
    pdf.data['PDF Controls']['Ruland'] = 0.1
    pdf.data['PDF Controls']['Lorch'] = True
    pdf.data['PDF Controls']['QScaleLim'] = [23.4, 26.0]
    pdf.data['PDF Controls']['Pack'] = 1.0
    pdf.data['PDF Controls']['Diam'] = 1.5
    pdf.data['PDF Controls']['Trans'] = 0.2
    pdf.data['PDF Controls']['Ruland'] = 0.1
    pdf.data['PDF Controls']['BackRatio'] = 0.184
    pdf.data['PDF Controls']['Rmax'] = 20.0

    for i in range(5):
        if pdf.optimize():
            break

    pdf.calculate()

    pdf.export(data['export']['prefix'], 'I(Q), S(Q), F(Q), G(r)')

    gpx.save()

    x, y = np.loadtxt(data['export']['prefix'] + '.gr', unpack=True)

    plt.plot(x, y, label='Sulfur')
    fig = plt.figure(1)

    plt.title('Sulfur G(R)')
    plt.xlabel('x')
    plt.ylabel('y')

    axes = plt.gca()

    plt.xlim(data['limits']['xlim'])
    plt.ylim(data['limits']['ylim'])

    plt.savefig(data['outputfig'])
    os.makedirs(data['datadir'] + "/charts", exist_ok=True)
    generate_charts(data['export']['prefix'] + '.gr', os.path.basename(data['export']['prefix']) + "-gr", data['datadir'] + "/charts", "heat", "G(R)")

    x, y = np.loadtxt(data['export']['prefix'] + '.sq', unpack=True)

    plt.plot(x, y, label='Sulfur')
    fig = plt.figure(1)

    plt.title('Sulfur S(Q)')
    plt.xlabel('x')
    plt.ylabel('y')

    axes = plt.gca()

    plt.xlim(data['limits']['xlim'])
    plt.ylim(data['limits']['ylim'])

    plt.savefig(data['outputfig'])
    os.makedirs(data['datadir'] + "/charts", exist_ok=True)
    generate_charts(data['export']['prefix'] + '.sq', os.path.basename(data['export']['prefix']) + "-sq", data['datadir'] + "/charts", "heat", "S(Q)")

    return True
Exemplo n.º 13
0
# sort list of phases by name
phases.sort()

# creating and setting projects
projs = []
proj_dirs = []
for powder in powders:
    # create dirs
    proj_dir = os.path.join(OUTDIR, powder[:powder.find('-')])
    proj_dirs.append(proj_dir)
    if os.path.exists(proj_dir):
        #os.rmdir(proj_dir)
        shutil.rmtree(proj_dir)
    os.makedirs(proj_dir)
    # create project
    gpx = G2sc.G2Project(newgpx=os.path.join(proj_dir, PNAME + PRJEXT))
    # add phases
    for phase in phases:
        gpx.add_phase(os.path.join(INDIR, phase))
    # add powder data
    gpx.add_powder_histogram(datafile=os.path.join(INDIR, powder),
                             iparams=os.path.join(INDIR, PRM),
                             phases='all')
    #	# set controls
    gpx.set_Controls('cycles', 10)
    # save project
    gpx.save()
    #	print(gpx)
    projs.append(gpx)

# ----------------------------------------------
Exemplo n.º 14
0
    """
    print(u"*** profile Rwp, " + os.path.split(gpx.filename)[1])
    for hist in gpx.histograms():
        print("\t{:20s}: {:.2f}".format(hist.name,hist.get_wR()))
    print("")

# where files will be written
work_dir = "tmp_gsasii"
if not os.path.exists(work_dir):
    os.mkdir(work_dir)

# where data files are stored
data_dir = os.getcwd()

# create a GSAS-II project
gpx = gsasii.G2Project(newgpx=os.path.join(work_dir, "PbSO4.gpx"))

# add histograms
hist1 = gpx.add_powder_histogram(
                          os.path.join(data_dir,"PBSO4.xra"),
                          os.path.join(data_dir,"INST_XRY.prm"))
hist2 = gpx.add_powder_histogram(
                          os.path.join(data_dir,"PBSO4.cwn"),
                          os.path.join(data_dir,"inst_d1a.prm"))

# add phase
phase1 = gpx.add_phase(os.path.join(data_dir, "PbSO4-Wyckoff.cif"),
                       phasename="PbSO4",
                       histograms=[hist1, hist2])

# increase number of cycles to improve convergence
Exemplo n.º 15
0
    def compute(self):

        # create a GSAS-II project
        self.gpx = gsasii.G2Project("step_1.gpx")
        self.gpx.save("step_2.gpx")

        # change lattice parameters
        for phase in self.gpx["Phases"].keys():

            # ignore data key
            if phase == "data":
                continue

            # handle PBSO4 phase
            elif phase == "PBSO4":
                cell = self.gpx["Phases"][phase]["General"]["Cell"]
                a, b, c = self.get("PBSO4_A"), self.get("PBSO4_B"), self.get(
                    "PBSO4_C")
                t11, t22, t33 = cell[1] / a, cell[2] / b, cell[3] / c
                self.gpx["Phases"][phase]["General"][
                    "Cell"][1:] = lattice.TransformCell(
                        cell[1:7],
                        [[t11, 0.0, 0.0], [0.0, t22, 0.0], [0.0, 0.0, t33]])

            # otherwise raise error because refinement plan does not support this phase
            else:
                raise NotImplementedError(
                    "Refinement plan cannot handle phase {}".format(phase))

        # turn on unit cell refinement
        args = {
            "set": {
                "Cell": True,
            }
        }

        # refine
        self.gpx.set_refinement(args)
        self.gpx.do_refinements([{}])

        # get histograms and phases
        hist1, hist2 = self.gpx.histograms()
        phase1 = self.gpx.phases()[0]

        # turn on Dij terms (HAP) for phase 1 only
        args6 = {
            "set": {
                "HStrain": True
            },
            "histograms": [hist1],
            "phases": [phase1],
        }

        # turn on size and strain broadening (HAP) for histogram 1 only
        args7 = {
            "set": {
                "Mustrain": {
                    "type": "isotropic",
                    "refine": True,
                },
                "Size": {
                    "type": "isotropic",
                    "refine": True
                },
            },
            "histograms": [hist1],
        }

        # turn on sample parameters and radius (Hist)
        # turn on atom parameters (phase)
        args8a = {
            "set": {
                "Sample Parameters": ["Shift"]
            },
            "histograms": [hist1],
            "skip": True,
        }
        args8b = {
            "set": {
                "Atoms": {
                    "all": "XU",
                },
                "Sample Parameters": ["DisplaceX", "DisplaceY"],
            },
            "histograms": [hist2],
        }

        # change data limits and instrument parmeter refinements (Hist)
        args9a = {
            "set": {
                "Limits": [16.0, 158.4],
            },
            "histograms": [hist1],
            "skip": True,
        }
        args9b = {
            "set": {
                "Limits": [19.0, 153.0],
            },
            "histograms": [hist2],
            "skip": True,
        }
        args9c = {
            "set": {
                "Instrument Parameters": ["U", "V", "W"],
            },
        }

        # change number of cycles and radius
        self.gpx.data["Controls"]["data"]["max cyc"] = 8
        hist2.data["Sample Parameters"]["Gonio. radius"] = 650.0

        # refine
        args_list = [args6, args7, args8a, args8b, args9a, args9b, args9c]
        self.gpx.do_refinements(args_list)

        # get minimization statistic
        stat = self.gpx["Covariance"]["data"]["Rvals"]["Rwp"]

        return stat