简体   繁体   中英

How would I output fitting data in Python for use in Origin

I have a code that reads in 50 text files, each one generates a histogram, and a gaussian is fitted for each histogram. The area under each gaussian is then taken and plotted against time (which is essentially which text file it was multiplied by 18).

I would like to then manipulate this data separately in origin. I can get the code to print out the y values from the graph, but am struggling to change it into a form that could be copied and pasted into a spreadsheet format like origin's.

The print out was:

77.78630383833547, 62.92926582239441, 63.84025706577048, 55.489066870438165, 38.60797989548756, 40.771390484048545, 14.679073842876978, 33.95959972488966, 29.41960790300141, 32.93241034391399, 30.927428194781815, 31.086396885182356, 21.52771899125612, 4.27684299160886, 6.432975528727562, 7.500376934048583, 18.730555740591637, 4.355896959987761, 11.677509915219987, 12.865482314301719, 0.6120306267606219, 12.614420497451556, 2.2025029753442404, 9.447046999592711, 4.0688197216393425, 0.546672901996845, 1.12780050608251, 2.2030852358874635, 2.202804718915858, 0.5726686031033587, 0.5465322281618783, 0.5185100682386156, 0.575055917739342, 0.5681697592593679

Full code is here , if required. And I guess the other variable I just write 0, 18, 36, 54... so python probably isn't needed for that!

Update Relevant code example was requested. I think this is a minimal example. The relevant variable I'm trying ot output is amps. I don't mind if this done via saving a file (probably prefered) or in the IDE console.

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from numpy import exp, loadtxt, pi, sqrt, random, linspace
from lmfit import Model
import glob, os

## Define gaussian
def gaussian(x, amp, cen, wid):
    """1-d gaussian: gaussian(x, amp, cen, wid)"""
    return (amp / (sqrt(2*pi) * wid)) * exp(-(x-cen)**2 / (2*wid**2))

## Define exponential decay
def expdecay(x, t, A): 
     return A*exp(-x/t)

## Define constants
fileToRun = 'Run0'
location = 'ControlRoom6'
stderrThreshold = 10
minimumAmplitude = 0.1
approxcen = 780
DeadTime = 3
LiveTime = 15


## Get location of files to be loaded

## Define paramaters
amps = []; ampserr = []; ts = []
folderToAnalyze = baseFolder + fileToRun + '\\'

## Generate the time array and coincidence plots
for n in range(0, numfiles):
    
    ## Load text file
    x = np.linspace(0, 8191, 8192)
    finalprefix = str(n).zfill(3)
    fullprefix = folderToAnalyze + prefix + finalprefix
    y = loadtxt(fullprefix + ".Spe", skiprows= 12, max_rows = 8192) 

    ## Make figure and label
    fig, ax = plt.subplots(figsize=(15,8))

    ## Plot data
    ax.bar(x, y)
    ax.set_xlim(600,960)
    
    # Fit data to a gaussian
    gmodel = Model(gaussian)
    result = gmodel.fit(y, x=x, amp=8, cen=approxcen, wid=1)
        
    ## Append to list if error in amplitude and amplitude itself is within reasonable bounds
    if result.params['amp'].stderr < stderrThreshold and result.params['amp'] > minimumAmplitude:
        amps.append(result.params['amp'].value) 
        ampserr.append(result.params['amp'].stderr) 
        ts.append(MaestroT*n)

## Plot decay curve
print(amps)
fig, ax = plt.subplots()
ax.errorbar(ts, amps, yerr= 2*np.array(ampserr), fmt="ko-", capsize = 5, capthick= 2, elinewidth=3, markersize=5)
plt.xlabel('Time', fontsize=14)
plt.ylabel('Peak amplitude', fontsize=14)
plt.title("Decay curve of P-31 by $β^+$ emission", fontsize=14)
    
## Fit decay curve

If you're using the recent Origin, you can use originpro module to transfer the data

import originpro as op
import pandas as pd

# balabalabala

df = pd.DataFrame(list(zip(ts, amps, ampserr)), columns=['ts', 'Amp', 'Err']) # create a dataframe
op.find_sheet('w').from_df(df) # import dataframe to activated worksheet

While if you're using old version, you will have to save the data as a file. For more information please check their document page: https://www.originlab.com/python/doc/originpro/index.html

If the idea is print out your values of amps , ampserr , and ts to a file for later manipulation, you might do something like this:

    ## Append to list if error in amplitude and amplitude itself is within reasonable bounds
    if result.params['amp'].stderr < stderrThreshold and result.params['amp'] > minimumAmplitude:
        amps.append(result.params['amp'].value) 
        ampserr.append(result.params['amp'].stderr) 
        ts.append(MaestroT*n)

## convert results to list of strings for csv file
buffer = ['# fit results ...']
for _t, _a, _e in zip(ts, amps, ampserr):
    buff.append("{:.8g}, {:.8g}, {:.8g}".format(_t, _a, _e))
buff.append('')
## save results
with open('results.csv', 'w') as fh:
     f.write('\n'.join(buffer))
         

Hope that helps with the problem you are having. If not, please refine the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM