How to fix ''int' object has no attribute 'triu_indices' - python

I'm using a double for loop, to calculate a value. This for loop gets the i element of a vector and the i+1 element of the same vector, then it does some calculation. But when the second iteration of the second for loop starts, I get the error 'int' object has no attribute 'triu_indices'
I have three matrixes, and some functions. Also I use a double for (I don't think this is the pythonic way to do that, however I'm learning)
I have this:
import numpy as np
#The three matrixes
flowMatrixSymNoCeros = np.array([[0,4,6,2,4,4],
[4,0,4,2,2,8],
[6,4,0,2,2,6],
[2,2,2,0,6,2],
[4,2,2,6,0,10],
[4,8,6,2,10,0]])
flowMatrixSymCeros = np.array([[0,0,6,2,4,0],
[0,0,4,2,2,8],
[6,4,0,2,2,6],
[2,2,2,0,6,2],
[4,2,2,6,0,0],
[0,8,6,2,0,0]])
closenessRatingSymNoceros = np.array([[0,5,3,2,6,4],
[5,0,5,2,6,2],
[3,5,0,1,2,1],
[2,2,1,0,2,2],
[6,6,2,2,0,6],
[4,2,1,2,6,0]])
matrices = np.array([flowMatrixSymNoCeros,
flowMatrixSymCeros,
closenessRatingSymNoceros])
def normalMatrixesAsym(matrices):
matrixes = np.copy(matrices)
matrixes = np.absolute(matrixes)
normalMatrixes = []
for matriz in matrixes:
s = np.sum(matriz)
normalMatrixes.append(matriz / s)
return np.asarray(normalMatrixes)
def sdwm(symetria, normalMatrix):
SD= 0
normalizedMatrix = np.copy(normalMatrix)
m = normalizedMatrix.shape[0]
sd = lambda num,den : (num/den)**(1/2)
# maskUpper = np.mask_indices(m, np.triu, 1)
# maskLower = np.mask_indices(m, np.tril, -1)
upper = normalizedMatrix[np.triu_indices(m,1)]
lower = normalizedMatrix[np.tril_indices(m,-1)]
upperAbs = np.abs(upper)
if(symetria):
media = np.absolute(np.mean(upper))
num = np.sum((upperAbs - np.mean(media))**2)
den = ((m * (m-1))/2)-1
SD = sd(num,den) #calculo del SD
else:
# lower = np.tril(normalizedMatrix,-1)
matrixNoDiag = np.append(upper,lower)
matrixNoDiagAbs = np.abs(matrixNoDiag)
mean = np.absolute(np.mean(matrixNoDiag))
num = np.sum((matrixNoDiagAbs - mean)**2)
den = (m*(m-1))-1 #calcula el denominador
SD = sd(num,den) #calcula el SD
return SD
def calcularCriticalValues(funcion, symetria, normalMatrixes):
normalMatrices = np.copy(normalMatrixes)
criticalValules = []
for normalMatriz in normalMatrices:
criticalValules.append(funcion(symetria,normalMatriz))
return np.asarray(criticalValules)
normalizedMatrices = normalMatrixesAsym(matrices)
SD = calcularCriticalValues(nm.sdwm,False,normalizedMatrices)
m=len(matrices)
R= np.zeros((m,m))
n = len(normalizedMatrices[0])
for i,matrix in enumerate(normalizedMatrices):
upperI = matrix[np.triu_indices(n,1)]
lowerI = matrix[np.tril_indices(n,-1)]
matrixNoDiagI = np.append(upperI,lowerI)
meanI = np.absolute(np.mean(matrixNoDiagI))
matrixNoDiagIAbs = np.abs(matrixNoDiagI)
for j in range(i+1,m):
matrixJ =normalizedMatrices[j]
upperJ = matrixJ[np.triu_indices(n,1)] #the problem is here
lowerJ = matrixJ[np.tril_indices(n,-1)]
matrixNoDiagJ = np.append(upperJ,lowerJ)
meanJ = np.absolute(np.mean(matrixNoDiagJ))
matrixNoDiagJAbs = np.abs(matrixNoDiagJ)
num = np.sum((matrixNoDiagIAbs - meanI)*(matrixNoDiagJAbs -
meanJ))
np = (n*(n-1))-1 #n''
den = np*SD[i]*SD[j]
r = num/den
R[i][j] = r
print(R)
What I expect is a matrix named R, with the calculations that the algorithm do.
This is
>>>R
>>>[[0. 0.456510 0.987845]
[0. 0.156457 0.987845]
[0. 0. 0. ]]
The error I get is:
AttributeError Traceback (most recent call last)
in ()
204 # print(i,j)
205 matrixJ =normalizedMatrices[j]
--> 206 upperJ = matrixJ[np.triu_indices(n,1)] # Obtiene elementos diagonal superior
207 lowerJ = matrixJ[np.tril_indices(n,-1)] # Obtiene elementos diagonal superior
208 matrixNoDiagJ = np.append(upperJ,lowerJ)
AttributeError: 'int' object has no attribute 'triu_indices'

