[关闭]
@zhouhuibin 2023-03-15T07:15:41.000000Z 字数 1861 阅读 86

Python程序中涉及到的子函数

博士后出站报告附录


import math
import numpy as np
import os
from scipy import interpolate


def arcsin(x):
    y_asin = []
    for i in range(len(x)):
        y_asin.append(math.asin(x[i]))
    return y_asin

def arccos(x):
    y_acos = []
    for i in range(len(x)):
        y_acos.append(math.acos(x[i]))
    return y_acos

def arctan(x):
    y_atan = []
    for i in range(len(x)):
        y_atan.append(math.atan(x[i]))
    return y_atan

def arccot(x):
    y_acot = []
    for i in range(len(x)):
        y_acot.append(math.acot(x[i]))
    return y_acot

def cot(x):
    return np.cos(x)/np.sin(x)

def dataoutput(name,unit,comment,data,path,filename):
    title = np.r_[[name],[unit],[comment]]
    text = np.r_[title,data]
    file = os.path.join(path,filename)
    np.savetxt(file,text,fmt='%s')

def mkdir(path):  # 创建目标文件夹
    # 引入模块
    import os

    # 去除首位空格
    path=path.strip()
    # 去除尾部 \ 符号
    path=path.rstrip("\\")

    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists=os.path.exists(path)

    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(path) 

        print (path+' Created successfully')
        return path
    else:
        # 如果目录存在则不创建,并提示目录已存在
        print (path+' Directory already exists')
        return path

def biSection(a, b, limit, f):
    while b - a > limit:
        x_mid = (a+b)/2
        y_mid = f(x_mid)
        if y_mid == 0:
            x_0 = x_mid
            break
        elif (f(a)*f(b)>0):
            print ('There is no solution in (a,b)')
        elif (f(a)*f(x_mid)<0):
            b = x_mid
        elif (f(a)*f(x_mid)>0):
            a = x_mid
        if abs(a-b) < limit:
            x_0 = x_mid
            break
    return x_0

def dydx(x,y):
    f = []
    for i in range(len(x)):
        if i == 0:
            f_i = (y[i+1]-y[i])/(x[i+1]-x[i])
        elif i == len(x)-1:
            f_i = (y[i]-y[i-1])/(x[i]-x[i-1])
        else:
            f_i = 1/2*((y[i+1]-y[i])/(x[i+1]-x[i])+(y[i]-y[i-1])/(x[i]-x[i-1]))
        f.append(f_i)
    return f

def Error(x,y,x_0,Delta_x):
    dy_dx = dydx(x,y)
    dy_dx0 = interpolate.interp1d(x, dy_dx, kind='linear')(x_0)
    f = dy_dx0*Delta_x
    return f

def FWHM(x,y):
    y_max = max(y)
    if y_max == 0:
        fwhm = 0
        x_center = 0
    else:
        index_max = np.argwhere(y==y_max)[0,0]
        x_center = x[index_max]
        half_max = 0.5*y_max
        x1 = x[0:index_max+1]
        y1 = y[0:index_max+1]
        x2 = x[index_max:]
        y2 = y[index_max:]
        x_01 = interpolate.interp1d(y1, x1, kind='linear')(half_max)
        x_02 = interpolate.interp1d(y2, x2, kind='linear')(half_max)
        fwhm = x_02 - x_01
    return x_center,fwhm
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注