简体   繁体   English

我将如何在 Python 中使用 output 拟合数据以用于 Origin

[英]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.我有一个读取 50 个文本文件的代码,每个文件生成一个直方图,并且为每个直方图拟合一个高斯。 The area under each gaussian is then taken and plotted against time (which is essentially which text file it was multiplied by 18).然后获取每个高斯下的区域并根据时间绘制(本质上是它乘以 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.我可以获取代码以从图表中打印出 y 值,但我正在努力将其更改为可以复制并粘贴到原始电子表格格式的表单。

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!而且我猜我只写了另一个变量 0, 18, 36, 54... 所以 python 可能不需要!

Update Relevant code example was requested.更新请求了相关的代码示例。 I think this is a minimal example.我认为这是一个最小的例子。 The relevant variable I'm trying ot output is amps.我正在尝试的 output 的相关变量是安培。 I don't mind if this done via saving a file (probably prefered) or in the IDE console.我不介意这是通过保存文件(可能是首选)还是在 IDE 控制台中完成的。

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如果您使用的是最近的 Origin,您可以使用 originpro 模块来传输数据

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有关更多信息,请查看他们的文档页面: 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:如果想法是将您的ampsampserrts的值打印到文件中以供以后操作,您可能会执行以下操作:

    ## 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.如果不是,请细化问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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