Ejemplo n.º 1
0
def cost_state_old(s, state_considered, L, Q, gamma):
    """
    Asscoiate each state and its child transition a cost
    Assumption: paralleltopes
    """
    if s == s.goal:
        return 0
    model = Model("trajectory of polytopes")
    p = {}
    for row in range(s.n):
        p[row] = model.addVar(lb=-1, ub=1)
    model.update()
    GLG = np.dot(state_considered.G.T, np.dot(L, state_considered.G))
    theta = state_considered.successor[2]
    u = state_considered.successor[1]
    i = state_considered.mode
    theta_Q_theta = np.dot(theta.T, np.dot(Q, theta))
    J = QuadExpr()
    for row in range(s.n):
        for k in range(s.n):
            J.add(p[row] * p[k] * GLG[row, k] +
                  p[row] * p[k] * theta_Q_theta[row, k])
    model.setParam('OutputFlag', False)
    model.setObjective(J)
    model.optimize()
    return model.ObjVal + np.asscalar(
        np.dot(state_considered.x.T, np.dot(L, state_considered.x)) +
        np.dot(u.T, np.dot(Q, u)) + gamma)
Ejemplo n.º 2
0
def point_trajectory_given_modes_and_central_traj(x_traj,list_of_cells,goal,eps=0,scale=[]):
    """
    Description: 
        Point Trajectory Optimization with the ordered list of polytopes given
        This is a convex program as mode sequence is already given
        list_of_cells: each cell has the following attributes: A,B,c, and polytope(H,h)
    """
    model=Model("Fixed Mode Polytopic Trajectory")
    T=len(list_of_cells)
    n,m=list_of_cells[0].B.shape
    x=model.addVars(range(T+1),range(n),lb=-GRB.INFINITY,ub=GRB.INFINITY,name="x")
    u=model.addVars(range(T),range(m),lb=-GRB.INFINITY,ub=GRB.INFINITY,name="u")
    model.update()
    if len(scale)==0:
        scale=np.ones(x_traj[0].shape[0])    
    print "inside function epsilon is",eps
    for j in range(n):
        model.addConstr(x[0,j]<=x_traj[0][j]+eps*scale[j])
        model.addConstr(x[0,j]>=x_traj[0][j]-eps*scale[j])

    for t in range(T):
        cell=list_of_cells[t]
        A,B,c,_p=cell.A,cell.B,cell.c,cell.p
        for j in range(n):
            expr_x=LinExpr([(A[j,k],x[t,k]) for k in range(n)])
            expr_u=LinExpr([(B[j,k],u[t,k]) for k in range(m)])
            model.addConstr(x[t+1,j]==expr_x+expr_u+c[j,0])
        x_t=np.array([x[t,j] for j in range(n)]).reshape(n,1)
        u_t=np.array([u[t,j] for j in range(m)]).reshape(m,1)
        xu=np.vstack((x_t,u_t))
        subset_LP(model,xu,np.zeros((n+m,1)),Ball(1),_p)


    x_T=np.array([x[T,j] for j in range(n)]).reshape(n,1)
    z=zonotope(x_T,np.zeros((n,1)))
    subset_generic(model,z,goal)
    # Cost function
    J=QuadExpr()
    for t in range(T):
        for i in range(n):
            J.add(x[t,i]*x[t,i]-x[t,i]*x_traj[t][i])
    model.setObjective(J)
    model.write("polytopic_trajectory.lp")
    model.setParam('TimeLimit', 150)
    model.optimize()
    x_num,u_num={},{}
    for t in range(T+1):
        x_num[t]=np.array([[x[t,j].X] for j in range(n)])
    for t in range(T):
        u_num[t]=np.array([[u[t,i].X] for i in range(m) ])
    return (x_num,u_num)
