예제 #1
0
def output_datarate_optimization_GEKKO(q,
                                       w,
                                       N,
                                       M,
                                       P,
                                       T_s,
                                       U_max=1000,
                                       Q_max=1,
                                       tol=1e-7):
    '''
    inputs: q(k) and w(k) and P(k) 
    set of base stations visible by sensors
    '''
    if N == 0:
        return []

    #initialize the model
    m = GEKKO(remote=False)

    q_k = m.Array(m.Param, N)
    for i in range(N):
        q_k[i].value = q[i]

    w_k = m.Array(m.Param, N)
    for i in range(N):
        w_k[i].value = w[i]

    u_k = m.Array(m.Var, (N, M), value=0, lb=0)
    P_k = m.Array(m.Param, (N, M))
    for i in range(N):
        for j in range(M):
            P_k[i, j].value = P[i, j]
    for i in range(N):
        for j in range(M):
            m.Equation((1 - P_k[i, j]) * u_k[i, j] <= 0.0)

    for j in range(M):
        m.Equation(sum(u_k[:, j]) <= U_max)

    for i in range(N):
        m.Equation(q_k[i] + T_s * (w_k[i] - sum(u_k[i, :])) >= 0)
        m.Equation(q_k[i] + T_s * (w_k[i] - sum(u_k[i, :])) <= Q_max)

    #Load balancing

    m.Obj(
        sum([(sum(u_k[:, i]) - sum(u_k[:, j])) for i in range(M - 1)
             for j in range(i + 1, M)]) +
        100 * sum([(q_k[i] + T_s * (w_k[i] - sum(u_k[i, :])))
                   for i in range(N)]))
    m.solve(disp=False)
    u_final = np.zeros((N, M))
    for i in range(N):
        for j in range(M):
            u_final[i, j] = u_k[i, j].value[0]
            if u_final[i, j] < tol:
                u_final[i, j] = 0
    return u_final
def init_solver(G, w, num_tasks, task_prev, task_ordering):
    m = GEKKO()

    # Use IPOPT solver (default)
    m.options.SOLVER = 3

    # Change to parallel linear solver
    m.solver_options = ['linear_solver ma97']

    # variable array dimension

    # create array
    s = m.Array(m.Var, num_tasks)
    for i in range(num_tasks):
        s[i].value = 2.0
        s[i].lower = 0

    M = m.Var(value=5, lb=0)
    P = m.Var(value=5, lb=0)

    # define completion time of each task
    c = m.Array(m.Var, num_tasks)
    for i in range(num_tasks):
        c[i].value = 0
        c[i].lower = 0

    #1b
    # task's completion time must be later than the time to run task itself
    for i in range(num_tasks):
        m.Equation(w[i] / s[i] <= c[i])

    #1c
    # task must start later than all ancestors
    for i in range(num_tasks):
        for j in nx.algorithms.ancestors(G, i):
            m.Equation(c[j] + (w[i] / s[i]) <= c[i])

    # task must start later than previous task on machine
    for task, prev in task_prev.items():
        if prev != None:
            m.Equation(c[prev] + (w[task] / s[task]) <= c[task])

    #1d
    # Total load assigned to each machine should not be greater than the makespan
    for lst in task_ordering:
        m.Equation(sum([w[i] / s[i] for i in lst]) <= M)

    #1e (define M in objective function)
    for i in range(num_tasks):
        m.Equation(c[i] <= M)

    # define P in objective function
    m.Equation(sum([s[i] for i in range(num_tasks)]) == P)

    return m, s, c, P, M
예제 #3
0
def init_solver(v, O_value=5):
    m = GEKKO()

    # Use IPOPT solver (default)
    m.options.SOLVER = 3

    # Change to parallel linear solver
    m.solver_options = ['linear_solver ma97']

    # variable array dimension
    n = len(v)  # rows

    # create array
    s = m.Array(m.Var, n)
    for i in range(n):
        s[i].value = 2.0
        s[i].lower = 0

    # Optimal value for ibjective
    O = m.Var(value=O_value, lb=0)

    # The objective basically
    m.Equation(sum([int(v[i]) / s[i] + s[i] for i in range(len(v))]) == O)

    return m, s, O
예제 #4
0
def init_solver_machine_scaling(v, machine_task_list, task_machine_dict, O_value=5):
    """

    :param v: number of tasks dependent on each task
    :param machine_task_list: order
    :param task_machine_dict: task machine mapping
    :param O_value: optimal objective value
    :return:
    """
    m = GEKKO()

    # Use IPOPT solver (default)
    m.options.SOLVER = 3

    # Change to parallel linear solver
    m.solver_options = ['linear_solver ma97']

    # variable array dimension
    n = len(machine_task_list)  # rows

    # create array
    s = m.Array(m.Var, n)
    for i in range(n):
        s[i].value = 2.0
        s[i].lower = 0

    # Optimal value for ibjective
    O = m.Var(value=O_value, lb=0)

    # The objective basically
    m.Equation(sum([int(v[i]) / s[task_machine_dict[i]] + s[task_machine_dict[i]] for i in range(len(v))]) == O)
    return m, s, O
예제 #5
0
 def _genMeanVarianceModel(self, nvar, prepared_objective,
                           prepared_constraints, prepared_option):
     Model = GEKKO(remote=prepared_option.get("remote", False))
     x = Model.Array(Model.Var, (nvar, ))
     Obj = 0
     if "f" in prepared_objective:
         Obj += np.dot(prepared_objective["f"].flatten(), x)
     if "X" in prepared_objective:
         Sigma = np.dot(
             np.dot(prepared_objective["X"], prepared_objective["F"]),
             prepared_objective["X"].T) + np.diag(
                 prepared_objective["Delta"].flatten())
         Sigma = (Sigma + Sigma.T) / 2
         Obj += np.dot(np.dot(x, Sigma), x)
     elif "Sigma" in prepared_objective:
         Obj += np.dot(np.dot(x, prepared_objective["Sigma"]), x)
     if "Mu" in prepared_objective:
         Obj += np.dot(prepared_objective["Mu"].flatten(), x)
     if "lambda1" in prepared_objective:
         Obj += prepared_objective["lambda1"] * sum(
             abs(x - prepared_objective["c"].flatten()))
     if "lambda2" in prepared_objective:
         c_pos = prepared_objective["c_pos"].flatten()
         Obj += prepared_objective["lambda2"] / 2 * sum(
             abs(x - c_pos) + (x - c_pos))
     if "lambda3" in prepared_objective:
         c_neg = prepared_objective["c_neg"].flatten()
         Obj += prepared_objective["lambda3"] / 2 * sum(
             abs(x - c_neg) + (x - c_neg))
     Model.Obj(Obj)
     self._Model, self._x = self._genModelConstraints(
         Model, x, nvar, prepared_constraints, prepared_option)
     return 0
예제 #6
0
def init_solver_original(v, machine_task_list):
    m = GEKKO()

    # Use IPOPT solver (default)
    m.options.SOLVER = 3

    # Change to parallel linear solver
    m.solver_options = ['linear_solver ma97']

    # variable array dimension
    n = len(v)  # rows

    # create array
    s = m.Array(m.Var, n)
    for i in range(n):
        s[i].value = 2.0
        s[i].lower = 0

    P = m.Var(value=5, lb=0)
    m.Equation(sum([s[i] for i in range(len(v))]) == P)

    M1 = m.Var(value=5, lb=0)
    M2 = m.Var(value=5, lb=0)
    m.Equation(sum([1 / s[i] for i in machine_task_list[0]]) == M1)
    m.Equation(sum([1 / s[i] for i in machine_task_list[1]]) == M2)

    return m, s, P, M1, M2
예제 #7
0
def solve03():
    # Variable and Equation Arrays
    m = GEKKO()
    p = m.Param(1.2)
    x = m.Array(m.Var, 3)
    eq0 = x[1] == x[0] + p
    eq1 = x[2] - 1 == x[1] + x[0]
    m.Equation(x[2] == x[1]**2)
    m.Equations([eq0, eq1])
    m.solve()
    for i in range(3):
        print('x[' + str(i) + ']=' + str(x[i].value))
예제 #8
0
import numpy as np
from gekko import GEKKO

m = GEKKO(remote=False)

# Random 3x3
A = np.random.rand(3, 3)
# Random 3x1
b = np.random.rand(3, 1)
# Gekko array 3x3
p = m.Array(m.Param, (3, 3))
# Gekko array 3x1
y = m.Array(m.Var, (3, 1))

# Dot product of A p
x = np.dot(A, p)
# Dot product of x y
w = np.dot(x, y)
# Dot product of p y
z = np.dot(p, y)
# Trace (sum of diag) of p
t = np.trace(p)

# solve Ax = b
s = m.axb(A, b)
m.solve()
예제 #9
0
# gamma1=0.063
# gamma2=0.05

beta = 0.2967

Pmax = 0.03
Pmax0 = 8.9
Pmin = 0
Pmaxper = 0.0005

Ts = 1

n = 200

S = m.Array(m.Var, (n))
U = m.Array(m.Var, (n))
Q = m.Array(m.Var, (n))
C = m.Array(m.Var, (n))
Cper = m.Array(m.Var, (n - 1))
u = m.Array(m.Var, (n - 1))

m.Equation(S[0] == 8.9)
m.Equation(U[0] == 0.001)
m.Equation(Q[0] == 0)
m.Equation(C[0] == 0)

s = 0

for j in range(n - 1):
    m.Equation(S[j + 1] == S[j] - Ts * beta * S[j] * U[j] / N)
farms = ['Nebraska','Colorado']
warehouses = ['Kansas City','Omaha','Des Moines']
stores = ['Chicago','St. Louis','Cincinnati']

# Shipping costs
ship_farms = pd.DataFrame([[16.0, 10.0, 12.0], [15.0,14.0,17.0]], columns=warehouses, index=farms)
ship_warehouses = pd.DataFrame([[6.0,8.0,10.0],[7.0,11.0,11.0],[4.0,5.0,12.0]], columns=stores, index=warehouses)

# Supply and Demand
supply= pd.DataFrame([[300],[300]], index=farms, columns=['Supply'])
demand = pd.DataFrame([[200],[100],[300]], index=stores, columns=['Demand'])

###############################
# Model Details

x_a = m.Array(m.Var, (2, 3), lb=0, value=1)  # Farm -> Warehouse
x_b = m.Array(m.Var, (3, 3), lb=0, value=1)  # Warehouse -> Stores

# Intermediates
# Sum products (X * Costs)
stage_a_costs = m.Intermediate(sum(
                        [ (x_a[r, c] * ship_farms.iloc[r, c]) 
                          for r, c in product(range(2), range(3)) ] ))

stage_b_costs = m.Intermediate(sum(
                        [ (x_b[r, c] * ship_warehouses.iloc[r, c])
                          for r, c in product(range(3), range(3)) ] ))

# Sums for rows and columns for constraints
from_nebraska     = m.Intermediate(sum([x_a[0, c] for c in range(3)]))
from_colorado     = m.Intermediate(sum([x_a[1, c] for c in range(3)]))
예제 #11
0
from gekko import GEKKO
import numpy as np
m = GEKKO(remote=False)
x1 = m.Param(-2)
x2 = m.Param(-1)
x3 = np.linspace(0, 1, 6)
x4 = m.Array(m.Param, 3)
y4 = m.Array(m.Var, 3)
y5 = m.Intermediate(3)
for i in range(3):
    x4[i].value = -0.2
    y4[i] = m.abs3(x4[i])
# create variable
y = m.Var()
# y = 3.6 =            -2 -1   + 3          + 0            +3        + 0.6
m.Equation(y == m.sum([x1, x2]) + m.sum(x3) + m.sum([x1 + x2, x3, y5]) +
           sum(y4))
m.solve()  # solve
print('x1: ' + str(x1.value))
print('x2: ' + str(x2.value))
print('y: ' + str(y.value))
N = 10
beta = 0.75
epsilon = 1 / 5
mu = 1 / 30295
gamma = 1 / 5
alpha = 0.006

Ts = 1

DeltaDmax = 0.003
Dmax = 0.1

lambda1 = mu * N

n = 100
I = m.Array(m.Var, (n))
E = m.Array(m.Var, (n))
S = m.Array(m.Var, (n))
R = m.Array(m.Var, (n))
D = m.Array(m.Var, (n))
Dper = m.Array(m.Var, (n - 1))
u = m.Array(m.Var, (n - 1))

m.Equation(I[0] == 0.001)
m.Equation(E[0] == 0.02)
m.Equation(S[0] == 9.979)
m.Equation(R[0] == 0)
m.Equation(D[0] == 0)

s = 0
예제 #13
0
def init_relaxed_opt_solver(mrt, G, num_tasks, num_machines, w):
    """
    prepares the relaxed optimal solver by adding the necessary constraints
    :param mrt: Boolean variable that is True if objective is to optimize for
                MRT + E, False if objective is to optimize Makespan + E.
    :param G: DAG to schedule
    :param num_tasks: total number of tasks
    :param w: weights
    :return: m, s, c
    """
    m = GEKKO()

    # Use IPOPT solver (default)
    m.options.SOLVER = 3

    # Change to parallel linear solver
    #m.solver_options = ['minlp_max_iter_with_int_sol 10000']

    # create array
    s = m.Array(m.Var, num_tasks)
    for i in range(num_tasks):
        s[i].value = 2.0
        s[i].lower = 0

    # define completion time of each task
    c = m.Array(m.Var, num_tasks)
    for i in range(num_tasks):
        c[i].value = 0
        c[i].lower = 0

    # relaxation of variables to take on a value in [0,1]
    x = [[m.Var(0, lb=0, ub=1) for j in range(num_tasks)]
         for i in range(num_machines)]

    # 1a
    # each task will be assigned to exactly one machine
    for j in range(num_tasks):
        m.Equation(m.sum([x[i][j] for i in range(num_machines)]) == 1)

    # 1b
    # task's completion time must be later than the time to run task itself
    for j in range(num_tasks):
        m.Equation(w[j] / s[j] <= c[j])

    # 1c
    # task must start later than all ancestors
    for j in range(num_tasks):
        for k in nx.algorithms.ancestors(G, j):
            m.Equation(c[k] + (w[j] / s[j]) <= c[j])

    M = m.Var(value=5, lb=0)
    P = m.Var(value=5, lb=0)
    MRT = m.Var(value=5, lb=0)

    # Total load assigned to each machine should not be greater than the makespan
    for i in range(num_machines):
        m.Equation(
            m.sum([w[j] * x[i][j] / s[j] for j in range(num_tasks)]) <= M)

    # 1e (define M in objective function)
    for j in range(num_tasks):
        m.Equation(c[j] <= M)

    # define P in objective function
    m.Equation(m.sum([w[j] * s[j] for j in range(num_tasks)]) == P)

    # define MRT
    m.Equation(m.sum([c[j] for j in range(num_tasks)]) == MRT)

    if mrt:
        m.Obj(MRT + P)

    else:

        m.Obj(P + M)  # Objective

    return x, m, s, c
예제 #14
0
def assignment_simple_gekko2(candidate_dic, position_list, fitness_dic, G):

    m = GEKKO()
    m.options.SOLVER = 1
    m.options.MAX_MEMORY = 3000000  # APOPT is an MINLP solver

    # optional solver settings with APOPT
    m.solver_options = ['minlp_maximum_iterations 1000', \
                        # minlp iterations with integer solution

                        'minlp_max_iter_with_int_sol 10', \
                        # treat minlp as nlp

                        'minlp_as_nlp 0', \
                        # nlp sub-problem max iterations

                        'nlp_maximum_iterations 500', \
                        # 1 = depth first, 2 = breadth first

                        'minlp_branch_method 1', \
                        # maximum deviation from whole number

                        'minlp_integer_tol 0.05', \
                        # covergence tolerance

                        'minlp_gap_tol 0.01']
    X = m.Array(m.Var, len(fitness_dic), integer=True)
    for xi in X:
        xi.value = 0
        xi.lower = 0
        xi.upper = 1

    fitness_index_dic = dict(zip(fitness_dic.keys(), range(len(fitness_dic))))

    weight_list = list(fitness_dic.values())
    weight_list = [float(item) for item in weight_list]
    candidate_pair_list = list(fitness_dic.keys())

    objective = sum([X[i] * weight_list[i] for i in range(len(weight_list))])
    objective.NAME = simplify_Objective(objective.NAME, len(X))
    m.Maximize(objective)

    pos_cand_dic = {}
    cand_pos_dic = {}
    for i in range(len(candidate_pair_list)):
        (c, p) = candidate_pair_list[i]
        if p in pos_cand_dic:
            pos_cand_dic[p].append(c)
        else:
            pos_cand_dic[p] = [c]

        if c in cand_pos_dic:
            cand_pos_dic[c].append(p)
        else:
            cand_pos_dic[c] = [p]

    score_tuple_dic = neighbor_info(G, position_list)

    for p, cands in pos_cand_dic.items():
        indices = []
        (mm, ff) = score_tuple_dic[p]
        m_ind = []
        f_ind = []
        for c in cands:
            i = fitness_index_dic[(c, p)]
            indices.append(i)
            if candidate_dic[c] == 'male':
                m_ind.append(i)
            else:
                f_ind.append(i)

        #constraint
        z = sum([X[i] for i in indices])
        z.NAME = simplify_Objective(z.NAME, len(X))
        m.Equation(z == 1)

        a1 = mm - ff
        a2 = ff - mm
        o1 = sum([X[i] for i in m_ind])
        o2 = sum([X[i] for i in f_ind])

        if len(m_ind) > 0:
            o1.NAME = simplify_Objective(o1.NAME, len(X))
        if len(f_ind) > 0:
            o2.NAME = simplify_Objective(o2.NAME, len(X))

        m.Minimize(a1 + o1 + (-1) * (o2))
        m.Minimize(a2 + o2 + (-1) * (o1))
        x = 0

    for c, pos in cand_pos_dic.items():
        indices = []
        for p in pos:
            i = fitness_index_dic[(c, p)]
            indices.append(i)
        z = sum([X[i] for i in indices])
        z.NAME = simplify_Objective(z.NAME, len(X))
        m.Equation(z == 1)
    try:
        m.solve(disp=False)
        result = X.copy()
        result_list = [item.value[0] for item in result]

        G_output = G.copy()
        att_dic = nx.get_node_attributes(G_output, 'att')

        score = 0.0
        matched = []
        for i in range(len(result)):
            if result_list[i] == 1:
                (c, p) = candidate_pair_list[i]
                matched.append((c, p))
                score += float(fitness_dic[(c, p)])
                att_dic[p] = candidate_dic[c]

        nx.set_node_attributes(G_output, att_dic, 'att')

        #print(matched)
    except:
        return G, []
    return G_output, matched
예제 #15
0
from gekko import GEKKO
import numpy as np
m = GEKKO(remote=False)
ni = 3; nj = 2; nk = 4
# solve AX=B
A = m.Array(m.Var,(ni,nj),lb=0)
X = m.Array(m.Var,(nj,nk),lb=0)
AX = np.dot(A,X)
B = m.Array(m.Var,(ni,nk),lb=0)
# equality constraints
m.Equations([AX[i,j]==B[i,j] for i in range(ni) \
                             for j in range(nk)])
m.Equation(5==m.sum([m.sum([A[i][j] for i in range(ni)]) \
                                    for j in range(nj)]))
m.Equation(2==m.sum([m.sum([X[i][j] for i in range(nj)]) \
                                    for j in range(nk)]))
# objective function
m.Minimize(m.sum([m.sum([B[i][j] for i in range(ni)]) \
                                 for j in range(nk)]))
m.solve()
print(A)
print(X)
print(B)
예제 #16
0
class Optimizer():
    def __init__(self):
        # Queue for data thread safe
        self.data = queue.LifoQueue()
        self.control_data = queue.LifoQueue()

        # Create thread lock
        # self.lock = threading.Lock()

        # stop thread variable
        self.stop = False

        # variable to prevent multiple solutions form running
        self.solving = False

        # Create thread parameters
        self.MPC_thread = threading.Thread(target=self.run, args=(), daemon=True)

        # Controller state to pass into get_output function
        self.controllerState = con.Controller()

        # Optimal Control data updated by thread
        self.u_pitch_star = 0.0
        self.u_star = 0.0


        # time.sleep(1)
        # self.MPC_queue.put('worked')

        # Initialize optimization parameters
        self.initialize_optimization()


    def initialize_optimization(self):
################# AIRBORNE OPTIMIZER SETTINGS################ NOW IN 3D
        self.m = GEKKO(remote=False) # Airborne optimzer

        nt = 11
        self.m.time = np.linspace(0, 1, nt)


        # options
        # self.m.options.NODES = 3
        self.m.options.SOLVER = 3
        self.m.options.IMODE = 6# MPC mode
        # m.options.IMODE = 9 #dynamic ode sequential
        self.m.options.MAX_ITER = 200
        self.m.options.MV_TYPE = 0
        self.m.options.DIAGLEVEL = 0

        # final time
        self.tf = self.m.FV(value=1.0,lb=0.1,ub=100.0)

        # tf = m.FV(value=5.0)
        self.tf.STATUS = 1

        # Scaled time for Rocket league to get proper time
        self.ts = np.multiply(self.m.time, self.tf)

        # some constants
        self.g = 650 # Gravity (my data says its more like 670)
        # v_end = 500

        # force (thruster)
        self.u_thrust = self.m.FV(value=1.0,lb=0.0,ub=1.0) #Fixed variable, stays on entire time
        self.u_thrust = self.m.MV(value=1, lb=0, ub=1) # Manipulated variable non integaer
        # self.u_thrust = self.m.MV(value=0,lb=0,ub=1, integer=True) #Manipulated variable integer type
        self.u_thrust.STATUS = 1
        self.u_thrust.DCOST = 1e-5

        # angular acceleration for all 3 axes
        self.u_pitch = self.m.MV(value=0.0, lb=-1.0, ub=1.0)
        self.u_pitch.STATUS = 1
        self.u_pitch.DCOST = 1e-5

        self.u_roll = self.m.MV(value=0.0, lb=-1.0, ub=1.0)
        self.u_roll.STATUS = 1
        self.u_roll.DCOST = 1e-5

        self.u_yaw = self.m.MV(value=0.0, lb=-1.0, ub=1.0)
        self.u_yaw.STATUS = 1
        self.u_yaw.DCOST = 1e-5

        self.Tr = -36.07956616966136; # torque coefficient for roll
        self.Tp = -12.14599781908070; # torque coefficient for pitch
        self.Ty =   8.91962804287785; # torque coefficient for yaw
        self.Dr =  -4.47166302201591; # drag coefficient for roll
        self.Dp = -2.798194258050845; # drag coefficient for pitch
        self.Dy = -1.886491900437232; # drag coefficient for yaw

        # # integral over time for u^2
        # self.u2 = self.m.Var(value=0.0)
        # self.m.Equation(self.u2.dt() == 0.5*self.u_thrust**2)
        #
        # # integral over time for u_pitch^2
        # # self.u2_pitch = self.m.Var(value=0)
        # # self.m.Equation(self.u2.dt() == 0.5*self.u_pitch**2)
        
        # end time variables to multiply u2 by to get total value of integral
        self.p = np.zeros(nt)
        self.p[-1] = 1.0
        self.final = self.m.Param(value = self.p)


#################GROUND DRIVING OPTIMIZER SETTTINGS##############
        self.d = GEKKO(remote=False) # Driving on ground optimizer

        ntd = 9
        self.d.time = np.linspace(0, 1, ntd) # Time vector normalized 0-1

        # options
        # self.d.options.NODES = 2
        self.d.options.SOLVER = 1
        self.d.options.IMODE = 6# MPC mode
        # self.d.options.IMODE = 9 #dynamic ode sequential
        self.d.options.MAX_ITER = 500
        self.d.options.MV_TYPE = 0
        self.d.options.DIAGLEVEL = 0

        # final time for driving optimizer
        self.tf_d = self.d.FV(value=1.0,lb=0.1,ub=100.0)

        # allow gekko to change the tfd value
        self.tf_d.STATUS = 1

        # Scaled time for Rocket league to get proper time


        # Boost variable, its integer type since it can only be on or off
        self.u_thrust_d = self.d.MV(integer = True, lb=0,ub=1) #Manipulated variable integer type
        self.u_thrust_d.STATUS = 1
        # self.u_thrust_d.DCOST = 1e-5

        # Throttle value, this can vary smoothly between 0-1
        self.u_throttle_d = self.d.MV(value = 1, lb = 0.1, ub = 1)
        self.u_throttle_d.STATUS = 1
        self.u_throttle_d.DCOST = 1e-5

        # Turning input value also smooth
        self.u_turning_d = self.d.MV(value = 0, lb = -1, ub = 1)
        self.u_turning_d.STATUS = 1
        self.u_turning_d.DCOST = 1e-5

        # end time variables to multiply u2 by to get total value of integral
        self.p_d = np.zeros(ntd)
        self.p_d[-1] = 1.0
        self.final_d = self.d.Param(value = self.p_d)

    def MPC_optimize(self, car, ball):
        #NOTE: I should make some data structures to easily pass this data around as one variable instead of so many variables

        # variables intial conditions are placed here
        # CAR VARIABLES
        # NOTE: maximum velocites, need to be total velocity magnitude, not max on indididual axes, as you can max on both axes but actually be above the true max velocity of the game
#--------------------------------
        # Position of car vector
        self.s = self.m.Array(self.m.Var,(3))
        ig = [car.x,car.y, car.z]

        #Initialize values for each array element
        i = 0
        for xi in self.s:
            xi.value = ig[i]
            xi.lower = -2300.0
            xi.upper = 2300
            i += 1
#--------------------------------
        #velocity of car vector
        self.v = self.m.Array(self.m.Var,(3))
        ig = [car.vx,car.vy, car.vz]

        #Initialize values for each array element
        i = 0
        for xi in self.v:
            xi.value = ig[i]
            xi.lower = -2300.0
            xi.upper = 2300
            i += 1

        # Pitch rotation and angular velocity
        # self.roll = self.m.Var(value = car.roll)
        # self.pitch = self.m.Var(value = car.pitch) #orientation pitch angle
        # self.yaw = self.m.Var(value = car.yaw)
        # self.omega_roll = self.m.Var(value = car.wx, lb = -5.5, ub = 5.5)
        # self.omega_pitch = self.m.Var(value=car.wy, lb=-5.5, ub=5.5) #angular velocity
        # self.omega_yaw = self.m.Var(value = car.wz, lb = -5.5, ub = 5.5)
#--------------------------------
        #Orientation Quaternion
        self.q = self.m.Array(self.m.Var, (4))
        q = euler_to_quaternion(car.roll, car.pitch, car.yaw)
        ig = [q[0], q[1], q[2], q[3]]

        #Initialize values for each array element
        i = 0
        for xi in self.q:
            xi.value = ig[i]
            i += 1
#--------------------------------
        #Angular Velocity quaternion
        self.q_dt = self.m.Array(self.m.Var, (4))

        #Initialize values for each array element
        ig = [0, car.wx, car.wy, car.wz]

        #Initialize values for each array element
        i = 0
        for xi in self.q_dt:
            xi.value = ig[i]
            i += 1
#--------------------------------
        #Thrust direction vector from quaternion
        self.thrust_direction_x = self.m.Var(value = get_thrust_direction_x(self.q))
        self.thrust_direction_y = self.m.Var(value = get_thrust_direction_y(self.q))
        self.thrust_direction_z = self.m.Var(value = get_thrust_direction_z(self.q))

        #Rworld_to_car
        # r = self.roll #rotation around roll axis to get world to car frame
        # p = self.pitch #rotation around pitch axis to get world to car frame
        # y = -1*self.yaw #rotation about the world z axis to get world to car frame
        # self.Rx = np.matrix([[1, 0, 0], [0, math.cos(r), -1*math.sin(r)], [0, math.sin(r), math.cos(r)]])
        # self.Ry = np.matrix([[math.cos(p), 0, math.sin(p)], [0, 1, 0], [-1*math.sin(p), 0, math.cos(p)]])
        # self.Rz = np.matrix([[math.cos(y), -1*math.sin(y), 0], [math.sin(y), math.cos(y), 0], [0, 0, 1]])
        # #Order of rotations from world to car is x then y then z
        # self.Rinter = np.matmul(self.Rx, self.Ry)
        # self.Rworld_to_car = np.matmul(self.Rinter, self.Rz)
        # self.q = Quaternion(matrix = self.Rworld_to_car).normalised #orientation quaternion created from rotation matrix derived from euler qngle "sensor"
        # self.qi = self.q.inverse

        # BALL VARIABLES
        # NOTE: same issue with max velocity as car, will fix later
        self.ball_s = self.m.Array(self.m.Var,(3)) #Ball position
        self.ball_s[0].value = ball.x
        self.ball_s[1].value = ball.y
        self.ball_s[2].value = ball.z

        self.ball_v = self.m.Array(self.m.Var,(3)) #Ball Velocity
        self.ball_v[0].value = ball.vx
        self.ball_v[1].value = ball.vy
        self.ball_v[2].value = ball.vz

        # differential equations scaled by tf
        thrust = np.array([991.666+66.666, 0, 0]) #Thrust lies along the car's local x axis only, so need to rotate this by quaternio car is rotated by to get thrust in each axis
        q = np.array([self.q[0],self.q[1],self.q[2]])
        # qi = np.array([self.qi[0],self.qi[1],self.qi[2]])
        # print(self.q.rotate(t))
        # self.thrust_direction = self.m.Array(self.m.Intermediate(self.u_thrust.value * self.q[0]))
        # self.thrust_direction_y = self.m.Intermediate(self.q.rotate(thrust)[1])
        # self.thrust_direction_z = self.m.Intermediate(self.q.rotate(t)[2])  #Intermediate thrust direction vector rotated by the quaternion


        # CARS DIFFERENTIAL EQUATIONS
            #angular orientatio quaternion and angular velocity quaternion

            #position and velocity
        self.m.Equation(self.s[0].dt()==self.tf * self.v[0])
        self.m.Equation(self.s[1].dt()==self.tf * self.v[1])
        self.m.Equation(self.s[2].dt()==self.tf * self.v[2])


        self.m.Equation(self.v[0].dt()==self.tf * ((self.u_thrust*self.thrust_direction_x)))
        self.m.Equation(self.v[1].dt()==self.tf * ((self.u_thrust*self.thrust_direction_y)))
        self.m.Equation(self.v[2].dt()==self.tf * ((self.u_thrust*self.thrust_direction_z)))

        # self.m.Equation(self.pitch.dt()==self.tf * self.omega_pitch)
        # self.m.Equation(self.omega_pitch.dt()== self.tf * ((self.u_pitch*self.Tp) + (self.omega_pitch*self.Dp*(1.0-self.m.sqrt(self.u_pitch*self.u_pitch)))))

        # BALLS DIFFERENTIAL EQUATIONS
        self.m.Equation(self.ball_s[0].dt()==self.tf * self.ball_v[0])
        self.m.Equation(self.ball_s[1].dt()==self.tf * self.ball_v[1])
        self.m.Equation(self.ball_s[2].dt()==self.tf * self.ball_v[2])

        self.m.Equation(self.ball_v[0].dt()==self.tf * 0)
        self.m.Equation(self.ball_v[1].dt()==self.tf * 0)
        self.m.Equation(self.ball_v[2].dt()==self.tf * (-1.0*self.g))

        # self.m.Equation(self.error == self.sx - trajectory_sx)

        # hard constraints
        # self.m.fix(self.sz, pos = len(self.m.time) - 1, val = 1000)


        #Soft constraints for the end point
        # Uncomment these 4 objective functions to get a simlple end point optimization
        #sf[1] is z position @ final time etc...
        # self.m.Obj(self.final*1e3*(self.sz-sf[1])**2) # Soft constraints
        # self.m.Obj(self.final*1e3*(self.vz-vf[1])**2)
        # self.m.Obj(self.final*1e3*(self.sx-sf[0])**2) # Soft constraints
        # self.m.Obj(self.final*1e3*(self.vx-vf[0])**2)

        # Objective values to hit into ball in minimal time
        self.m.Obj(self.final*1e4*(self.s[2]-self.ball_s[2])**2) # Soft constraints
        self.m.Obj(self.final*1e4*(self.s[1]-self.ball_s[1])**2) # Soft constraints
        self.m.Obj(self.final*1e4*(self.s[0]-self.ball_s[0])**2) # Soft constraints

        # Objective funciton to hit with a particular velocity
        # self.m.Obj(self.final*1e3*(self.vz/)**2)
        # self.m.Obj(self.final*1e4*(self.vx + 1000)**2)
        #Objective function to minimize time
        self.m.Obj(self.tf * 1e3)

        #Objective functions to follow trajectory
        # self.m.Obj(self.final * (self.errorx **2) * 1e3)

        # self.m.Obj(self.final*1e3*(self.sx-traj_sx)**2) # Soft constraints
        # self.m.Obj(self.errorz)
        # self.m.Obj(( self.all * (self.sx - trajectory_sx) **2) * 1e3)
        # self.m.Obj(((self.sz - trajectory_sz)**2) * 1e3)

        # minimize thrust used
        # self.m.Obj(self.u2*self.final*1e3)

        # minimize torque used
        # self.m.Obj(self.u2_pitch*self.final)

        #solve
        # self.m.solve('http://127.0.0.1') # Solve with local apmonitor server
        self.m.solve()

        # NOTE: another data structure type or class here for optimal control vectors
        # Maybe it should have some methods to also make it easier to parse through the control vector etc...
        # print('time', np.multiply(self.m.time, self.tf.value[0]))
        # time.sleep(3)

        # self.ts = np.multiply(self.m.time, self.tf.value[0])
        # print('ts', self.ts)
        # print('ustar', self.u_pitch.value)
        # time.sleep(0.10)
        return self.u_thrust, self.u_pitch#, self.ts, self.sx, self.sz, self.ball_sx, self.ball_sz, self.ball_vz, self.pitch



    def run(self):
        while(self.stop == False):
            try:
                print('in run function')
                [car, car_desired] = self.data.get()
                print('car actual', car.position, 'car desired', car_desired.position)

                if(car != None and self.solving == False):
                    self.solving = True
                    self.optimizeDriving(copy.deepcopy(car), copy.deepcopy(car_desired))
                    print('t', self.ts_d, 'u_turn', self.u_turning_d.value)

                    #Push data to control data queue
                    self.control_data.put([self.ts_d, self.u_throttle_d, self.u_turning_d, self.u_thrust_d])

                    # Save local control vector and time that the control vector should start
            except Exception as e:
                print('Exception in optimization thread', e)
                traceback.print_exc()