The problem is that you use np as a variable in that loop: np = (n*(n-1))-1 #n''. You are assigning it to an int value, which is shadowing the imported np. You need to rename that variable.

Related

Problems using fsolve to find two unknowns in Python

I've been having problems trying to estimate two variables while using fsolve. Below is the code
def f(variables):
#Ideal
n=0 #this is passed as an argument but given in this example for simplicity
P1 = 101325; T1 = 300
q = 'H2:2,O2:1,N2:{}'.format(molno[n])
mech = 'H2O2sandan.cti'
cj_speed,R2,plot_data = CJspeed(P1,T1,q,mech,fullOutput=True)
gas = PostShock_fr(cj_speed, P1, T1, q, mech)
Ta = gas.T; Ps = gas.P;
CVout1 = cvsolve(gas)
taua = CVout1['ind_time']
Tb = Ta*1.01
gas.TPX = Tb,Ps,q
CVout2 = cvsolve(gas)
taub = CVout2['ind_time']
#Constant Volume
k,Ea = variables
T_0_1= Tvn_mg_d[n]
T_vn_1 = Tvn_mg_d[n]
den = rhovn_mg_d[n]
t = np.linspace(0,0.0001,100000000)
qr = Q_mg[n]
perfect_var = T_vn_1,den,Ea,k,qr
sol_t= odeint(ode,T_0_1,t=t,args=(perfect_var,))
index = np.argmax(np.gradient(sol_t[:,0]))
tau_cv_1 = t[index]
T_0_2= Tvn_mg_d[n]*1.01
T_vn_2 = Tvn_mg_d[n]*1.01
den = rhovn_mg_d[n]
t = np.linspace(0,0.0001,100000000)
qr = Q_mg[n]
perfect_var = T_vn_2,den,Ea,k,qr
sol_t= odeint(ode,T_0_2,t=t,args=(perfect_var,))
index = np.argmax(np.gradient(sol_t[:,0]))
tau_cv_2 = t[index]
root1 = taua - t_cv_1
root2 = taub - t_cv_2
return[root1,root2]
import scipy.optimize as opt
k_guess = 95000
Ea_guess = 28*300
solution = opt.fsolve(f,(k_guess,Ea_guess))
print(solution)
I want to find values of k_guess and Ea_guess such that roo1 and roo2 are 0 (i.e. taua = t_cv_1 and taub = t_cv_2). However I don't know if I've used fsolve the right way as the values returned seem to be way off. Am I returning the right thing? I also get the below error:
lsoda-- warning..internal t (=r1) and h (=r2) are
such that in the machine, t + h = t on the next step
(h = step size). solver will continue anyway
What am I doing wrong here?

Is there a way to fix value-error problem

Hello guys i am trying to implement an algortihm to remove water from underwater images and make image more noticable , but i got an errror ValueError: max() arg is an empty sequence , at the function homomorpic on this line r = max(np.ravel(result[:,:i])) , the error is caused because the result array is empty but i filled it above .Here the code below.
import numpy as np
import cv2
def homomorpic(img):
img = np.float32(img)
#img = img/255
rows , cols , dim = img.shape
(rh,rl,cutoff) = 1.3, 0.8, 32
b,g,r = cv2.split(img)
y_log_b = np.log(b + 0.01)
y_log_g = np.log(g + 0.01)
y_log_r = np.log(r + 0.01)
y_fft_b= np.fft.fft2(y_log_b)
y_fft_g= np.fft.fft2(y_log_g)
y_fft_r= np.fft.fft2(y_log_r)
y_fft_b_shift = np.fft.fftshift(y_log_b)
y_fft_g_shift = np.fft.fftshift(y_log_g)
y_fft_r_shift = np.fft.fftshift(y_log_r)
D0=cols/cutoff
H= np.ones((rows,cols))
B= np.ones((rows,cols))
for i in range(rows):
for j in range(cols):
H[i][j] = ((rh-rl)* (1-np.exp(-((i-rows/2)**2+(j-cols/2)**2)/(2*D0**2))))+rl
result_filter_b = H* y_fft_b_shift
result_filter_g = H* y_fft_g_shift
result_filter_r = H* y_fft_r_shift
result_b_intern = np.real(np.fft.ifft2(np.fft.ifftshift(result_filter_b)))
result_g_intern = np.real(np.fft.ifft2(np.fft.ifftshift(result_filter_g)))
result_r_intern = np.real(np.fft.ifft2(np.fft.ifftshift(result_filter_r)))
result_b = np.exp(result_b_intern)
result_g = np.exp(result_g_intern)
result_r = np.exp(result_r_intern)
result = np.zeros((rows,cols,dim))
result[:,:,0] = result_b
result[:,:,1] = result_g
result[:,:,2] = result_r
ma = -1
mi = 500
for i in range(3):
r = max(np.ravel(result[:,:i]))
x = min(np.ravel(result[:,:i]))
if r > ma :
ma = r
if x < mi :
mi = x
return(result)
image = cv2.imread("eg.png")
image2 = homomorpic(image)
Thanks for any help or suggestion.
In this loop for i in range(3): the first value of i would be 0.
This will later on lead to this r = max(np.ravel(result[:,:0])) where the result from the slicing would be empty.
You would want to shift yourrange forward like this:
for i in range(1, 3+1):

