如何在 python 3 中接收元组作为函数的参数?

How to receive tuple as an argument to a function in python 3?

我有一些代码在 python2 中运行良好。我需要将其翻译成 python3。 有一段看不懂怎么改编。

这是一些代码。

函数有错误

def gauss((x, y), x0, y0, intens, sigma):
    return intens*numpy.exp(-(numpy.power(x-x0, 2)+numpy.power(y-y0, 2))/(2.*sigma**2)).ravel()

调用函数

def dofwhm(psfdata):
    x = numpy.arange(psfdata.shape[1])
    y = numpy.arange(psfdata.shape[0])
    x, y = numpy.meshgrid(x, y)
    popt, pcov = opt.curve_fit(gauss, (x, y), psfdata.ravel(), p0=[psfdata.shape[1]/2, psfdata.shape[0]/2, psfdata[psfdata.shape[1]/2, psfdata.shape[0]/2], 5.0])

    return 2.355*abs(popt[3])

我得到的错误是

Traceback (most recent call last):
  File "catalog.py", line 8, in <module>
    import cutPsf
  File "/Users/igor/GALPHAT/pypygalphat/preprocessingNew/cutPsf.py", line 9
    def gauss((x, y), x0, y0, intens, sigma):
              ^
SyntaxError: invalid syntax

有人可以帮助我如何调整它以适应 python3 吗?

更新: 好吧,@hpaulj 的回答似乎是正确的。我发现有将 Python2 代码转换为 Python3 代码的例程。在 运行 目标文件 2to3 -w cutPsf.py 之后,我从 hpaulj 得到了建议的解决方案。不幸的是,它会导致休闲错误:

Traceback (most recent call last):
  File "catalog.py", line 323, in <module>
    cutPsf.run(tempDir+galaxy.psffile, outDirFits+galaxy.psffile)
  File "/Users/igor/GALPHAT/pypygalphat_p3/preprocessingNew/cutPsf.py", line 63, in run
    coeffwhm = dofwhm(newPsf)
  File "/Users/igor/GALPHAT/pypygalphat_p3/preprocessingNew/cutPsf.py", line 20, in dofwhm
    psfdata.shape[1]/2, psfdata.shape[0]/2, psfdata[psfdata.shape[1]/2, psfdata.shape[0]/2], 5.0])
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

如前所述,Python2...

一切都完美运行

您需要使用 * 运算符进行一些修改。

def gauss(x, y, x0, y0, intens, sigma):
    return intens*numpy.exp(-(numpy.power(x-x0, 2)+numpy.power(y-y0, 2))/(2.*sigma**2)).ravel()

def dofwhm(psfdata):
    x = numpy.arange(psfdata.shape[1])
    y = numpy.arange(psfdata.shape[0])
    x, y = numpy.meshgrid(x, y)
    popt, pcov = opt.curve_fit(gauss, *(x, y), psfdata.ravel(), p0=[psfdata.shape[1]/2, psfdata.shape[0]/2, psfdata[psfdata.shape[1]/2, psfdata.shape[0]/2], 5.0])

    return 2.355*abs(popt[3])

稍后解包

def gauss(xy, x0, y0, intens, sigma):
    x, y = xy
    return intens*numpy.exp(-(numpy.power(x-x0, 2)+numpy.power(y-y0, 2))/(2.*sigma**2)).ravel()

我建议这个基于典型的scipy优化要求,其中用户定义的函数用f(x, *args)调用,其中x是优化的变量(可能是数组) .但是curve_fit就不一样了。

scipy.optimize.curve_fit(f, xdata, ydata, p0=None,...)

其中f(你的gauss?)满足:

ydata = f(xdata, *params) + eps 

https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html

如果 xdata(x,y) 元组,或者由它构成的数组,我想我的建议仍然有效。 ydatapsfdata.ravel().