예제 #17
0
from gekko import GEKKO
import numpy as np
import numpy.random as random

m = GEKKO(remote=True)

Nh = random.randint(low=1, high=5)  #corresponds to i
Nc = random.randint(low=1, high=5)  #corresponds to j

Nhe = 2 * (Nh + Nc)  #corresponds to m
Cph = np.full(shape=Nh, fill_value=4.2)
Cpc = np.full(shape=Nc, fill_value=4.2)
h = 1

Thin = m.Array(m.FV, (Nhe, Nh))
Tcin = m.Array(m.FV, (Nhe, Nc))

#tracking array
trackhot = []
trackcold = []

#random inlet hot temperature case
Th_i0 = m.Array(m.Const, (1, Nh))

for Th in Th_i0[0]:
    Th.value = random.uniform(low=30, high=300)
    trackhot.append(Th.value)

#random inlet cold temperature case
Tc_j0 = m.Array(m.Const, (1, Nc))
for Tc in Tc_j0[0]:
예제 #18
0
from gekko import GEKKO    
m = GEKKO(remote=False)

# create variables
x1,x2,x3,x4 = m.Array(m.Var,4,lb=1,ub=5)

# initial guess values
x1.value = 1; x2.value = 5; x3.value = 5; x4.value = 1

m.Equation(x1*x2*x3*x4>=25)
m.Equation(x1**2+x2**2+x3**2+x4**2==40)
m.Minimize(x1*x4*(x1+x2+x3)+x3)
m.solve(disp=False)

print('Results')
print('x1: ' + str(x1.value[0])); print('x2: ' + str(x2.value[0]))
print('x3: ' + str(x3.value[0])); print('x4: ' + str(x4.value[0]))
예제 #19
0
def HE_solve(T_hot, T_cold, Num_HE):

    inf = 1000000000

    m = GEKKO(remote=True)
    '''
	Nh=random.randint(low=1,high=4) #corresponds to i
	Nc=random.randint(low=1,high=4) #corresponds to j
	Nhe=5    #corresponds to m
	'''

    Nh = T_hot.__len__()  #corresponds to i
    Nc = T_cold.__len__()  #corresponds to j
    Nhe = Num_HE  #corresponds to m

    #Initialize Cp array
    Cph = [m.Const(value=4.2) for i in range(Nh)]
    Cpc = [m.Const(value=4.2) for i in range(Nc)]

    #Initialize h array
    hh = [m.Const(value=1) for i in range(Nh)]
    hc = [m.Const(value=1) for i in range(Nc)]

    EMAT = [m.Const(value=10) for i in range(Nhe)]

    objMES = True

    #Temperature for Hot Stream

    #tracking array
    trackhot = []
    trackcold = []
    '''
	#random inlet hot temperature case
	Th_i0=m.Array(m.Const,(1,Nh))
	Thf=[m.Const(value=200) for i in range(Nh)]#250
	for Th in Th_i0[0]:
		#Th.value=random.uniform(low=260,high=400) #random inlet   
	  Th.value=400
	  trackhot.append(Th.value)
		
	#random inlet cold temperature case
	Tc_j0=m.Array(m.Const,(1,Nc))
	Tcf=[m.Const(value=150) for i in range(Nc)]

	for Tc in Tc_j0[0]:
		#Tc.value=random.uniform(low=0,high=50) 
	  Tc.value=40
	  trackcold.append(Tc.value)
	'''
    #random inlet hot temperature case
    Th_i0 = m.Array(m.Const, (1, Nh))
    Thf = [m.Const(value=200) for i in range(Nh)]  #250

    for i in range(Nh):
        #Th.value=random.uniform(low=260,high=400) #random inlet
        Th_i0[0][i].value = T_hot[i]
        trackhot.append(Th_i0[0][i].value)

    #random inlet cold temperature case
    Tc_j0 = m.Array(m.Const, (1, Nc))
    Tcf = [m.Const(value=150) for i in range(Nc)]

    for i in range(Nc):
        #Tc.value=random.uniform(low=0,high=50)
        Tc_j0[0][i].value = T_cold[i]
        trackcold.append(Tc_j0[0][i].value)

    #announce heat exchanger
    print("Number of hot stream = ", Nh)
    print("Number of cold stream = ", Nc)
    print("Hot Stream Temperature=", trackhot)
    print("Cold Stream Temperature=", trackcold)

    #Integrated Heat
    Qm = [m.Var(lb=0, ub=inf) for i in range(Nhe)]

    #Heat cascade
    Thin = [[m.Var(lb=0, ub=inf) for i in range(Nhe)] for i in range(Nh)]
    Thout = [[m.Var(lb=0, ub=inf) for i in range(Nhe)] for i in range(Nh)]

    #Cold cascade
    Tcin = [[m.Var(lb=0, ub=inf) for i in range(Nhe)] for i in range(Nc)]
    Tcout = [[m.Var(lb=0, ub=inf) for i in range(Nhe)] for i in range(Nc)]

    #Heat and cool binary
    wh = [[m.Var(lb=-0.1, ub=1.1, integer=True) for i in range(Nhe)]
          for i in range(Nh)]
    wc = [[m.Var(lb=-0.1, ub=1.1, integer=True) for i in range(Nhe)]
          for i in range(Nc)]

    for k in range(Nhe):
        m.Equation(sum([wh[j][k] for j in range(Nh)]) == 1)
        m.Equation(sum([wc[j][k] for j in range(Nc)]) == 1)

    #Eq2 First row of Heat Matrix
    for i in range(Nh):
        m.Equation(Thin[i][0] == Th_i0[0][i])

    #Eq5 First Row of Cool Matrix
    for i in range(Nc):
        m.Equation(Tcin[i][Nhe - 1] == Tc_j0[0][i])

    #Eq3 and Eq6 Heat balance and Eq4 and Eq7 cascade operation
    for k in range(Nhe):
        for i in range(Nh):
            m.Equation(Thout[i][k] == Thin[i][k] - wh[i][k] * Qm[k] / Cph[i])
            if k != 0:
                m.Equation(Thin[i][k] == Thout[i][k - 1])
        for j in range(Nc):
            m.Equation(Tcout[j][k] == Tcin[j][k] + wc[j][k] * Qm[k] / Cpc[j])
            if k != Nhe - 1:
                m.Equation(Tcin[i][k] == Tcout[i][k - 1])

    #Additional cooler and heater
    Qcu = [m.Var(lb=0, ub=inf) for i in range(Nh)]
    Qhu = [m.Var(lb=0, ub=inf) for i in range(Nc)]

    #for MES Objective
    whQ = [[m.Var(value=0, lb=0, ub=inf) for i in range(Nhe)]
           for i in range(Nh)]
    wcQ = [[m.Var(value=0, lb=0, ub=inf) for i in range(Nhe)]
           for i in range(Nc)]

    for k in range(Nhe):
        for i in range(Nh):
            m.Equation(whQ[i][k] == wh[i][k] * Qm[k])

    for j in range(Nc):
        m.Equation(wcQ[j][k] == wc[j][k] * Qm[k])

    for i in range(Nh):
        m.Equation(Qcu[i] == Cph[i] * (Th_i0[0][i] - Thf[i]) - sum(whQ[i]))

    for i in range(Nc):
        m.Equation(Qhu[i] == Cpc[i] * (Tcf[i] - Tc_j0[0][i]) - sum(wcQ[i]))

    if objMES == True:
        m.Obj(0.2 * sum(Qcu) + 0.8 * sum(Qhu))

    #Temperature of Recovert Heat Exchanger
    Thhin = [m.Var(lb=0, ub=inf) for i in range(Nhe)]
    Thhout = [m.Var(lb=0, ub=inf) for i in range(Nhe)]
    Tccin = [m.Var(lb=0, ub=inf) for i in range(Nhe)]
    Tccout = [m.Var(lb=0, ub=inf) for i in range(Nhe)]

    for k in range(Nhe):
        m.Equation(
            Thhout[k] == sum([wh[i][k] * Thout[i][k] for i in range(Nh)]))
        m.Equation(
            Tccout[k] == sum([wc[i][k] * Tcout[i][k] for i in range(Nc)]))
        m.Equation(Thhin[k] == sum([wh[i][k] * Thin[i][k] for i in range(Nh)]))
        m.Equation(Tccin[k] == sum([wc[i][k] * Tcin[i][k] for i in range(Nc)]))

    #Feasibility constraint

    for k in range(Nhe):
        m.Equation(Thhin[k] >= Tccout[k] + EMAT[k])
        m.Equation(Thhout[k] >= Tccin[k] + EMAT[k])

    for i in range(Nh):
        m.Equation(sum(whQ[i]) >= 0)
        m.Equation(sum(whQ[i]) <= Cph[i] * (Th_i0[0][i] - Thf[i]))
        m.Equation(Qcu[i] >= 0)
        m.Equation(Qcu[i] <= Cph[i] * (Th_i0[0][i] - Thf[i]))
        #m.Equation(Thout[i][Nhe-1]>=Thf[i])#Temperature down in cooler

    for j in range(Nc):
        m.Equation(sum(wcQ[j]) >= 0)
        m.Equation(sum(wcQ[j]) <= Cpc[j] * (Tcf[j] - Tc_j0[0][j]))
        m.Equation(Qhu[j] >= 0)
        #m.Equation(Tcout[j][0]<=Tcf[j]) #Temperature up in heater
        m.Equation(Qhu[j] <= Cpc[j] * (Tcf[j] - Tc_j0[0][j]))
    '''
	#Making sure that temperature follows sequence
	for k in range(Nhe-1):
		for i in range(Nh):
			m.Equation(Thout[i][k]>=Thout[i][k+1]) #follow sequence
		for j in range(Nc):
			m.Equation(Tcout[j][k]<=Tcout[i][k+1]) #follow sequence
	'''
    #Eqn 19-22 Cooler Heater Temperature
    Tcooler_hin = [m.Var(lb=0, ub=inf) for i in range(Nh)]
    Tcooler_hout = [m.Var(lb=0, ub=inf) for i in range(Nh)]
    Theater_cin = [m.Var(lb=0, ub=inf) for i in range(Nc)]
    Theater_cout = [m.Var(lb=0, ub=inf) for i in range(Nc)]

    for i in range(Nh):
        m.Equation(Tcooler_hin[i] == Thout[i][Nhe - 1])
        m.Equation(Tcooler_hout[i] == Thf[i])
        #m.Equation(Thf[i]>=Thout[i][Nhe-1])
    for i in range(Nc):
        m.Equation(Theater_cin[i] == Tcout[i][0])
        m.Equation(Theater_cout[i] == Tcf[i])
        #m.Equation(Tcf[i]<=Tcout[i][0])

    m.options.SOLVER = 1
    m.solver_options = ['minlp_maximum_iterations 5000', \
	# minlp iterations with integer solution

    'minlp_max_iter_with_int_sol 5000', \
	# treat minlp as nlp

    'minlp_as_nlp 0', \
	# nlp sub-problem max iterations

    'nlp_maximum_iterations 2000', \
	# 1 = depth first, 2 = breadth first

    'minlp_branch_method 1', \
	# maximum deviation from whole number

    'minlp_integer_tol 0.001', \
	# covergence tolerance

    'minlp_gap_tol 0.00001']
    try:
        m.solve()
    except:
        return inf
    print(
        sum([
            Cph[i].value * (Th_i0[0][i].value - Thf[i].value)
            for i in range(Nh)
        ]))
    print(
        sum([
            Cpc[i].value * (Tcf[i].value - Tc_j0[0][i].value)
            for i in range(Nc)
        ]))
    import pprint
    pp = pprint.PrettyPrinter(indent=4)
    print("Number of hot stream = ", Nh)
    print("Number of cold stream = ", Nc)
    print("Hot Stream Temperature=", trackhot)
    print("Cold Stream Temperature=", trackcold)

    import pprint
    print("Heat Recovered:", Qm)

    print("Hot binary:")
    print(wh)
    print("Cold binary:")
    print(wc)
    print("Hot Temperature in:", Thhin)
    print("Hot Temperature out:", Thout)
    print("Cooler Temperature:", Tcooler_hin, Tcooler_hout)
    print("Cold Temperature in:", Tcin)
    print("Cold Temperature out:", Tcout)
    print("Heater Temperature:", Theater_cin, Theater_cout)

    return m.options.objfcnval