How to square the individual matrix value using python?

Cost function implemented with Python:
**Thanks for help to achieve this.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
load_data = pd.read_csv('C:\python_program\ex1data1.txt',sep = ",",header = None)
feature_vale = load_data[0]
y = np.matrix(load_data[1])
m = len(feature_vale)
plt.scatter(load_data[0],load_data[1],marker='+',c = 'r')
plt.title("Cost_Function")
plt.xlabel("Population of City in 10,000s")
plt.ylabel("Profit in $10,000s")
df = pd.DataFrame(pd.Series(1,index= range(0,m)))
df[1] = load_data[0]
X = np.matrix(df)
row_theta = np.zeros(2,dtype = int)
theta = np.array([row_theta]) # Transpose the array
prediction = np.dot(X,theta.T)
error = (prediction-y.T)
error_df = pd.DataFrame(error)
#square the error
squared_error = np.square(error_df)
sum = np.sum(squared_error)
print(sum)
J = np.sum(squared_error) / (2 * m)
print(J)
Data reference link: searchcode.com/codesearch/view/5404318
repeat the following steps and let me know
load_data = pd.read_csv('data.txt',sep = ",",header = None)
feature_vale = load_data[0]
y = np.matrix(load_data[1])
m = len(feature_vale)
#print(m)
#plt.scatter(load_data[0],load_data[1])
df = pd.DataFrame(pd.Series(1,index= range(0,m)))
df[1] = load_data[0]
X = np.matrix(df)
row_theta = np.zeros(2,dtype = int)
theta = np.array([row_theta]) # Transpose the array
print(theta.T)
prediction = np.matmul(X,theta.T)
error = (prediction-y)
error_df = pd.DataFrame(error)
squared_error = np.square(error_df)
print(squared_error)

TypeError: 'int' object is not callable Modeling in python

I am getting the following error in python, and I am not sure why. I am trying to model how meth affects mice.
Here is my code, and the functions that are created in my code:
from scipy import array, linspace
from scipy import integrate
from matplotlib.pyplot import *
def Temp2(z, t, Ta, Te, wexc, yexc, winhib, yinhib, whd, yhd, wexctoinhib, winhibtomdl, whdtospn, yspn, Tt):
# Dependence of Meth Concentration
# dx
# -- = -x/Ta
# dt
#
# dy
# -- = x/Ta - y/Te
# dt
# x = interperitoneal
# y = blood
# Ta is the time constant of Meth in the absorbtion
# Te is the time constant of Meth in elimination
x = z[0] # Rabbits density
y = z[1] # Sheep density
T = z[2]
D = int(x=1)
yt = D(Ta/Te -1)**-1 * (e**-t/Ta - e**-t/Te)
Pexc = (1+tanhx)*[wexc*yt*yexc]
Pinhib = (1+tanhx)*[winhib*yt*yinhib]
Phd = (1+tanhx)*[whd*yt*yhd]
Pmdl = wexctoinghib*Pexc-winhibtomdl*Pinhib
Pspn = Pmdl + whdtospn*Phd+yspn
V = array([-x/Ta, x/Ta - y/Te, (Pspn-(T-T0))/Tt])
return V
def main():
# set up our initial conditions
IC0 = 1
BC0 = 0
T0 = 37
z0 = array([IC0, BC0, T0])
# Parameters
Ta = 8.25
Te = 57.5
wexc = 1.225
yexc = -0.357
winhib = 1.335
yinhib = 1.463
whd = 0.872
yhd = -3.69
wexctoinhib = 7.47
winhibtomdl = 6.38
whdtospn = 5.66
yspn = -3.35
Tt = 89.2
# choose the time's we'd like to know the approximate solution
t = linspace(0., 1., 60)
# and solve
xode= integrate.odeint(Temp2, z0, t, args=(Ta, Te, wexc, yexc, winhib, yinhib, whd, yhd, wexctoinhib, winhibtomdl, whdtospn, yspn, Tt))
print (xode)
main()
Ignore the #s as they do not relate to what the code is saying. Here is the error I am getting:
yt = D(Ta/Te -1)**-1 * (e**-t/Ta - e**-t/Te)
TypeError: 'int' object is not callable
I am not sure what is wrong, and how I can fix this? Can anyone help me?
The issue is here
yt = D(Ta/Te -1)**-1 * (e**-t/Ta - e**-t/Te)
There is no implicit multiplication in python, so when you attempt to do D(Ta/Te - 1) it is being interpreted as a function call rather than D multiplied by what is in the bracket.
Rewrite it like this
yt = D*(Ta/Te -1)**-1 * (e**-t/Ta - e**-t/Te)

