Closed ZiadJanpih closed 2 years ago
Hi, x represents the value of each variable?
Hi Shayan, x is a vector of variables
One way is to create binary variables with conditional statements such as m.if3()
statements:
from gekko import GEKKO
m = GEKKO()
# create x / xi arrays
x=[8,8,8,6,6,9,9,9]; n=len(x)
xi = [m.Param(i,lb=6,ub=9,integer=True) for i in x]
# count functions
bins = [6,7,8,9]; nb = len(bins)
bC = m.Array(m.Var,(nb,n))
for j,b in enumerate(bins):
bL = [m.if3(xi[i]-(b-0.1),0,1) for i in range(n)]
bU = [m.if3(xi[i]-(b+0.1),1,0) for i in range(n)]
m.Equations([bC[j,i]==bU[i]*bL[i] for i in range(n)])
k = m.Array(m.Var,nb)
m.Equations([k[j]==m.sum(bC[j,:]) for j in range(nb)])
m.solve()
print('bC=',bC)
print('k=',k)
The result counts the number of elements in the bins [6,7,8,9]
as k= [[2.0] [0.0] [3.0] [3.0]]
for array [8,8,8,6,6,9,9,9]
. You can add additional constraints to the variables k[i]
and make xi
a variable with xi = [m.Var(i,lb=6,ub=9,integer=True) for i in x]
--------- APM Model Size ------------
Each time step contains
Objects : 0
Constants : 0
Variables : 300
Intermediates: 0
Connections : 0
Equations : 228
Residuals : 228
Number of state variables: 292
Number of total equations: - 228
Number of slack variables: - 128
---------------------------------------
Degrees of freedom : -64
* Warning: DOF <= 0
----------------------------------------------
Steady State Optimization with APOPT Solver
----------------------------------------------
Iter: 1 I: 0 Tm: 0.03 NLPi: 3 Dpth: 0 Lvs: 0 Obj: 0.00E+00 Gap: 0.00E+00
Successful solution
---------------------------------------------------
Solver : APOPT (v1.0)
Solution time : 6.839999998919666E-002 sec
Objective : 0.000000000000000E+000
Successful solution
---------------------------------------------------
bC= [[[0.0] [0.0] [0.0] [1.0] [1.0] [0.0] [0.0] [0.0]]
[[0.0] [0.0] [0.0] [0.0] [0.0] [0.0] [0.0] [0.0]]
[[1.0] [1.0] [1.0] [0.0] [0.0] [0.0] [0.0] [0.0]]
[[0.0] [0.0] [0.0] [0.0] [0.0] [1.0] [1.0] [1.0]]]
k= [[2.0] [0.0] [3.0] [3.0]]
Could you post this question on StackOverflow with tag Gekko? This GitHub is typically for reporting and tracking bugs and development of feature requests.
thank you for helping, I have posted it on StackOverflow-post
Thanks!
x= [8,8,8,6,6,9,9,9] i want to make sure that x[i] is appeared at least k times in x for example : k =2 x is ok, but k=3 is not x[i] is always an integer