예제 #20
0
t_incubation = 5.1
t_infective = 3.3
R0 = 2.4
N = 33517

# initial number of infected and recovered individuals
e_initial = 1 / N
i_initial = 0.00
r_initial = 0.00
s_initial = 1 - e_initial - i_initial - r_initial

alpha = 1 / t_incubation
gamma = 1 / t_infective
beta = R0 * gamma

s, e, i, r = m.Array(m.Var, 4)
s.value = s_initial
e.value = e_initial
i.value = i_initial
s.value = s_initial
m.Equations([s.dt()==-(1-u)*beta * s * i,\
             e.dt()== (1-u)*beta * s * i - alpha * e,\
             i.dt()==alpha * e - gamma * i,\
             r.dt()==gamma*i])

t = np.linspace(0, 200, 101)
t = np.insert(t,1,[0.001,0.002,0.004,0.008,0.02,0.04,0.08,\
                   0.2,0.4,0.8])
m.time = t
m.options.IMODE = 7
m.options.NODES = 3
예제 #21
0
from gekko import GEKKO

m = GEKKO()


def f(x, c):
    y = m.sum([(xi - c)**2 for xi in x])
    return y


x1 = m.Array(m.Var, 5)
p = 2.1

m.Minimize(f(x1, p))
m.Equation(f(x1, 0) <= 10)

m.solve()

print(x1)
예제 #22
0
def init_solver(mrt, G, num_tasks, w, order, task_scaling=False):
    """
    prepares the optimization equation by adding the necessary constraints
    :param mrt: Boolean variable that is True if objective is to optimize for 
                MRT + E, False if objective is to optimize Makespan + E.
    :param G: DAG to schedule
    :param num_tasks: total number of tasks
    :param order: ordering
    :param task_scaling: Boolean whether to scale tasks or not
    :return: m, s, c
    """
    m = GEKKO()

    # Use IPOPT solver (default)
    m.options.SOLVER = 3

    # Change to parallel linear solver
    m.solver_options = ['linear_solver ma97']

    # create array
    s = m.Array(m.Var, num_tasks)
    for i in range(num_tasks):
        s[i].value = 2.0
        s[i].lower = 0

    # define completion time of each task
    c = m.Array(m.Var, num_tasks)
    for i in range(num_tasks):
        c[i].value = 0
        c[i].lower = 0

    # 1b
    # task's completion time must be later than the time to run task itself
    for i in range(num_tasks):
        m.Equation(w[i] / s[i] <= c[i])

    # 1c
    # task must start later than all ancestors
    for i in range(num_tasks):
        for j in nx.algorithms.ancestors(G, i):
            m.Equation(c[j] + (w[i] / s[i]) <= c[i])


    # task must start later than previous task on machine
    resource_constraints = get_resource_constraints(order)
    for constraint in resource_constraints:
        task = constraint[1]
        prev = constraint[0]
        m.Equation(c[prev] + (w[task] / s[task]) <= c[task])

    # all tasks on single machine must run at same speed
    if not task_scaling:
        for machine in order:
            for i in range(len(machine)):
                if i != len(machine)-1:
                    m.Equation(s[machine[i]] == s[machine[i+1]])

    P = m.Var(value=5, lb=0)
    m.Equation(m.sum([w[j] * s[j] for j in range(num_tasks)]) == P)

    M = m.Var(value=5, lb=0)
    MRT = m.Var(value=5, lb=0)


    for j in range(num_tasks):
            m.Equation(c[j] <= M)

    for lst in order:
        m.Equation(sum([w[i] / s[i] for i in lst]) <= M)

    # define MRT
    m.Equation(m.sum([c[j] for j in range(num_tasks)]) == MRT)

    if mrt: 
        m.Obj(MRT + P)

    else:

        m.Obj(P + M) # Objective

    
    return m, s, c