Ejemplo n.º 3
0
def calcDieselCost(ini, dieselGeneratorsVars, dieselStatusVars):
    dieselObjExp = QuadExpr()
    for index in range(len(ini.timestamps)):
        dieselObjExp.add(
            dieselGeneratorsVars[index, 0] * dieselGeneratorsVars[index, 0] *
            ini.dieselQuadraticCof * ini.dieselFuelPrice * ini.stepsizeHour)
        dieselObjExp.add(dieselGeneratorsVars[index, 0] * ini.dieselLinearCof *
                         ini.dieselFuelPrice * ini.stepsizeHour)
        dieselObjExp.add(ini.dieselConstantCof *
                         (1 - dieselStatusVars[index, 0]) *
                         ini.dieselFuelPrice * ini.stepsizeHour)
        dieselObjExp.add(ini.startUpCost * dieselStatusVars[index, 1] /
                         ini.startUpTimestepNumber)
    return dieselObjExp
Ejemplo n.º 4
0
def anchor_point(polytope):
    """
        A point in H,h
    """
    model = Model("Polytope Sampling")
    n = polytope.H.shape[1]
    x = np.empty((n, 1), dtype="object")
    rho = np.empty((polytope.H.shape[0], 1), dtype="object")
    for row in range(n):
        x[row, 0] = model.addVar(lb=-GRB.INFINITY, ub=GRB.INFINITY)
    for row in range(polytope.H.shape[0]):
        rho[row, 0] = model.addVar(lb=0, ub=GRB.INFINITY)
    model.update()
    J = QuadExpr(0)
    for row in range(polytope.H.shape[0]):
        a = LinExpr()
        for column in range(polytope.H.shape[1]):
            a.add(polytope.H[row, column] * x[column, 0])
        model.addConstr(a + rho[row, 0] == polytope.h[row])
        J.add(rho[row, 0] * rho[row, 0])
    model.setParam('OutputFlag', False)
    model.setObjective(J)
    model.optimize()
    return valuation(x)
Ejemplo n.º 5
0
class BaseProblem:
    def __init__(self, index: int, scenario: float, probability: float,
                 cfg: Config):
        self.cfg = cfg

        self.probability = probability
        self.index = index
        self.scenario = scenario

        self.objective = QuadExpr()

        # model.ModelSense is minimization by default
        self.model = Model(f"base_problem_{self.index}")

        self.x_1 = self.model.addVar(ub=self.cfg.area, name="x_1")
        self.x_2 = self.model.addVar(ub=self.cfg.area, name="x_2")
        self.x_3 = self.model.addVar(ub=self.cfg.area, name="x_3")

        self.model.addConstr(self.x_1 + self.x_2 + self.x_3 <= self.cfg.area)

        self.objective.add(self.x_1 * self.cfg.wheat.plant_cost *
                           self.probability)
        self.objective.add(self.x_2 * self.cfg.corn.plant_cost *
                           self.probability)
        self.objective.add(self.x_3 * self.cfg.beet.plant_cost *
                           self.probability)

        self._corn_variables_constraint()
        self._wheat_variables_constraint()
        self._beet_variables_constraint()

    def _wheat_variables_constraint(self):
        y_11 = self.model.addVar(name=f"y_11_{self.index}")
        y_12 = self.model.addVar(name=f"y_12_{self.index}")

        self.objective.add(y_11 * self.cfg.wheat.buy_price * self.probability)
        self.objective.add(y_12 * -self.cfg.wheat.sell_price *
                           self.probability)

        self.model.addConstr(
            self.cfg.wheat.requirement <=
            self.x_1 * self.cfg.wheat.produce_rate *
            (1 + self.scenario) + y_11 - y_12,
            name="wheat_produce_constraint",
        )

    def _corn_variables_constraint(self):
        y_21 = self.model.addVar(name=f"y_21_{self.index}")
        y_22 = self.model.addVar(name=f"y_22_{self.index}")

        self.objective.add(y_21 * self.cfg.corn.buy_price * self.probability)
        self.objective.add(y_22 * -self.cfg.corn.sell_price * self.probability)

        self.model.addConstr(
            self.cfg.corn.requirement <=
            self.x_2 * self.cfg.corn.produce_rate *
            (1 + self.scenario) + y_21 - y_22,
            name="cron_produce_constraint",
        )

    def _beet_variables_constraint(self):
        y_32 = self.model.addVar(
            ub=self.cfg.beet.max_demand,
            name=f"y_32_{self.index}",
        )
        y_33 = self.model.addVar(name=f"y_33_{self.index}")

        self.objective.add(y_32 * -self.cfg.beet.sell_price_high *
                           self.probability)
        self.objective.add(y_33 * -self.cfg.beet.sell_price_low *
                           self.probability)

        self.model.addConstr(
            self.x_3 * self.cfg.beet.produce_rate *
            (1 + self.scenario) >= y_32 + y_33,
            name="beet_produce_constraint",
        )

    def solve(
        self,
        _lambda: typing.Tuple[float, float, float],
        rou: float,
        x_hat_1: float,
        x_hat_2: float,
        x_hat_3: float,
    ):
        obj = self.objective.copy(1)

        obj.add(_lambda[0] * self.x_1)
        obj.add(_lambda[1] * self.x_2)
        obj.add(_lambda[2] * self.x_3)
        obj.add(rou / 2 * (self.x_1 - x_hat_1) * (self.x_1 - x_hat_1))
        obj.add(rou / 2 * (self.x_2 - x_hat_2) * (self.x_2 - x_hat_2))
        obj.add(rou / 2 * (self.x_3 - x_hat_3) * (self.x_3 - x_hat_3))

        self.model.setObjective(obj)
        self.model.optimize()

        return (
            self.model.objVal,
            self.x_1.x,
            self.x_2.x,
            self.x_3.x,
        )