TypeError: 'float' object has no attribute '__getitem__' in while statement

I am getting TypeError: 'float' object has no attribute 'getitem' for my while statement below. I am not sure what the problem is in this case. I am using sys in the code
s1P = 4.51775*10.0**16.0
ii= 1
while s1P[ii-1] > 0.0
sys.stdout.write('\rstep={0}'.format(ii))
sys.stdout.flush()
Rad = s1r[ii-1]+delrms1[ii-1]*delm
Mas = s1m[ii-1]*[i]
Pres = s1P[ii-1]+delPms1[ii-1]*delm
lPres = np.log10(Pres)
Temp = s1T[ii-1]+delTms1[ii-1]*delm
lTemp = np.log10(Temp)
Lum = s1L[ii-1]+deLms1[ii-1]*delm
Rho = (Pres - 1.0/3.0*a*Temp**4.0)*mu/(NA*k*Temp)
lRho = np.log10(Rho)
lR = np.log10(10.0**lRho/(10.0**Temp/10.0**6)**3.0)
lK = interpolate.bisplev(lTemp,lR,tck)
K = 10.0**lK
T_n = Temp/(10.0**9.0)
epp = 2.4*10.0**4.0*(Rho*X**2.0/T_n**(2.0/3.0))*np.exp(-3.38/T_n**(1.0/3.0))
ecno = 4.4*10.0**25.0*(Rho*X*Z/T_n**(2.0/3.0))*np.exp(-15.228/T_n**(1.0/3.0))
eta = 5.0*10.0**8.0*(Rho**2.0*Y**3.0/T_n**3.0)*np.exp(-4.4/T_n)
ec = epp+ecno+eta
Bt = NA*k*Rhoc*T_n/(Pres*mu)
Gam2 =(32.0-24.0*Bt-3.0*Bt**2.0)/(24.0-18.0*Bt-3.0*Bt**2.0)
drm = 1.0/(4.0*np.pi*Rad**2.0*Rho)
dPm = -G*Mas*1.99*10.0**33.0/(4.0*np.pi*Rad**4.0)
dLm = eg
Term1 = 16.0*np.pi*a*c*G/(3.0*K)
Term2 = (1.0-1.0/Gam2)
Term3 = Temp**4.0*(Mas*1.99*10.0**33.0)/Pres
Tal = Term1+Term2+Term3
CR = Lum/Tal
dTrm = -3.0*s1K*s1L/(64.0*np.pi**2.0*a*c*s1r**4.0*s1T**3.0)
dTcm = -(1.0-1.0/s1gam2)*(G*s1m*1.99*10.0**33.0*s1T/(4.0*np.pi*s1r**4.0*s1P))
dTm = np.where(Lum > Tal, dTcm, dTrm)
sys.stdout.write('\n')
s1m.append(Mas)
s1r.append(Rad)
s1L.append(Lum)
r_c.append(CR)
s1T.append(Temp)
logs1T.append(lTemp)
s1P.append(Pres)
logs1P.append(lPres)
s1rho.append(Rho)
logs1rho.append(lRho)
logs1K.append(lK)
slK.append(K)
s1eg.append(ec)
s1gam2.append(Gam2)
delrms1.append(drm)
delPms1.append(dPm)
delLms1.append(dLm)
delTm1.append(dTm)
ii = ii+1
sys.stdout.write('\n')
s1m=s1m[:-1]
s1r=s1r[:-1]
s1L=s1L[:-1]
r_c=r_c[:-1]
s1T=s1T[:-1]
logs1T=logs1T[:-1]
s1P=s1P[:-1]
logs1P=logs1P[:-1]
s1rho=s1rho[:-1]
logs1rho=logs1K[:-1]
logs1K=logs1K[:-1]
slK=s1K[:-1]
s1eg=s1eg[:-1]
s1gam2=s1gam2[:-1]
delrms1=delrms1[:-1]
delPms1=delPms1[:-1]
delLms1=delLms1[:-1]
delTm1=delTm1[:-1]
Could still be a problem from appending the outputs of my statement?
If s1P is supposed to be a list of numbers then you need to initialize it like
s1P = [4.51775*10.0**16.0]
instead of s1P = 4.51775*10.0**16.0, which will make it a single number.

Categories