"int 'object is not subscriptable" - python

i'm starting to learn GEKKO. Now, I am solving a knapsak problem to learn, but this time I get the error "int 'object is not subscriptable". can you look at this code? what is the source of the problem How should I define the 1.10 matrices?
from gekko import GEKKO
import numpy as np
m = GEKKO(remote=False)
x = m.Var((10),lb=0,ub=1,integer=True)
#x = m.Array(m.Var,(1,10),lb=0,ub=1,integer=True)
v=np.array([2, 2, 7, 8, 2, 1, 7, 9, 4, 10])
w=np.array([2, 2, 2, 2, 2, 1, 6, 7, 3, 3])
capacity=16
for j in range(10):
m.Maximize(v[j]*x[j])
for i in range(10):
m.Equation(m.sum(x[i]*w[i])<=capacity)
m.options.solver = 1
m.solve()
#print('Objective Function: ' + str(m.options.objfcnval))
print(x)
My second question is that there is a function called "showproblem ()" in MATLAB. Does GEKKO have this function?
thanks for help.
new question that according to answer.
can i write here this style(that doesnt work, if i can do it, please write working style)(i want to write this style, because i think this style is easier to understand.),
for i in range(10):
xw = x[i]*w[i]
m.Equation(m.sum(xw)<=capacity)
instead of this.
xw = [x[i]*w[i] for i in range(10)]
m.Equation(m.sum(xw)<=capacity)

Here is a modified version that solves the mixed integer problem in gekko.
from gekko import GEKKO
import numpy as np
m = GEKKO(remote=False)
x = m.Array(m.Var,10,lb=0,ub=1,integer=True)
v=np.array([2, 2, 7, 8, 2, 1, 7, 9, 4, 10])
w=np.array([2, 2, 2, 2, 2, 1, 6, 7, 3, 3])
capacity=16
for j in range(10):
m.Maximize(v[j]*x[j])
xw = [x[i]*w[i] for i in range(10)]
m.Equation(m.sum(xw)<=capacity)
m.options.solver = 1
m.solve()
print('Objective Function: ' + str(-m.options.objfcnval))
print(x)
Your problem formulation was close. You just needed to define a list xw that you use to form the capacity constraint.
If you want to use a loop instead of a list comprehension then I recommend the following instead of xw = [x[i]*w[i] for i in range(10)].
xw = []
for i in range(10):
xw.append(x[i]*w[i])

Related

What's meaning of plt.plot(x[0:-1],y/y[0])?

I am plotting an exponential distribution using the information provided by the tutor.
plt.plot(x[:-1],y/y[0])
plt.plot(tvals,pvals)
plt.show()
But, I do not know what's meaning of x[:-1] and y/y[0]?
x[:-1] means all the elements except the last one
y/y[0] is simply dividing the array y by the first value i.e y[0] of the array.
Code Example
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1, 3, 5, 7])
y = np.array([2, 4, 6])
a = x[:-1] # [1, 3, 5]
b = y/y[0] # [1, 2, 3]
plt.plot(a, b)
Output

Pytorch median - is it bug or am I using it wrong

I am trying to get median of each row of 2D torch.tensor. But the result is not what I expect when compared to working with standard array or numpy
import torch
import numpy as np
from statistics import median
print(torch.__version__)
>>> 0.4.1
y = [[1, 2, 3, 5, 9, 1],[1, 2, 3, 5, 9, 1]]
median(y[0])
>>> 2.5
np.median(y,axis=1)
>>> array([2.5, 2.5])
yt = torch.tensor(y,dtype=torch.float32)
yt.median(1)[0]
>>> tensor([2., 2.])
Looks like this is the intended behaviour of Torch as mentioned in this issue
https://github.com/pytorch/pytorch/issues/1837
https://github.com/torch/torch7/pull/182
The reasoning as mentioned in the link above
Median returns 'middle' element in case of odd-many elements, otherwise one-before-middle element (could also do the other convention to take mean of the two around-the-middle elements, but that would be twice more expensive, so I decided for this one).
You can emulate numpy median with pytorch:
import torch
import numpy as np
y =[1, 2, 3, 5, 9, 1]
print("numpy=",np.median(y))
print(sorted([1, 2, 3, 5, 9, 1]))
yt = torch.tensor(y,dtype=torch.float32)
ymax = torch.tensor([yt.max()])
print("torch=",yt.median())
print("torch_fixed=",(torch.cat((yt,ymax)).median()+yt.median())/2.)

Reiterative mapping with the previous result

