计算高斯误差传播的助手。
SecondaryValue的Python项目详细描述
二次值
这是一个实用程序,用于简化值及其
使用sympy
和numpy
从符号公式得出的不确定性。
安装
只要一个快速的pip install SecondaryValue
就行了。
示例
(很快就会有文件。现在:看看docstrings!)
基本用法
fromSecondaryValueimportSecondaryValue# create a secondary value# the argument can be either a string or a sympy expressionx=SecondaryValue("a*b/sqrt(c)")# Calculate a result value by substi3tuting the keyword arguments# where a keyword agument may consist of (value, error_1, error_2, ...)# and (...) stands for any iterable.result=x(a=(1,20),b=(2,30),c=2)# The calculation returns a numpy array with the length of the longest# keyword argument above: [value, error_1, error_2]# For each error_n the uncertainties error_n of the keyword args above are# used if present. This may be useful to calculate statistical and systemic# errors in one go.print(result)# >> (1.41421356, 35.35533906)# As a goodie, you can print out the gaussian error distribution in# symbolic form. (Works best in Jupyter Notebooks)x.pretty_gauss_propagation('a','b','c')
默认值
为了减少样板文件,可以设置符号的默认替换(有错误)。 这对常数特别有用。
fromSecondaryValueimportSecondaryValue# create a secondary value with default argumentsx=SecondaryValue("a + b",defaults=dict(b=1/2))# this works because `b` is substituted from the defaultsresult=x(b=1/2)print(result)# >> 1.0# As a goodie, you can print out the gaussian error distribution in# symbolic form. (Works best in Jupyter Notebooks)x.pretty_gauss_propagation('a','b','c')
矢量化输入
SecondaryValue
支持矢量化输入。作为重击的规则:放置
可以放置标量的iterable(list,np.array)。
只要所有的错误和值都是 标量或具有相同长度。
fromSecondaryValueimportSecondaryValuex=SecondaryValue('a**2+b')x(a=[[1,2,3]],b=1)# >> array([ 2., 5., 10.])x(a=([1,2,3],1),b=1)# >> (array([ 2., 5., 10.]), array([2., 4., 6.]))x(a=([1,2,3],[1,2,3]),b=1)# >> (array([ 2., 5., 10.]), array([ 2., 8., 18.]))x(a=([1,2,3],[1,2,3]),b=([1,2,3],1))# >> (array([ 2., 6., 12.]), array([ 2.23606798, 8.06225775, 18.02775638]))# THAT DOES NOT WORK:x(a=([1,2,3],[1,2,3]),b=([1,2],1))
如果元组中返回的所有数组都具有相同的形状,则可以
轻松地将元组转换为numpy数组:
np.array(x(a=([1,2,3], [1,2,3]), b=([1,2,3], 1)))
依赖性
为了简化复杂值的计算,可以定义
依赖于aSecondaryValue
:
fromSecondaryValueimportSecondaryValuedep=SecondaryValue('u')x=SecondaryValue("a + b",dependencies=dict(a=dep))# x will now accept u as an additional kwarg and calculate d==dep on the fly# and return a dictionary containing it as a second return value if you# specify `retdeps=True`.print(x(b=1,u=(1,2),retdeps=True))# >> ((2.0, 2.0), {'a': ((1.0, 2.0), {})})# To make the output predictable, the dependencies aren't returned by deafult.print(x(b=1,u=(1,2)))# >> (2.0, 2.0)# you can overwrite the dependency calculationprint(x(b=1/2,a=1/2))# >> 1.0
如果没有依赖项值,则当
retdeps=True
已指定。