2016-11-23 10 views
0

SO, когда я запускаю код ниже:Неподдерживаемой ошибки типа операнда в питоне кода

from pylab import plt 
import numpy as np 
from pandas import DataFrame 
from scipy.spatial.distance import pdist, squareform 

z = open('WGTutorial/ZoneA.dat','r').readlines() 
z = [ i.strip().split() for i in z[10:] ] 
z = np.array(z, dtype=np.float) 
z = DataFrame(z, columns=['x','y','thk','por','perm','lperm','lpermp','lpermr']) 

fig, ax = plt.subplots() 
ax.scatter(z.x, z.y, c=z.por, cmap='gray') 
ax.set_aspect(1) 
plt.xlim(-1500,22000) 
plt.ylim(-1500,17500) 
plt.xlabel('Easting [m]') 
plt.ylabel('Northing [m]') 
plt.title('Porosity %') ; 

def SVh(P, h, bw): 
    ''' 
    Experimental semivariogram for a single lag 
    ''' 
    pd = squareform(pdist(P[:,:2])) 
    N = pd.shape[0] 
    Z = list() 
    for i in range(N): 
     for j in range(i+1,N): 
      if(pd[i,j] >= h-bw)and(pd[i,j] <= h+bw): 
       Z.append((P[i,2] - P[j,2])**2.0) 
    return np.sum(Z)/(2.0 * len(Z)) 

def SV(P, hs, bw): 
    ''' 
    Experimental variogram for a collection of lags 
    ''' 
    sv = list() 
    for h in hs: 
     sv.append(SVh(P, h, bw)) 
    sv = [ [ hs[i], sv[i] ] for i in range(len(hs)) if sv[i] > 0 ] 
    return np.array(sv).T 

def C(P, h, bw): 
    ''' 
    Calculate the sill 
    ''' 
    c0 = np.var(P[:,2]) 
    if h == 0: 
     return c0 
    return c0 - SVh(P, h, bw) 

# part of our data set recording porosity 
P = np.array(z[['x','y','por']]) 
# bandwidth, plus or minus 250 meters 
bw = 500 
# lags in 500 meter increments from zero to 10,000 
hs = np.arange(0,10500,bw) 
sv = SV(P, hs, bw) 
plt.plot(sv[0], sv[1], '.-') 
plt.xlabel('Lag [m]') 
plt.ylabel('Semivariance') 
plt.title('Sample Semivariogram') ; 
#plt.savefig('sample_semivariogram.png',fmt='png',dpi=200) 

def opt(fct, x, y, C0, parameterRange=None, meshSize=1000): 
    if parameterRange == None: 
     parameterRange = [ x[1], x[-1] ] 
    mse = np.zeros(meshSize) 
    a = np.linspace(parameterRange[0], parameterRange[1], meshSize) 
    type(y) 
    type(x) 
    type(a) 
    type(C0) 
    for i in range(meshSize): 
     mse[i] = np.mean((y - fct(x, a[i], C0))**2.0) 
    return a[ mse.argmin() ] 

def spherical(h, a, C0): 
    ''' 
    Spherical model of the semivariogram 
    ''' 
    # if h is a single digit 
    if type(h) == np.float64: 
     # calculate the spherical function 
     if h <= a: 
      return C0*(1.5*h/a - 0.5*(h/a)**3.0) 
     else: 
      return C0 
    # if h is an iterable 
    else: 
     # calcualte the spherical function for all elements 
     a = np.ones(h.size) * a 
     C0 = np.ones(h.size) * C0 
     return map(spherical, h, a, C0) 

def cvmodel(P, model, hs, bw): 
    ''' 
    Input: (P)  ndarray, data 
      (model) modeling function 
         - spherical 
         - exponential 
         - gaussian 
      (hs)  distances 
      (bw)  bandwidth 
    Output: (covfct) function modeling the covariance 
    ''' 
    # calculate the semivariogram 
    sv = SV(P, hs, bw) 
    # calculate the sill 
    C0 = C(P, hs[0], bw) 
    # calculate the optimal parameters 
    param = opt(model, sv[0], sv[1], C0) 
    # return a covariance function 
    covfct = lambda h, a=param: C0 - model(h, a, C0) 
    return covfct 

sp = cvmodel(P, model=spherical, hs=np.arange(0,10500,500), bw=500) 
plt.plot(sv[0], sv[1], '.-') 
plt.plot(sv[0], sp(sv[0])) ; 
plt.title('Spherical Model') 
plt.ylabel('Semivariance') 
plt.xlabel('Lag [m]') 
#plt.savefig('semivariogram_model.png',fmt='png',dpi=200) 

Ошибки я получаю это;

File "C:/Users/PANATEC/Documents/Python Scripts/GlacMIK/Kriging.py", line 118, in cvmodel 
    param = opt(model, sv[0], sv[1], C0) 

    File "C:/Users/PANATEC/Documents/Python Scripts/GlacMIK/Kriging.py", line 81, in opt 
    mse[i] = np.mean((y - fct(x, a[i], C0))**2.0) 

TypeError: unsupported operand type(s) for -: 'float' and 'map' 

Я перешел на python несколько дней назад, и у меня возникли трудности с его исправлением.

Может ли кто-нибудь любезно помочь мне.

ответ

0

Fixed. Я использовал список (карта (сферическая, h, a, c0)). Функции карты python3 возвращают итератор, а не список напрямую.

+0

Интересно, что это работает, я думал, что вам нужен массив с множеством чисел, чтобы он работал. – Leo

0

Проблема описана в сообщении об ошибке: на этой строке кода, у является поплавка; fct выражение оценивает тип данных map. Вы не можете вычесть карту из поплавка.

Как я могу отследить свой код, ГЦТ является предварительно определенной функцией сферической. Каков тип возврата?

0

Заменить

return map(spherical, h, a, C0) 

С:

return spherical(h, a, C0)