예제 #23
0
def assignment_simple_gekko_(candidate_dic, position_list, fitness_dic, G):

    gender = nx.get_node_attributes(G, 'att')
    gender.update(candidate_dic)
    gender_list = list(gender.values())
    m = gender_list.count('male')
    f = gender_list.count('female')
    t = float(m + f)
    m = m / t
    f = f / t
    p1 = m * m * t
    p2 = m * f * t * 2
    p3 = f * f * t

    m = GEKKO()
    m.options.SOLVER = 1
    m.options.MAX_MEMORY = 3000000  # APOPT is an MINLP solver

    # optional solver settings with APOPT
    m.solver_options = ['minlp_maximum_iterations 1000', \
                        # minlp iterations with integer solution

                        'minlp_max_iter_with_int_sol 10', \
                        # treat minlp as nlp

                        'minlp_as_nlp 0', \
                        # nlp sub-problem max iterations

                        'nlp_maximum_iterations 500', \
                        # 1 = depth first, 2 = breadth first

                        'minlp_branch_method 1', \
                        # maximum deviation from whole number

                        'minlp_integer_tol 0.05', \
                        # covergence tolerance

                        'minlp_gap_tol 0.01']
    X = m.Array(m.Var, len(fitness_dic), integer=True)
    for xi in X:
        xi.value = 0
        xi.lower = 0
        xi.upper = 1

    fitness_index_dic = dict(zip(fitness_dic.keys(), range(len(fitness_dic))))

    weight_list = list(fitness_dic.values())
    weight_list = [float(item) for item in weight_list]
    candidate_pair_list = list(fitness_dic.keys())

    objective = sum([X[i] * weight_list[i] for i in range(len(weight_list))])
    objective.NAME = simplify_Objective(objective.NAME, len(X))
    m.Maximize(objective)

    pos_cand_dic = {}
    cand_pos_dic = {}
    for i in range(len(candidate_pair_list)):
        (c, p) = candidate_pair_list[i]
        if p in pos_cand_dic:
            pos_cand_dic[p].append(c)
        else:
            pos_cand_dic[p] = [c]

        if c in cand_pos_dic:
            cand_pos_dic[c].append(p)
        else:
            cand_pos_dic[c] = [p]

    mm_count = 0
    mf_count = 0
    ff_count = 0

    mm_count_ind = []
    mf_count_ind = []
    ff_count_ind = []

    mm_count_ = []
    mf_count_ = []
    ff_count_ = []
    for p in G.nodes():
        neighs = G[p]
        neighs = [item for item in neighs if item > p]
        if gender[p] == 'male':
            for v in neighs:
                if gender[v] == 'male':
                    mm_count += 1
                elif gender[v] == 'female':
                    mf_count += 1
                else:
                    cands = pos_cand_dic[v]
                    for c in cands:
                        i = fitness_index_dic[(c, v)]
                        if candidate_dic[c] == 'male':
                            mm_count_ind.append(i)
                        else:
                            mf_count_ind.append(i)
        elif gender[p] == 'female':
            for v in neighs:
                if gender[v] == 'male':
                    mf_count += 1
                elif gender[v] == 'female':
                    ff_count += 1
                else:
                    cands = pos_cand_dic[v]
                    for c in cands:
                        i = fitness_index_dic[(c, v)]
                        if candidate_dic[c] == 'male':
                            mf_count_ind.append(i)
                        else:
                            ff_count_ind.append(i)
        else:
            cands = pos_cand_dic[p]
            m_ind = []
            f_ind = []
            for c in cands:
                i = fitness_index_dic[(c, p)]
                if candidate_dic[c] == 'male':
                    m_ind.append(i)
                else:
                    f_ind.append(i)
            m_p = sum([X[i] for i in m_ind])
            f_p = sum([X[i] for i in f_ind])

            if len(m_ind) > 0:
                m_p.NAME = simplify_Objective(m_p.NAME, len(X))
            if len(f_ind) > 0:
                f_p.NAME = simplify_Objective(f_p.NAME, len(X))

            m1 = 0
            f1 = 0
            m1_ind = []
            f1_ind = []
            for v in neighs:
                if gender[v] == 'male':
                    m1 += 1
                elif gender[v] == 'female':
                    f1 += 1
                else:
                    cands = pos_cand_dic[v]
                    for c in cands:
                        i = fitness_index_dic[(c, v)]
                        if candidate_dic[c] == 'male':
                            m1_ind.append(i)
                        else:
                            f1_ind.append(i)

            m1_p = sum([X[i] for i in m1_ind]) + m1
            f1_p = sum([X[i] for i in f1_ind]) + f1

            if len(m1_ind) > 0:
                m1_p.NAME = simplify_Objective(m1_p.NAME, len(X))
            if len(f1_ind) > 0:
                f1_p.NAME = simplify_Objective(f1_p.NAME, len(X))

            if len(m_ind) > 0 and (len(m1_ind) > 0 or m1 != 0):
                mm_count_.append(m_p * m1_p)
            if len(m_ind) > 0 and (len(f1_ind) > 0 or f1 != 0):
                mf_count_.append(m_p * f1_p)
            if len(f_ind) > 0 and (len(m1_ind) > 0 or m1 != 0):
                mf_count_.append(f_p * m1_p)
            if len(f_ind) > 0 and (len(f1_ind) > 0 or f1 != 0):
                ff_count_.append(f_p * f1_p)

    ###
    mm_count__ = sum([X[i] for i in mm_count_ind])
    mf_count__ = sum([X[i] for i in mf_count_ind])
    ff_count__ = sum([X[i] for i in ff_count_ind])

    mm_count_ = sum(mm_count_)
    mf_count_ = sum(mf_count_)
    ff_count_ = sum(ff_count_)

    mm_count = mm_count_ + mm_count__ + mm_count
    ff_count = ff_count_ + ff_count__ + ff_count
    mf_count = mf_count_ + mf_count__ + mf_count

    m.Minimize(mm_count - p1)
    m.Minimize(p1 - mm_count)
    m.Minimize(mf_count - p2)
    m.Minimize(p2 - mf_count)
    m.Minimize(ff_count - p3)
    m.Minimize(p3 - ff_count)
    for c, pos in cand_pos_dic.items():
        indices = []
        for p in pos:
            i = fitness_index_dic[(c, p)]
            indices.append(i)
            # constraint
        z = sum([X[i] for i in indices])
        z.NAME = simplify_Objective(z.NAME, len(X))
        m.Equation(z == 1)

    if True:
        m.solve(disp=False)
        result = X.copy()
        result_list = [item.value[0] for item in result]

        G_output = G.copy()
        att_dic = nx.get_node_attributes(G_output, 'att')

        score = 0.0
        matched = []
        for i in range(len(result)):
            if result_list[i] == 1:
                (c, p) = candidate_pair_list[i]
                matched.append((c, p))
                score += float(fitness_dic[(c, p)])
                att_dic[p] = candidate_dic[c]

        nx.set_node_attributes(G_output, att_dic, 'att')
    return G_output, matched
예제 #24
0
def init_opt_solver(mrt, G, num_tasks, num_machines, w):
    """
    prepares the optimization equation by adding the necessary constraints
    :param mrt: Boolean variable that is True if objective is to optimize for 
                MRT + E, False if objective is to optimize Makespan + E.
    :param G: DAG to schedule
    :param num_tasks: total number of tasks
    :param w: weights
    :return: m, s, c
    """
    m = GEKKO()

    # Use IPOPT solver (default)
    m.options.SOLVER = 3

    # Change to parallel linear solver
    m.solver_options = ['minlp_max_iter_with_int_sol 10000']

    # create array
    s = m.Array(m.Var, num_tasks)
    for i in range(num_tasks):
        s[i].value = 2.0
        s[i].lower = 0

    # define completion time of each task
    c = m.Array(m.Var, num_tasks)
    for i in range(num_tasks):
        c[i].value = 0
        c[i].lower = 0

    x = [[m.sos1([0,1]) for j in range(num_tasks)] for i in range(num_machines)]

    #Yu's constraints that you can uncomment
    p = [[m.sos1([0,1]) for j in range(num_tasks)] for j_prime in range(num_tasks)] 
    b = [[m.sos1([0,1]) for j in range(num_tasks)] for j_prime in range(num_tasks)] 

    # 1a
    # each task will be assigned to exactly one machine
    for j in range(num_tasks):
        m.Equation(m.sum([x[i][j] for i in range(num_machines)]) == 1)

    # 1b
    # task's completion time must be later than the time to run task itself
    for j in range(num_tasks):
        m.Equation( w[j] / s[j]  <= c[j])

    # 1c
    # task must start later than all ancestors
    for j in range(num_tasks):
        for k in nx.algorithms.ancestors(G, j):
            m.Equation(c[k] + (w[j] / s[j]) <= c[j])

    M = m.Var(value=5, lb=0)
    P = m.Var(value=5, lb=0)
    MRT = m.Var(value=5, lb=0)

    # Yu's constraints that you can uncomment
    for j_prime in range(num_tasks):
        for j in range(num_tasks):
            if j != j_prime:
                m.Equation(m.sum([x[i][j] * x[i][j_prime] for i in range(num_machines)]) == p[j][j_prime])

    for j_prime in range(num_tasks):
        for j in range(num_tasks):
            if j != j_prime:
                m.Equation(p[j][j_prime] * (c[j] - c[j_prime] + (w[j_prime] / s[j_prime])) <= b[j][j_prime] * (
                            M - c[j_prime] + (w[j_prime] / s[j_prime])))
                m.Equation(b[j][j_prime] * (c[j_prime] + (w[j]/s[j])) <= p[j][j_prime] * c[j])
                m.Equation(b[j][j_prime] <= p[j][j_prime])
                b[j][j_prime] = m.if3(b[j_prime][j] - 1, 1, 0)


    # Total load assigned to each machine should not be greater than the makespan
    for i in range(num_machines):
        m.Equation(m.sum([w[j] * x[i][j] / s[j] for j in range(num_tasks)]) <= M)

    # 1e (define M in objective function)
    for j in range(num_tasks):
        m.Equation(c[j] <= M)

    # define P in objective function
    m.Equation(m.sum([w[j] * s[j] for j in range(num_tasks)]) == P)

    # define MRT
    m.Equation(m.sum([c[j] for j in range(num_tasks)]) == MRT)

    if mrt: 
        m.Obj(MRT + P)

    else:

        m.Obj(P + M) # Objective
   

    # Old Objective
    # m.Obj(sum([int(v[i]) / s[i] + s[i] for i in range(len(v))]))

    # objective for mean completion time
    
    return x, m, s, c