I'm trying to reiterate calculation using the previous result via using map function. I have a code work, but looks ugly. If you have insights, so that a code can be written elegantly, please, teach me. Any help will be very appreciable.
The reiterating process is described as you see in the figure below.
I have put my ugly code and also my trial with map function. I appreciate your help in advance.
The ugly one
import numpy as np
ys=np.array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
xs=ys
from scipy.interpolate import interp1d
g = interp1d(xs, ys, fill_value='extrapolate')
x0=ys[0]
s1=-4
def func(x1):
return -g(x1)/(x0-x1)-s1
from scipy.optimize import fsolve
initial_guess = 5
x1=fsolve(func, initial_guess)[0]
print(x1)
s2=-2
def func(x2):
return -g(x2)/(x1-x2)-s2
from scipy.optimize import fsolve
initial_guess = 5
x2=fsolve(func, initial_guess)[0]
print(x2)
s3=-0.67
def func(x3):
return -g(x3)/(x2-x3)-s3
from scipy.optimize import fsolve
initial_guess = 5
x3=fsolve(func, initial_guess)[0]
print(x3)
My trial with map function
import numpy as np
ys=np.array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
xs=ys
from scipy.interpolate import interp1d
g = interp1d(xs, ys, fill_value='extrapolate')
x0=ys[0]
s=[-4,-2,-0.67]
def func(x):
return -g(x)/(x0-x)-s
xall=list(map(func, s))
from scipy.optimize import fsolve
initial_guess = 5*np.ones(s.size)
xi=fsolve(xall, initial_guess)[0]
print(xi)
Maybe you want to use a lambda function as input to fsolve. Something like this:
import numpy as np
from scipy.optimize import fsolve
from scipy.interpolate import interp1d
ys = np.array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
xs = ys
g = interp1d(xs, ys, fill_value='extrapolate')
x0 = ys[0]
s = [-4, -2, -0.67]
initial_guess = 5
for si in s:
x0 = fsolve(lambda x1: -g(x1)/(x0 - x1) - si, initial_guess)[0]
print(x0)

How to re-write script of matrix 3D matlab in python

I newbie in python. I have matlab script like below. I want to re-write matrix 3D in matlab script in to python 3.x language. How can I fix it?
nl=length(res);
ndat=length(per);
phi=atan(1)*4;
amu=phi*4e-7;
for i=1:ndat
for j=1:nl
z=sqrt(phi*amu*res(j)/per(i));
zz(j)=complex(z,z);
exp0=exp((-2)*zz(j)/res(j)*thi(j));
exp1=complex(1,0)+exp0;
exp2=complex(1,0)-exp0;
%matrix 3D
ldi(1,1,j)=exp1;
ldi(1,2,j)=zz(j)*exp2
ldi(2,1,j)=exp2/zz(j);
ldi(2,2,j)=exp1;`
end
end
You'll find a self-contained implementation of your code (below), with a few key differences:
Python indexing starts from 0 instead of one
Python indexing uses square brackets instead of round ones
Mathematic functions must be imported from libraries (here math and cmath)
Good luck!
import math
import cmath
# Data
res = [1, 4, 1, 2, 3]
per = [5, 5, 1, 1, 0.5, 0.6]
thi = [1, 2, 3, 4, 5, 6]
nl = len(res)
ldi = [[[0 for x in range(nl)],[0 for x in range(nl)]], [[0 for x in range(nl)],[0 for x in range(nl)]]]
zz = [0]*nl
nl = len(res)
ndat = len(per)
phi = math.atan(1)*4
amu = phi*4e-7
for i in range(ndat):
for j in range(nl):
z = math.sqrt(phi*amu*res[j]/per[i])
zz[j] = complex(z,z)
exp0=cmath.exp((-2)*zz[j]/res[j]*thi[j]);
exp1=complex(1,0)+exp0;
exp2=complex(1,0)-exp0;
#- matrix 3D
ldi[0][0][j]=exp1;
ldi[0][1][j]=zz[j]*exp2
ldi[1][0][j]=exp2/zz[j]
ldi[1][1][j]=exp1

Convert tensor sum to real value

How can I convert the following
Sum{acc_dtype=float64}.0
to a real value to be able to print it?
I have tried T.cast, but it is not working.
I guess you are trying to print a tensor variable directly, this will never work, you always have to define computations via tensor/symbolic variables and then pass real data/values to them to actually evaluate those computations.
This should work:
import theano
import theano.tensor as T
import numpy as np
x = T.matrix('x')
sum_0 = T.sum(x, axis=0)
sum_1 = T.sum(x, axis=1)
f0 = theano.function(inputs=[x], outputs=sum_0)
f1 = theano.function(inputs=[x], outputs=sum_1)
x_d = np.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=theano.config.floatX)
print('x: ', x_d)
print('sum{axis=0}: ', f0(x_d))
print('sum{axis=1}: ', f1(x_d))
I would suggest going through the Theano basic tutorials and then Deep Learning tutorials.

Categories