Changeset 5022 for trunk


Ignore:
Timestamp:
Sep 10, 2021 12:02:16 PM (4 years ago)
Author:
toby
Message:

Add originpro export from Conrad Gillard (conrad.gillard@…); needs testing

Location:
trunk
Files:
1 added
1 edited

Legend:

Unmodified
Added
Removed
  • TabularUnified trunk/GSASIIplot.py

    r5018 r5022  
    38423842        plotOpt['fmtChoices'].append('Grace input file, agr')
    38433843        plotOpt['fmtChoices'].append('Igor Pro input file, itx')
     3844        if sys.platform == "win32":
     3845            plotOpt['fmtChoices'].append('OriginPro file, opju')
    38443846        if plotOpt['format'] is None:
    38453847            if 'pdf' in fmtDict:
     
    41594161        print('file',filename,'written')
    41604162
     4163    def CopyRietveld2Origin(Pattern,Plot,Page,plotOpt,G2frame):
     4164        # Exports plot to Origin. This function was written by Conrad Gillard (conrad.gillard@gmail.com).
     4165
     4166        def origin_shutdown_exception_hook(exctype, value, tracebk):
     4167            '''Ensures Origin gets shut down if an uncaught exception'''
     4168            try:
     4169                op.exit()
     4170            except:
     4171                pass
     4172            print('\n****OriginPro error****')
     4173            import traceback
     4174            traceback.print_exception(exctype, value, tracebk)
     4175            G2G.G2MessageBox(G2frame,
     4176                'Failed to connect to OriginPro. Is it installed?\nSee console window for more info.')
     4177            #sys.__excepthook__(exctype, value, tracebk)
     4178
     4179        # Function to increase line width, for later use
     4180        def increase_line_width(plot):
     4181            layr = op.GLayer(plot.layer)
     4182            pindex = plot.index()
     4183            pname = layr.obj.GetStrProp(f'plot{pindex + 1}.name')
     4184            layr.lt_exec(f'set {pname} -w 1000')
     4185       
     4186        import itertools # delay this since not commonly called or needed
     4187
     4188        try:
     4189            import originpro as op
     4190        except:
     4191            note1,note2 = '',''
     4192            # get pip location
     4193            pyPath = os.path.split(os.path.realpath(sys.executable))[0]
     4194            import shutil
     4195            if shutil.which('pip'):
     4196                pip = shutil.which('pip')
     4197            elif os.path.exists(os.path.join(pyPath,'pip.exe')):
     4198                pip = os.path.join(pyPath,'pip.exe')
     4199            elif os.path.exists(os.path.join(pyPath,'Scripts','pip.exe')):
     4200                pip = os.path.join(pyPath,'Scripts','pip.exe')
     4201            else:
     4202                note1 = "\nNote pip not found, you may need to install that too\n"
     4203                pip = 'pip'
     4204            try:
     4205                import win32clipboard
     4206                win32clipboard.OpenClipboard()
     4207                win32clipboard.EmptyClipboard()
     4208                win32clipboard.SetClipboardText('{} install originpro'.format(pip))
     4209                win32clipboard.CloseClipboard()
     4210                note2 = "\nNote: command copied to clipboard (use control-C to paste in cmd.exe window)"
     4211            except:
     4212                pass
     4213            msg = """Use of the OriginPro exporter requires that OriginPro be
     4214installed on your computer as well as a communication
     4215module (originpro) via pip.
     4216{}
     4217Use command
     4218
     4219\t{} install originpro
     4220
     4221in a cmd.exe window to do this.
     4222{}""".format(note1,pip,note2)
     4223            G2G.G2MessageBox(G2frame,msg)
     4224            return
     4225       
     4226        lblList = []
     4227        valueList = []
     4228
     4229        lblList.append('Axis-limits')
     4230        valueList.append(list(Plot.get_xlim())+list(Plot.get_ylim()))
     4231
     4232        tickpos = {}
     4233
     4234        for i,l in enumerate(Plot.lines):
     4235            if l.get_label() in ('obs','calc','bkg','zero','diff'):
     4236                lbl = l.get_label()
     4237            elif l.get_label()[1:] in ('obs','calc','bkg','zero','diff'):
     4238                lbl = l.get_label()[1:]
     4239            else:
     4240                lbl = l.get_label()
     4241            if 'magline' in lbl:
     4242                pass
     4243            elif lbl in ('obs','calc','bkg','zero','diff'):
     4244                if lbl == 'obs':
     4245                    lblList.append('x')
     4246                    valueList.append(l.get_xdata())
     4247                c = plotOpt['colors'].get(lbl,l.get_color())
     4248                if sum(c) == 4.0: continue
     4249                lblList.append(lbl)
     4250                valueList.append(l.get_ydata())
     4251            elif l in Page.tickDict.values():
     4252                c = plotOpt['colors'].get(lbl,l.get_color())
     4253                if sum(c) == 4.0: continue
     4254                tickpos[lbl] = l.get_ydata()[0]
     4255                lblList.append(lbl)
     4256                valueList.append(l.get_xdata())
     4257        if tickpos:
     4258            lblList.append('tick-pos')
     4259            valueList.append([])
     4260            for i in tickpos:
     4261                valueList[-1].append(i)
     4262                valueList[-1].append(tickpos[i])
     4263        # add (obs-calc)/sigma [=(obs-calc)*sqrt(weight)]
     4264        lblList.append('diff/sigma')
     4265        valueList.append(Pattern[1][5]*np.sqrt(Pattern[1][2]))
     4266        if sum(Pattern[1][0].mask): # are there are excluded points? If so, add them too
     4267            lblList.append('excluded')
     4268            valueList.append(1*Pattern[1][0].mask)
     4269        # magnifcation values
     4270        for l in Plot.texts:
     4271            lbl = l.get_label()
     4272            if 'magline' not in lbl: continue
     4273            if l.xycoords == 'axes fraction':
     4274                lbl = 'initial-mag'
     4275                lblList.append(lbl)
     4276                valueList.append([l.get_text()])
     4277            else:
     4278                lbl = 'mag'
     4279                lblList.append(lbl)
     4280                valueList.append([l.get_text(),l.get_position()[0]])
     4281        # invert lists into columns, use iterator for all values
     4282        if hasattr(itertools,'zip_longest'): #Python 3+
     4283            invertIter = itertools.zip_longest(*valueList,fillvalue=' ')
     4284        else:
     4285            invertIter = itertools.izip_longest(*valueList,fillvalue=' ')
     4286
     4287        # Start Origin instance
     4288        if op and op.oext:
     4289            sys.excepthook = origin_shutdown_exception_hook
     4290
     4291        # Set Origin instance visibility
     4292        if op.oext:
     4293            op.set_show(True)
     4294        op.new()
     4295
     4296        # Create folder to hold data and graph
     4297        refinementName = G2frame.Label
     4298        refinementName = refinementName[17:-4]
     4299        fldr = op.po.RootFolder.Folders.Add(refinementName)
     4300        fldr.Activate()
     4301
     4302        # Create worksheet to hold refinement data
     4303        dest_wks = op.new_sheet('w', lname='Refinement Data')
     4304        dest_wks.cols = 5
     4305
     4306        # Import refinement data
     4307        colNamesList =["x", "Observed", 'Calculated','Background','(Obs-Calc)']
     4308        for i in range(1, 6):
     4309            dest_wks.from_list(col=i-1, data=valueList[i].tolist(), lname=colNamesList[i-1])
     4310
     4311        # Create graph object, to which data will be added
     4312        graph = op.new_graph(template=os.path.join(GSASIIpath.path2GSAS2,'OriginTemplate2.otpu'))
     4313        graph.lname = refinementName + "_G"
     4314        gl = graph[0]
     4315
     4316        # Plot observed as scatter
     4317        plot = gl.add_plot(dest_wks, coly=1, colx=0, type='scatter')
     4318        plot.symbol_size = 10
     4319        plot.symbol_kind = 7
     4320        plot.colormap = 'Classic'
     4321        plot.color = 1
     4322
     4323        # Plot calculated, background and difference as line
     4324        for i in range(2, 5):
     4325            plot = gl.add_plot(dest_wks, coly=i, colx=0, type='line')
     4326            plot.colormap = 'Classic'
     4327            plot.color = i
     4328            increase_line_width(plot)
     4329
     4330        # Import reflection data for each phase
     4331        tickPosIdx = lblList.index("tick-pos")
     4332        # Initialise counters for colour index and number of phases
     4333        j = 1
     4334        k = 1
     4335        refLegendText = ""
     4336        for i in range(7, tickPosIdx):
     4337            # Create worksheet to hold reflections data
     4338            dest_wks = op.new_sheet('w', lname=lblList[i] + " Reflections")
     4339            dest_wks.cols = 2
     4340            # Generate lists of tick positions
     4341            tickPosList = valueList[i].tolist()
     4342            # Generate lists of tick intensities
     4343            refIntens = valueList[tickPosIdx][(i - 6) * 2 - 1]
     4344            refIntens = float(refIntens)
     4345            refIntensList = [refIntens] * len(tickPosList)
     4346            # Import tick positions and intensities to worksheet
     4347            dest_wks.from_list(col=0, data=tickPosList, lname="Tick Position")
     4348            dest_wks.from_list(col=1, data=refIntensList, lname="Tick Intensity")
     4349            # Add reflections to plot
     4350            plot = gl.add_plot(dest_wks, coly=1, colx=0, type='scatter')
     4351            plot.symbol_size = 10
     4352            plot.symbol_kind = 10
     4353            plot.color = 4 + j
     4354            refLegendText = refLegendText + "\l(" + str(4 + k) + ") " + lblList[i] + " "
     4355            # Increment phase counter
     4356            k += 1
     4357            # increment colour index, skipping yellow because it cannot be seen
     4358            if j == 2:
     4359                j += 2
     4360            else:
     4361                j += 1
     4362
     4363        #   # Set axis limits
     4364        xmin = Plot.get_xlim()[0]
     4365        if Plot.dataLim.x0 > xmin:
     4366            xmin = Plot.dataLim.x0 + 0.1
     4367        xmax = Plot.get_xlim()[1]
     4368        if Plot.dataLim.x1 < xmax:
     4369            xmax = Plot.dataLim.x1 + 0.1
     4370        gl.set_xlim(xmin, xmax)
     4371
     4372        ymin = Plot.get_ylim()[0]
     4373        ymax = Plot.get_ylim()[1]
     4374        gl.set_ylim(ymin, ymax)
     4375
     4376        # Change graph titles
     4377        gl.axis(ax="x").title = "2Ξ (°)"
     4378        gl.axis(ax="y").title = "Intensity (Arbitrary units)"
     4379
     4380        # Set up legend
     4381        label = gl.label('Legend')
     4382        label.text = '\l(1) %(1)\l(2) %(2)\l(3) %(3)\l(4) %(4) %(CRLF)' + refLegendText
     4383
    41614384    def CopyRietveld2Igor(Pattern,Plot,Page,plotOpt,filename,G2frame):
    41624385        '''Copy the contents of the Rietveld graph from the plot window to
     
    44534676        longFormatName,typ = plotOpt['format'].split(',')
    44544677        fil = G2G.askSaveFile(G2frame,'','.'+typ.strip(),longFormatName)
    4455         if 'csv' in typ and fil:
     4678        if 'opju' in typ and fil:
     4679            CopyRietveld2Origin(Pattern,Plot,Page,plotOpt,G2frame)
     4680            dlg.EndModal(wx.ID_OK)
     4681        elif 'csv' in typ and fil:
    44564682            CopyRietveld2csv(Pattern,Plot,Page,fil)
    44574683            dlg.EndModal(wx.ID_OK)
Note: See TracChangeset for help on using the changeset viewer.