예제 #25
0
u_j1.DCOST = 0.0
u_j2 = m.MV(ub=0.7, lb=-0.7, fixed_initial=False)
u_j2.STATUS = 1
u_j2.DCOST = 0.0

# Setup state variables
sp_x = m.Var()
sp_y = m.Var()
j1_p = m.Var(lb=-2.89, ub=2.89)
j2_p = m.Var(lb=0.05, ub=3.0)
j1_v = m.Var(lb=-0.9, ub=0.9)
j2_v = m.Var(lb=-0.9, ub=0.9)
mb_v_x = m.Var(lb=-0.35, ub=0.35)
mb_v_y = m.Var(lb=-0.35, ub=0.35)
mb_v_th = m.Var(lb=-0.7, ub=0.7)
scn_x = m.Array(m.Var, n_scans)
scn_y = m.Array(m.Var, n_scans)
scn = [(scn_x[i], scn_y[i]) for i in range(len(scn_x))]

# Define functions for state and input processing
def proc_obs(obs):
    pos_sp = np.array([obs[2], -obs[1]])
    mb_vel = np.clip(obs[6:9], [-0.4, -0.4, -0.75], [0.4, 0.4, 0.75])
    linkpos = [0.5, 0, 0, 1.0, 0, 0]
    j_pos = np.clip([obs[45], -obs[46]], [-2.89, 0.05], [2.89, 3.0])
    j_vel = np.clip([obs[47], -obs[48]], [-1.0, -1.0], [1.0, 1.0])
    sc = obs[49:49+n_scans]
    angs = np.linspace(-np.pi, np.pi, n_scans)
    sc_xs, sc_ys = np.cos(angs)*sc, np.sin(angs)*sc
    scf = np.vstack((sc_xs, sc_ys)).T.reshape((-1,))
    op = np.concatenate((pos_sp, mb_vel, j_pos, j_vel, linkpos, scf))
예제 #26
0
# Variable and Equation Arrays
# x1=x0+p, p=1.2
# x2-1=x1+x0
# x2=x1**2

from gekko import GEKKO

# Initialize model
m = GEKKO()

# Define parameter
p = m.Param(1.2)

# Define array
x = m.Array(m.Var, 3)

# Equations
eq0 = x[1] == x[0] + p
eq1 = x[2] - 1 == x[1] + x[0]
eq2 = x[2] == x[1]**2
m.Equation([eq0, eq1, eq2])

# Solve simulation
m.solve()
#m.solve(disp=False)

# Results
for i in range(3):
    print(f"x[{i}]={x[i].value}")
예제 #27
0
h0 = 1000 * V0 / areas
Vout0 = c * np.sqrt(h0)
vin = [
    0.13, 0.13, 0.13, 0.21, 0.21, 0.21, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,
    0.13
]
Vin = [0, 0, 0, 0]

#Initialize model
m = GEKKO()

#time array
m.time = np.linspace(0, 1, 13)
#define constants
#ThunderSnow Constants exist
c = m.Array(m.Const, 4, value=0)
c[0].value = 0.03
c[1].value = c[0] / 2
c[2].value = c[0] * 2
c[3].value = 0
#python constants are equivilant to ThunderSnow constants
Vuse = [0.03, 0.05, 0.02, 0.00]

#Paramters
evap_c = m.Array(m.Param, 4, value=1e-5)
evap_c[-1].value = 0.5e-5

A = [m.Param(value=i) for i in areas]  #python list comprehension

Vin[0] = m.Param(value=vin)
예제 #28
0
def reservoirs():

    #Initial conditions
    c = np.array([0.03, 0.015, 0.06, 0])
    areas = np.array([13.4, 12, 384.5, 4400])
    V0 = np.array([0.26, 0.18, 0.68, 22])
    h0 = 1000 * V0 / areas
    Vout0 = c * np.sqrt(h0)
    vin = [
        0.13, 0.13, 0.13, 0.21, 0.21, 0.21, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,
        0.13
    ]
    Vin = [0, 0, 0, 0]

    #Initialize model
    m = GEKKO()

    #time array
    m.time = np.linspace(0, 1, 13)
    #define constants
    #ThunderSnow Constants exist
    c = m.Array(m.Const, 4, value=0)
    c[0].value = 0.03
    c[1].value = c[0] / 2
    c[2].value = c[0] * 2
    c[3].value = 0
    #python constants are equivilant to ThunderSnow constants
    Vuse = [0.03, 0.05, 0.02, 0.00]

    #Paramters
    evap_c = m.Array(m.Param, 4, value=1e-5)
    evap_c[-1].value = 0.5e-5

    A = [m.Param(value=i) for i in areas]  #python list comprehension

    Vin[0] = m.Param(value=vin)

    #Variables
    V = [m.Var(value=i) for i in V0]
    h = [m.Var(value=i) for i in h0]
    Vout = [m.Var(value=i) for i in Vout0]

    #Intermediates
    Vin[1:4] = [m.Intermediate(Vout[i]) for i in range(3)]
    Vevap = [m.Intermediate(evap_c[i] * A[i]) for i in range(4)]

    #Equations
    m.Equations(
        [V[i].dt() == Vin[i] - Vout[i] - Vevap[i] - Vuse[i] for i in range(4)])
    m.Equations([1000 * V[i] == h[i] * A[i] for i in range(4)])
    m.Equations([Vout[i]**2 == c[i]**2 * h[i] for i in range(4)])

    #Set to simulation mode
    m.options.imode = 4

    #Solve
    m.solve(disp=False)

    hvals = [h[i].value for i in range(4)]
    assert (test.like(
        hvals,
        [[
            19.40299, 19.20641, 19.01394, 19.31262, 19.60511, 19.89159,
            19.6849, 19.48247, 19.28424, 19.09014, 18.90011, 18.71408, 18.53199
        ],
         [
             15.0, 15.15939, 15.31216, 15.46995, 15.63249, 15.79955, 15.95968,
             16.11305, 16.25983, 16.40018, 16.53428, 16.66226, 16.7843
         ],
         [
             1.768531, 1.758775, 1.74913, 1.739597, 1.730178, 1.720873,
             1.71168, 1.702594, 1.693612, 1.684731, 1.675947, 1.667259,
             1.658662
         ],
         [
             5.0, 5.001073, 5.002143, 5.003208, 5.004269, 5.005326, 5.00638,
             5.007429, 5.008475, 5.009516, 5.010554, 5.011589, 5.012619
         ]]))
예제 #29
0
from gekko import GEKKO
m = GEKKO(remote=False)
x, y = m.Array(m.Var, 2)
m.Equation(y == m.sigmoid(x))
m.Minimize((y - 0.2)**2)
m.solve()
print(x.value[0], y.value[0])
예제 #30
0
state = {'x' : 0, 'y' : 1, 'z' : 2, 'roll' : 3, 'pitch' : 4, 'yaw': 5, \
    'dx' : 6, 'dy' : 7, 'dz' : 8, 'p' : 9, 'q' : 10, 'r' : 11}
# moment of inertia of the drone
J_x = 0.0224
J_y = 0.0224
J_z = 0.0436
c = 0.002167


#################################################################################################################
m = GEKKO()
# multiple options as one list
m.options.MAX_ITER = 10000
print("Defining State Matrix and Input Variable Matrix for Each Corridor and Time Scalar Variable")

X_list = [m.Array(m.Var, (int(Set_num_roots[i]) + 1,dim_state)) for i in range(num_corr)] 
U_list = [m.Array(m.Var, (int(Set_num_roots[i]),dim_input)) for i in range(num_corr)]
t_list = [m.Var(value = 0) for i in range(num_corr + 1)]

print("- Initialization and Setting boundaries for each Variable")

print("    1. State Matrix Variable")

for corr_idx in range(num_corr):
    num_collo = Set_num_roots[corr_idx] # the number of collocation in its corridor
    for row in range(num_collo + 1):
            # Setting corridor boundaries (x,y,z lower and upper)
            # x
            X_list[corr_idx][row, state['x']].lower = Set_Corridor[corr_idx][state['x'], 0]
            X_list[corr_idx][row, state['x']].upper = Set_Corridor[corr_idx][state['x'], 1]