TypeError:ufunc'add'不包含循环

时间:2015-12-14 10:07:36

标签: loops typeerror signature

我使用Anaconda和gdsCAD,并在正确安装所有软件包时出错。 如下所述:http://pythonhosted.org/gdsCAD/

TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S32') dtype('S32') dtype('S32')

我的导入看起来像这样(最后我导入了所有内容):

import numpy as np
from gdsCAD import *
import matplotlib.pyplot as plt

我的示例代码如下所示:

something = core.Elements()
box=shapes.Box( (5,5),(1,5),0.5)
core.default_layer = 1
core.default_colors = 2
something.add(box)
something.show()

我的错误消息如下所示:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-2f90b960c1c1> in <module>()
 31 puffer_wafer = shapes.Circle((0.,0.), puffer_wafer_radius, puffer_line_thickness)
 32 bp.add(puffer_wafer)
---> 33 bp.show()
 34 wafer = shapes.Circle((0.,0.), wafer_radius, wafer_line_thickness)
 35 bp.add(wafer)

C:\Users\rpilz\AppData\Local\Continuum\Anaconda2\lib\site-packages\gdscad-0.4.5-py2.7.egg\gdsCAD\core.pyc in _show(self)
 80     ax.margins(0.1)
 81 
---> 82     artists=self.artist()
 83     for a in artists:
 84         a.set_transform(a.get_transform() + ax.transData)

C:\Users\rpilz\AppData\Local\Continuum\Anaconda2\lib\site-packages\gdscad-0.4.5-py2.7.egg\gdsCAD\core.pyc in artist(self, color)
952         art=[]
953         for p in self:
--> 954             art+=p.artist()
955         return art
956 

C:\Users\rpilz\AppData\Local\Continuum\Anaconda2\lib\site-packages\gdscad-0.4.5-py2.7.egg\gdsCAD\core.pyc in artist(self, color)
475         poly = lines.buffer(self.width/2.)
476 
--> 477         return [descartes.PolygonPatch(poly, lw=0, **self._layer_properties(self.layer))]
478 
479 

C:\Users\rpilz\AppData\Local\Continuum\Anaconda2\lib\site-packages\gdscad-0.4.5-py2.7.egg\gdsCAD\core.pyc in _layer_properties(layer)
103         # Default colors from previous versions
104         colors = ['k', 'r', 'g', 'b', 'c', 'm', 'y']
--> 105         colors += matplotlib.cm.gist_ncar(np.linspace(0.98, 0, 15))
106         color = colors[layer % len(colors)]
107         return {'color': color}

TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S32') dtype('S32') dtype('S32')    

3 个答案:

答案 0 :(得分:5)

gdsCAD一直是一个痛苦的问题,从形状安装到这个密谋问题。
此问题是由于错误的数据类型传递给colors函数。可以通过编辑core.py

中的以下行来解决
colors += matplotlib.cm.gist_ncar(np.linspace(0.98, 0, 15))

colors += list(matplotlib.cm.gist_ncar(np.linspace(0.98, 0, 15)))

如果您不知道core.py位于何处。只需键入:

from gdsCAD import *
core

这将为您提供core.py文件的路径。祝你好运!

答案 1 :(得分:1)

首先,我要求您提供实际代码,因为基于回溯,文件中的“示例代码”明显不同。调试时,细节很重要,我需要能够实际运行代码。

您显然存在数据类型问题。这里的变量很可能很好:

puffer_wafer = shapes.Circle((0.,0.), puffer_wafer_radius, puffer_line_thickness)

当我对Pandas进行调用时,我遇到了同样的错误。我将数据更改为str(数据)并且代码工作正常。

答案 2 :(得分:1)

我不知道这是否有助于我自己相当新,但我有一个类似的错误,并发现它是由于之前的答案所建议的类型转换问题。我无法从问题的例子中看到你正在尝试做什么。以下是我的问题和解决方案的一个小例子。我的代码是使用scikit learn制作一个简单的随机森林模型。

这是一个给出错误的示例,它是由第三行到最后一行引起的,将结果连接到写入文件。

import scipy
import math
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn import preprocessing, metrics, cross_validation

Data = pd.read_csv("Free_Energy_exp.csv", sep=",")
Data = Data.fillna(Data.mean()) # replace the NA values with the mean of the descriptor
header = Data.columns.values # Ues the column headers as the descriptor labels
Data.head()
test_name = "Test.csv"

npArray = np.array(Data)
print header.shape
npheader = np.array(header[1:-1])
print("Array shape X = %d, Y = %d " % (npArray.shape))
datax, datay =  npArray.shape

names = npArray[:,0]
X = npArray[:,1:-1].astype(float)
y = npArray[:,-1] .astype(float)
X = preprocessing.scale(X)

XTrain, XTest, yTrain, yTest = cross_validation.train_test_split(X,y, random_state=0)

# Predictions results initialised 
RFpredictions = []
RF = RandomForestRegressor(n_estimators = 10, max_features = 5, max_depth = 5, random_state=0)
RF.fit(XTrain, yTrain)       # Train the model
print("Training R2 = %5.2f" % RF.score(XTrain,yTrain))
RFpreds = RF.predict(XTest)

with open(test_name,'a') as fpred :
    lenpredictions = len(RFpreds)
    lentrue = yTest.shape[0]
    if lenpredictions == lentrue :
            fpred.write("Names/Label,, Prediction Random Forest,, True Value,\n")
            for i in range(0,lenpredictions) :
                    fpred.write(RFpreds[i]+",,"+yTest[i]+",\n")
    else :
            print "ERROR - names, prediction and true value array size mismatch."

这会导致错误;

Traceback (most recent call last):
  File "min_example.py", line 40, in <module>
    fpred.write(RFpreds[i]+",,"+yTest[i]+",\n")
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S32') dtype('S32') dtype('S32')

解决方案是在第三行到最后一行使每个变量成为str()类型,然后写入文件。上面没有对代码进行任何其他更改。

import scipy
import math
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn import preprocessing, metrics, cross_validation

Data = pd.read_csv("Free_Energy_exp.csv", sep=",")
Data = Data.fillna(Data.mean()) # replace the NA values with the mean of the descriptor
header = Data.columns.values # Ues the column headers as the descriptor labels
Data.head()
test_name = "Test.csv"

npArray = np.array(Data)
print header.shape
npheader = np.array(header[1:-1])
print("Array shape X = %d, Y = %d " % (npArray.shape))
datax, datay =  npArray.shape

names = npArray[:,0]
X = npArray[:,1:-1].astype(float)
y = npArray[:,-1] .astype(float)
X = preprocessing.scale(X)

XTrain, XTest, yTrain, yTest = cross_validation.train_test_split(X,y, random_state=0)

# Predictions results initialised 
RFpredictions = []
RF = RandomForestRegressor(n_estimators = 10, max_features = 5, max_depth = 5, random_state=0)
RF.fit(XTrain, yTrain)       # Train the model
print("Training R2 = %5.2f" % RF.score(XTrain,yTrain))
RFpreds = RF.predict(XTest)

with open(test_name,'a') as fpred :
    lenpredictions = len(RFpreds)
    lentrue = yTest.shape[0]
    if lenpredictions == lentrue :
            fpred.write("Names/Label,, Prediction Random Forest,, True Value,\n")
            for i in range(0,lenpredictions) :
                    fpred.write(str(RFpreds[i])+",,"+str(yTest[i])+",\n")
    else :
            print "ERROR - names, prediction and true value array size mismatch."

这些示例来自更大的代码,所以我希望这些示例足够清晰。