Ejemplo n.º 6
0
    def solve_problem(self, xs, mus, c, k):
        """Optimize via gurobi.

        Build and solve the constrained optimization problem at the basis
        of the fuzzy learning procedure using the gurobi API.

        :param xs: objects in training set.
        :type xs: iterable
        :param mus: membership values for the objects in `xs`.
        :type mus: iterable
        :param c: constant managing the trade-off in joint radius/error
          optimization.
        :type c: float
        :param k: kernel function to be used.
        :type k: :class:`mulearn.kernel.Kernel`
        :raises: ValueError if optimization fails or if gurobi is not installed
        :returns: list -- optimal values for the independent variables of the
          problem.
        """
        if not gurobi_ok:
            raise ValueError('gurobi not available')

        m = len(xs)

        with Env(empty=True) as env:
            env.setParam('OutputFlag', 0)
            env.start()
            with Model('mulearn', env=env) as model:
                model.setParam('OutputFlag', 0)
                model.setParam('TimeLimit', self.time_limit)

                for i in range(m):
                    if c < np.inf:
                        model.addVar(name=f'chi_{i}',
                                     lb=-c * (1 - mus[i]),
                                     ub=c * mus[i],
                                     vtype=GRB.CONTINUOUS)
                    else:
                        model.addVar(name=f'chi_{i}', vtype=GRB.CONTINUOUS)

                model.update()
                chis = model.getVars()

                if self.initial_values is not None:
                    for c, i in zip(chis, self.initial_values):
                        c.start = i

                obj = QuadExpr()

                for i, j in it.product(range(m), range(m)):
                    obj.add(chis[i] * chis[j], k.compute(xs[i], xs[j]))

                for i in range(m):
                    obj.add(-1 * chis[i] * k.compute(xs[i], xs[i]))

                if self.adjustment and self.adjustment != 'auto':
                    for i in range(m):
                        obj.add(self.adjustment * chis[i] * chis[i])

                model.setObjective(obj, GRB.MINIMIZE)

                constEqual = LinExpr()
                constEqual.add(sum(chis), 1.0)

                model.addConstr(constEqual, GRB.EQUAL, 1)

                try:
                    model.optimize()
                except GurobiError as e:
                    print(e.message)
                    if self.adjustment == 'auto':
                        s = e.message
                        a = float(s[s.find(' of ') + 4:s.find(' would')])
                        logger.warning('non-diagonal Gram matrix, '
                                       f'retrying with adjustment {a}')
                        for i in range(m):
                            obj.add(a * chis[i] * chis[i])
                        model.setObjective(obj, GRB.MINIMIZE)

                        model.optimize()
                    else:
                        raise e

                if model.Status != GRB.OPTIMAL:
                    raise ValueError('optimal solution not found!')

                return [ch.x for ch in chis]