예제 #1
0
    def get_best_libs_unlimited_ships(self,
                                      ind_libs_available,
                                      days_available,
                                      solverName="scip"):
        ind_books_available = set()
        for lib in ind_libs_available:
            books = self.lib_books_lists[lib]
            for book in books:
                ind_books_available.add(book)
        ind_books_available = np.array(list(ind_books_available))

        book_libs_lists_available = [[] for _ in range(self.num_books)]
        for lib in ind_libs_available:
            books = self.lib_books_lists[lib]
            for book in books:
                book_libs_lists_available[book].append(lib)

        self.model = pmo.block()

        self.model.books = pmo.variable_dict()
        for book in ind_books_available:
            self.model.books[book] = pmo.variable(lb=0, ub=1)

        self.model.libs = pmo.variable_dict()
        for lib in ind_libs_available:
            self.model.libs[lib] = pmo.variable(domain=pmo.Binary)

        self.model.max_libs_in_time = pmo.constraint_list()
        self.model.max_libs_in_time.append(
            pmo.constraint(
                sum([
                    self.model.libs[lib] * self.lib_days[lib]
                    for lib in ind_libs_available
                ]) <= days_available))

        self.model.use_books = pmo.constraint_list()
        for book in ind_books_available:
            libs = book_libs_lists_available[book]
            self.model.use_books.append(
                pmo.constraint(
                    self.model.books[book] <= sum(self.model.libs[lib]
                                                  for lib in libs)))

        self.model.objective = pmo.objective(sum(
            self.book_points[book] * self.model.books[book]
            for book in ind_books_available),
                                             sense=-1)

        solver = self.get_solver(solverName)
        solver_result = solver.solve(self.model)

        result = []
        for lib in ind_libs_available:
            if self.model.libs[lib] != 0:
                result.append(lib)
        return result
    def __init__(
        self,
        interval_set,
        params: dict,
    ):
        super().__init__()

        ## Setup
        self.id = params["name"]
        self.objective_terms = {}

        # Need to reference interval set in coupling method, either need to add it to class or pass it to function.
        self.interval_set = interval_set

        self.component_element_ids = params[
            "component_element_names"]  # resources or other collections

        ## Parameters
        self.import_limit = aml.parameter(
            params["import_limit"])  # assume positive
        self.export_limit = aml.parameter(params["export_limit"])

        ## Expressions/Variables
        # Should we define net_export as a variable and set equal later - allows to define upper and lower bounds here
        # or should it be an expression here, and we reconstruct constraints later whenever we add elements - i.e. the coupling aspect of the problem
        # It really depends on how the model is "constructed" - one option is to define everything as constructor functions that are called when the model is constructed, but order of construction matters here!
        # If we define as a variable, then we decouple them.
        self.net_export = aml.variable_dict()
        for interval in interval_set:
            self.net_export[interval] = aml.variable(lb=-self.import_limit,
                                                     ub=self.export_limit)
예제 #3
0
    def _generate_model(self):
        self.model = None
        self.model = pmo.block()
        model = self.model
        model._name = self.description

        model.s = list(range(1,13))
        model.x = pmo.variable_dict(
            (i, pmo.variable()) for i in model.s)
        model.x[1].lb = -1
        model.x[1].ub = 1
        model.x[2].lb = -1
        model.x[2].ub = 1
        model.obj = pmo.objective(sum(model.x[i]*((-1)**(i+1))
                                      for i in model.s))
        model.c = pmo.constraint_dict()
        # to make the variable used in the constraint match the name
        model.c[3] = pmo.constraint(model.x[3]>=-1.)
        model.c[4] = pmo.constraint(model.x[4]<=1.)
        model.c[5] = pmo.constraint(model.x[5]==-1.)
        model.c[6] = pmo.constraint(model.x[6]==-1.)
        model.c[7] = pmo.constraint(model.x[7]==1.)
        model.c[8] = pmo.constraint(model.x[8]==1.)
        model.c[9] = pmo.constraint((-1.,model.x[9],-1.))
        model.c[10] = pmo.constraint((-1.,model.x[10],-1.))
        model.c[11] = pmo.constraint((1.,model.x[11],1.))
        model.c[12] = pmo.constraint((1.,model.x[12],1.))

        model.c_inactive = pmo.constraint_dict()
        # to make the variable used in the constraint match the name
        model.c_inactive[3] = pmo.constraint(model.x[3]>=-2.)
        model.c_inactive[4] = pmo.constraint(model.x[4]<=2.)
예제 #4
0
    def _generate_model(self):
        self.model = None
        self.model = pmo.block()
        model = self.model
        model._name = self.description

        model.s = list(range(1, 13))
        model.x = pmo.variable_dict((i, pmo.variable()) for i in model.s)
        model.x[1].lb = -1
        model.x[1].ub = 1
        model.x[2].lb = -1
        model.x[2].ub = 1
        model.obj = pmo.objective(
            sum(model.x[i] * ((-1)**(i + 1)) for i in model.s))
        model.c = pmo.constraint_dict()
        # to make the variable used in the constraint match the name
        model.c[3] = pmo.constraint(model.x[3] >= -1.)
        model.c[4] = pmo.constraint(model.x[4] <= 1.)
        model.c[5] = pmo.constraint(model.x[5] == -1.)
        model.c[6] = pmo.constraint(model.x[6] == -1.)
        model.c[7] = pmo.constraint(model.x[7] == 1.)
        model.c[8] = pmo.constraint(model.x[8] == 1.)
        model.c[9] = pmo.constraint((-1., model.x[9], -1.))
        model.c[10] = pmo.constraint((-1., model.x[10], -1.))
        model.c[11] = pmo.constraint((1., model.x[11], 1.))
        model.c[12] = pmo.constraint((1., model.x[12], 1.))

        model.c_inactive = pmo.constraint_dict()
        # to make the variable used in the constraint match the name
        model.c_inactive[3] = pmo.constraint(model.x[3] >= -2.)
        model.c_inactive[4] = pmo.constraint(model.x[4] <= 2.)
예제 #5
0
    def _generate_model(self):
        self.model = pmo.block()
        model = self.model
        model._name = self.description

        model.f = pmo.variable()
        model.x = pmo.variable(lb=1,ub=3)
        model.fi = pmo.parameter_dict()
        model.fi[1] = pmo.parameter(value=1.0)
        model.fi[2] = pmo.parameter(value=2.0)
        model.fi[3] = pmo.parameter(value=0.0)
        model.xi = pmo.parameter_dict()
        model.xi[1] = pmo.parameter(value=1.0)
        model.xi[2] = pmo.parameter(value=2.0)
        model.xi[3] = pmo.parameter(value=3.0)
        model.p = pmo.variable(domain=NonNegativeReals)
        model.n = pmo.variable(domain=NonNegativeReals)
        model.lmbda = pmo.variable_dict(
            (i, pmo.variable()) for i in range(1,4))
        model.obj = pmo.objective(model.p+model.n)
        model.c1 = pmo.constraint_dict()
        model.c1[1] = pmo.constraint((0.0, model.lmbda[1], 1.0))
        model.c1[2] = pmo.constraint((0.0, model.lmbda[2], 1.0))
        model.c1[3] = pmo.constraint(0.0 <= model.lmbda[3])
        model.c2 = pmo.sos2(model.lmbda.values())
        model.c3 = pmo.constraint(sum(model.lmbda.values()) == 1)
        model.c4 = pmo.constraint(model.f==sum(model.fi[i]*model.lmbda[i]
                                               for i in model.lmbda))
        model.c5 = pmo.constraint(model.x==sum(model.xi[i]*model.lmbda[i]
                                               for i in model.lmbda))
        model.x.fix(2.75)

        # Make an empty SOS constraint
        model.c6 = pmo.sos2([])
예제 #6
0
        def _generate_base_model(self):

            self.model = pmo.block()
            model = self.model
            model._name = self.description

            model.s = list(range(1,13))
            model.x = pmo.variable_dict(
                ((i, pmo.variable()) for i in model.s))
            model.x[1].lb = -1
            model.x[1].ub = 1
            model.x[2].lb = -1
            model.x[2].ub = 1
            model.obj = pmo.objective(expr=sum(model.x[i]*((-1)**(i+1))
                                               for i in model.s))
            variable_order = [
                model.x[3],
                model.x[4],
                model.x[5],
                model.x[6],
                model.x[7],
                model.x[8],
                model.x[9],
                model.x[10],
                model.x[11],
                model.x[12]]

            return variable_order
예제 #7
0
파일: LP_compiled.py 프로젝트: Pyomo/pyomo
        def _generate_base_model(self):

            self.model = pmo.block()
            model = self.model
            model._name = self.description

            model.s = list(range(1,13))
            model.x = pmo.variable_dict(
                ((i, pmo.variable()) for i in model.s))
            model.x[1].lb = -1
            model.x[1].ub = 1
            model.x[2].lb = -1
            model.x[2].ub = 1
            model.obj = pmo.objective(expr=sum(model.x[i]*((-1)**(i+1))
                                               for i in model.s))
            variable_order = [
                model.x[3],
                model.x[4],
                model.x[5],
                model.x[6],
                model.x[7],
                model.x[8],
                model.x[9],
                model.x[10],
                model.x[11],
                model.x[12]]

            return variable_order
예제 #8
0
def build_unordered_variable_dict():
    """Build an unordered variable_dict with no references to external
    objects so its size can be computed."""
    return variable_dict(
        ((i, variable(domain_type=None, lb=None, ub=None, value=None))
         for i in range(N)),
        ordered=False)
예제 #9
0
    def __init__(self, V, W,
                 pyomo_solver="ipopt",
                 pyomo_solver_io="nl",
                 integer_tolerance=1e-4):
        assert V > 0
        assert integer_tolerance > 0
        self.V = V
        self.W = W
        self._integer_tolerance = integer_tolerance
        N = range(len(self.W))
        m = self.model = pmo.block()
        x = m.x = pmo.variable_dict()
        y = m.y = pmo.variable_dict()
        for i in N:
            y[i] = pmo.variable(domain=pmo.Binary)
            for j in N:
                x[i,j] = pmo.variable(domain=pmo.Binary)

        m.B = pmo.expression(sum(y.values()))
        m.objective = pmo.objective(m.B, sense=pmo.minimize)

        m.B_nontrivial = pmo.constraint(m.B >= 1)

        m.capacity = pmo.constraint_dict()
        for i in N:
            m.capacity[i] = pmo.constraint(
                sum(x[i,j]*self.W[j] for j in N) <= self.V*y[i])

        m.assign_1 = pmo.constraint_dict()
        for j in N:
            m.assign_1[j] = pmo.constraint(
                sum(x[i,j] for i in N) == 1)

        # relax everything for the bound solves,
        # since the objective uses a simple heuristic
        self.true_domain_type = pmo.ComponentMap()
        for xij in self.model.x.components():
            self.true_domain_type[xij] = xij.domain_type
            xij.domain_type = pmo.RealSet
        for yi in self.model.y.components():
            self.true_domain_type[yi] = yi.domain_type
            yi.domain_type = pmo.RealSet

        self.opt = pmo.SolverFactory(
            pyomo_solver,
            solver_io=pyomo_solver_io)
예제 #10
0
    def _generate_model(self):
        self.model = pmo.block()
        model = self.model
        model._name = self.description

        model.a = pmo.parameter(value=0.1)
        model.x = pmo.variable(domain=NonNegativeReals)
        model.y = pmo.variable_dict()
        model.y[1] = pmo.variable(domain=NonNegativeReals)
        model.y[2] = pmo.variable(domain=NonNegativeReals)

        model.obj = pmo.objective(model.x + model.y[1] + 2 * model.y[2])
        model.c1 = pmo.constraint(model.a <= model.y[2])
        model.c2 = pmo.constraint(2.0 <= model.x <= 10.0)
        model.c3 = pmo.sos1(model.y.values())
        model.c4 = pmo.constraint(sum(model.y.values()) == 1)

        # Make an empty SOS constraint
        model.c5 = pmo.sos1([])
예제 #11
0
파일: SOS1_simple.py 프로젝트: Pyomo/pyomo
    def _generate_model(self):
        self.model = pmo.block()
        model = self.model
        model._name = self.description

        model.a = pmo.parameter(value=0.1)
        model.x = pmo.variable(domain=NonNegativeReals)
        model.y = pmo.variable_dict()
        model.y[1] = pmo.variable(domain=NonNegativeReals)
        model.y[2] = pmo.variable(domain=NonNegativeReals)

        model.obj = pmo.objective(model.x + model.y[1]+2*model.y[2])
        model.c1 = pmo.constraint(model.a <= model.y[2])
        model.c2 = pmo.constraint((2.0, model.x, 10.0))
        model.c3 = pmo.sos1(model.y.values())
        model.c4 = pmo.constraint(sum(model.y.values()) == 1)

        # Make an empty SOS constraint
        model.c5 = pmo.sos1([])
예제 #12
0
    def get_optimal_ordering_and_books(self,
                                       ind_libs_available,
                                       days_available=None,
                                       book_points_available=None,
                                       solverName="scip"):
        if days_available is None:
            days_available = self.num_days
        if book_points_available is None:
            book_points_available = self.book_points
        ind_books_available = set()
        for lib in ind_libs_available:
            books = self.lib_books_lists[lib]
            for book in books:
                if book_points_available[book] != 0:
                    ind_books_available.add(book)
        ind_books_available = np.array(list(ind_books_available))

        book_libs_lists_available = [[] for _ in range(self.num_books)]
        for lib in ind_libs_available:
            books = self.lib_books_lists[lib]
            for book in books:
                book_libs_lists_available[book].append(lib)

        ind_index_available = np.arange(len(ind_libs_available))

        self.model = pmo.block()

        self.model.books = pmo.variable_dict()
        for book in ind_books_available:
            self.model.books[book] = pmo.variable(lb=0, ub=1)

        self.model.lib_books = pmo.variable_dict()
        for lib in ind_libs_available:
            for book in self.lib_books_lists[lib]:
                self.model.lib_books[lib, book] = pmo.variable(lb=0, ub=1)

        self.model.lib_index = pmo.variable_dict()
        for lib in ind_libs_available:
            for index in ind_index_available:
                self.model.lib_index[lib,
                                     index] = pmo.variable(domain=pmo.Binary)

        self.model.times_remaining = pmo.variable_dict()
        for time in ind_index_available:
            self.model.times_remaining[time] = pmo.variable(lb=0,
                                                            ub=self.num_days)

        self.model.lib_times_remaining = pmo.variable_dict()
        for lib in ind_libs_available:
            self.model.lib_times_remaining[lib] = pmo.variable(lb=0,
                                                               ub=2 *
                                                               self.num_days)

        self.model.every_book_once = pmo.constraint_list()
        for book in ind_books_available:
            libs = book_libs_lists_available[book]
            self.model.every_book_once.append(
                pmo.constraint(
                    sum(self.model.lib_books[lib, book] for lib in libs) <= 1))

        self.model.use_books = pmo.constraint_list()
        for book in ind_books_available:
            libs = book_libs_lists_available[book]
            self.model.use_books.append(
                pmo.constraint(self.model.books[book] <= sum(
                    self.model.lib_books[lib, book] for lib in libs)))

        self.model.one_place_per_lib = pmo.constraint_list()
        for lib in ind_libs_available:
            self.model.one_place_per_lib.append(
                pmo.constraint(
                    sum([
                        self.model.lib_index[lib, index]
                        for index in ind_index_available
                    ]) == 1))

        self.model.one_lib_per_place = pmo.constraint_list()
        for index in ind_index_available:
            self.model.one_lib_per_place.append(
                pmo.constraint(
                    sum([
                        self.model.lib_index[lib, index]
                        for lib in ind_libs_available
                    ]) == 1))

        self.model.use_libs = pmo.constraint_list()
        for lib in ind_libs_available:
            books = self.lib_books_lists[lib]
            for book in books:
                self.model.use_libs.append(
                    pmo.constraint(self.model.lib_books[lib, book] <= sum([
                        self.model.lib_index[lib, index]
                        for index in ind_index_available
                    ])))

        self.model.remaining_times = pmo.constraint_list()
        for time in ind_index_available:
            prev_time = self.model.times_remaining[
                time - 1] if time else days_available
            self.model.remaining_times.append(
                pmo.constraint(
                    self.model.times_remaining[time] == prev_time - sum([
                        self.model.lib_index[lib, time] * self.lib_days[lib]
                        for lib in ind_libs_available
                    ])))

        self.model.lib_remaining_times = pmo.constraint_list()
        for time in ind_index_available:
            for lib in ind_libs_available:
                self.model.lib_remaining_times.append(
                    pmo.constraint(
                        self.model.lib_times_remaining[lib] <=
                        self.model.times_remaining[time] + days_available *
                        (1 - self.model.lib_index[lib, time])))

        self.model.lib_max_num_books = pmo.constraint_list()
        for lib in ind_libs_available:
            books = self.lib_books_lists[lib]
            self.model.lib_max_num_books.append(
                pmo.constraint(
                    sum([self.model.lib_books[lib, book]
                         for book in books]) <= self.lib_ships[lib] *
                    self.model.lib_times_remaining[lib]))

        self.model.objective = pmo.objective(sum(
            book_points_available[book] * self.model.books[book]
            for book in ind_books_available),
                                             sense=-1)

        solver = self.get_solver(solverName)
        solver_result = solver.solve(self.model)

        result = []
        for index in range(len(ind_libs_available)):
            for lib in ind_libs_available:
                if self.model.lib_index.get((lib, index)) != 0:
                    books = self.lib_books_lists[lib]
                    result.append((lib, [
                        book for book in books
                        if self.model.lib_books.get((lib, book)) != 0
                    ]))

        return result
예제 #13
0
# Define the model
model = pmo.block()

# Create the sets
model.set_workers = range(NUM_WORKERS)
model.set_tasks = range(NUM_TASKS)

# Create the parameters
model.param_cost = pmo.parameter_dict()
for _worker in model.set_workers:
    for _task in model.set_tasks:
        model.param_cost[(_worker,
                          _task)] = pmo.parameter(costs[_worker][_task])

# Create the variables
model.var_group1 = pmo.variable_dict()
for _pair in range(5):
    model.var_group1[_pair] = pmo.variable(domain=pmo.Binary)

model.var_group2 = pmo.variable_dict()
for _pair in range(5):
    model.var_group2[_pair] = pmo.variable(domain=pmo.Binary)

model.var_group3 = pmo.variable_dict()
for _pair in range(5):
    model.var_group3[_pair] = pmo.variable(domain=pmo.Binary)

model.var_x = pmo.variable_dict()
for _worker in model.set_workers:
    for _task in model.set_tasks:
        model.var_x[(_worker, _task)] = pmo.variable(domain=pmo.Binary)
예제 #14
0
def build_variable_dict():
    """Build a variable_dict with no references to external
    objects so its size can be computed."""
    return variable_dict(
        ((i, variable(domain_type=None, lb=None, ub=None, value=None))
         for i in range(N)))
예제 #15
0
# Define the model
model = pmo.block()

# Create the sets
model.set_workers = range(NUM_WORKERS)
model.set_tasks = range(NUM_TASKS)

# Create the parameters
model.param_cost = pmo.parameter_dict()
for _worker in model.set_workers:
    for _task in model.set_tasks:
        model.param_cost[(_worker,
                          _task)] = pmo.parameter(costs[_worker][_task])

# Create the variables
model.var_x = pmo.variable_dict()
for _worker in model.set_workers:
    for _task in model.set_tasks:
        model.var_x[(_worker, _task)] = pmo.variable(domain=pmo.Binary)

# Create the constraints
## Each worker is assigned to at most 1 task
model.con_worker = pmo.constraint_list()
for _worker in model.set_workers:
    model.con_worker.append(
        pmo.constraint(
            sum(model.var_x[(_worker, _task)]
                for _task in model.set_tasks) <= 1))
## Each task is assigned to exactly 1 worker
model.con_task = pmo.constraint_list()
for _task in model.set_tasks:
예제 #16
0
    def create_optimization_model(self, config):

        self.logger.info('Creating optimization model.')

        # Consider using context managers

        # limit_sell = False

        # GET COMPONENTS FROM SYSTEM

        if self.system.has_battery:
            battery = self.system.get_battery_object()

        if self.system.has_external_grid:
            supply = self.system.get_external_grid_object()

        # STARTING MODEL

        m = pk.block()

        # Track the default attributes of the model to be aware of which the user adds.
        default_attributes = set(m.__dict__.keys())
        default_attributes.add('default_attributes')

        # SETS

        m.periods = range(config['periods'])
        m.E_set = []

        # VARIABLES

        m.E = pk.variable_dict()

        if self.system.has_stochastic_generators and not self.system.has_external_grid:
            m.E_set.append('stochastic')

            m.E['stochastic'] = pk.variable_list()
            for t in m.periods:
                m.E['stochastic'].append(
                    pk.variable(domain_type=pk.RealSet,
                                lb=0,
                                ub=self.system.stochastic_electrical_gen[t]))

        if self.system.has_external_grid:
            m.E_set.append('buy')
            m.E_set.append('sell')

            m.E['buy'] = pk.variable_list()
            for _ in m.periods:
                m.E['buy'].append(pk.variable(domain=pk.NonNegativeReals))

            m.E['sell'] = pk.variable_list()
            for _ in m.periods:
                m.E['sell'].append(pk.variable(domain=pk.NonNegativeReals))

            m.y_grid = pk.variable_list()
            for _ in m.periods:
                m.y_grid.append(
                    pk.variable(domain_type=pk.IntegerSet, lb=0, ub=1))

        if self.system.has_battery:
            m.E_set.append('batt_chrg')
            m.E_set.append('batt_dis')

            m.E['batt_chrg'] = pk.variable_list()
            for _ in m.periods:
                # The upper bound are impose in the constraints below
                m.E['batt_chrg'].append(
                    pk.variable(domain_type=pk.RealSet, lb=0))
            m.E['batt_dis'] = pk.variable_list()
            for _ in m.periods:
                m.E['batt_dis'].append(
                    pk.variable(domain_type=pk.RealSet, lb=0))

            m.y_bat = pk.variable_list()
            for _ in m.periods:
                m.y_bat.append(
                    pk.variable(domain_type=pk.IntegerSet, lb=0, ub=1))

            m.soc = pk.variable_list()
            for _ in m.periods:
                m.soc.append(
                    pk.variable(domain_type=pk.RealSet,
                                lb=battery.soc_lb,
                                ub=battery.soc_ub))
            # Extra soc variable for the last value of soc that should be >= soc_l
            m.soc.append(
                pk.variable(domain_type=pk.RealSet,
                            lb=battery.soc_l,
                            ub=battery.soc_ub))

        # PARAMETERS

        if self.system.has_external_grid:
            m.prices = {
                'buy': supply.electricity_purchase_prices.copy(),
                'sell': supply.electricity_selling_prices.copy(),
            }

        # OBJECTIVE FUNCTION

        obj_exp = 0
        obj_sense = pk.minimize

        if self.system.has_external_grid:
            obj_exp = quicksum((m.E['buy'][t] * m.prices['buy'][t] for t in m.periods), linear=True) \
                   - quicksum((m.E['sell'][t] * m.prices['sell'][t] for t in m.periods), linear=True)

        m.obj = pk.objective(obj_exp, sense=obj_sense)

        # CONSTRAINTS

        # Grid constraints

        # if limit_sell:
        #     m.c_limit_sell = pk.constraint(
        #             lb=0, body=system['selling_ratio']
        #             * sum(m.E['buy'][t] + system['E_pv'][t] for t in m.periods)
        #             - sum(m.E['sell'][t] for t in m.periods))

        grid_m = 1e5
        m.cl_y_buy = pk.constraint_list()
        for t in m.periods:
            m.cl_y_buy.append(
                pk.constraint(body=m.y_grid[t] * grid_m - m.E['buy'][t], lb=0))

        m.cl_y_sell = pk.constraint_list()
        for t in m.periods:
            m.cl_y_sell.append(
                pk.constraint(body=(1 - m.y_grid[t]) * grid_m - m.E['sell'][t],
                              lb=0))

        # Balance constraints

        energy_balance_exp = [0 for _ in m.periods]

        if self.system.has_fix_loads:
            for t in m.periods:
                energy_balance_exp[t] = -1 * self.system.fix_electrical_load[t]

        if self.system.has_external_grid:
            for t in m.periods:
                energy_balance_exp[
                    t] = energy_balance_exp[t] + m.E['buy'][t] - m.E['sell'][t]

        if self.system.has_battery:
            for t in m.periods:
                energy_balance_exp[t] = energy_balance_exp[t] + m.E[
                    'batt_dis'][t] - m.E['batt_chrg'][t]

        if self.system.has_stochastic_generators and not self.system.has_external_grid:
            for t in m.periods:
                energy_balance_exp[
                    t] = energy_balance_exp[t] + m.E['stochastic'][t]
        else:
            for t in m.periods:
                energy_balance_exp[t] = energy_balance_exp[
                    t] + self.system.stochastic_electrical_gen[t]

        m.cl_balance = pk.constraint_list()
        for t in m.periods:
            m.cl_balance.append(
                pk.constraint(body=energy_balance_exp[t], rhs=0))

        # Battery constraints and restrictions

        if self.system.has_battery:
            m.soc[0].fix(battery.soc_0)

            m.cl_soc = pk.constraint_list()
            for t in m.periods:
                m.cl_soc.append(
                    pk.constraint(
                        body=battery.batt_C * (m.soc[t + 1] - m.soc[t]) +
                        1 / battery.batt_dis_per * m.E['batt_dis'][t] -
                        battery.batt_chrg_per * m.E['batt_chrg'][t],
                        rhs=0))

            m.cl_y_char = pk.constraint_list()
            for t in m.periods:
                m.cl_y_char.append(
                    pk.constraint(body=m.y_bat[t] * battery.batt_chrg_speed -
                                  m.E['batt_chrg'][t],
                                  lb=0))

            m.cl_y_dis = pk.constraint_list()
            for t in m.periods:
                m.cl_y_char.append(
                    pk.constraint(
                        body=(1 - m.y_bat[t]) * battery.batt_dis_speed -
                        m.E['batt_dis'][t],
                        lb=0))

        # FINISHING

        # Determine the user defined attributes (written in this source code) by subtracting the defaults one.
        all_attributes = set(m.__dict__.keys())
        m.user_defined_attributes = list(all_attributes - default_attributes)

        self.optimization_model = m

        return m
예제 #17
0
    def get_optimal_books_for_ordered_libs(self,
                                           ind_libs_best,
                                           days_available=None,
                                           book_points_available=None,
                                           solverName="scip"):
        if days_available is None:
            days_available = self.num_days
        if book_points_available is None:
            book_points_available = self.book_points
        lib_num_books_available = np.zeros(self.num_libs, dtype=int)
        ind_libs_available = []
        for lib in ind_libs_best:
            days_available -= self.lib_days[lib]
            lib_num_books_available[lib] = days_available * self.lib_ships[lib]
        ind_libs_available = ind_libs_best

        ind_books_available = set()
        for lib in ind_libs_available:
            books = self.lib_books_lists[lib]
            for book in books:
                if book_points_available[book] != 0:
                    ind_books_available.add(book)
        ind_books_available = np.array(list(ind_books_available))

        book_libs_lists_available = [[] for _ in range(self.num_books)]
        for lib in ind_libs_available:
            books = self.lib_books_lists[lib]
            for book in books:
                book_libs_lists_available[book].append(lib)

        self.model = pmo.block()

        self.model.books = pmo.variable_dict()
        for book in ind_books_available:
            self.model.books[book] = pmo.variable(lb=0, ub=1)

        self.model.lib_books = pmo.variable_dict()
        for lib in ind_libs_available:
            for book in self.lib_books_lists[lib]:
                self.model.lib_books[lib,
                                     book] = pmo.variable(domain=pmo.Binary)

        self.model.every_book_once = pmo.constraint_list()
        for book in ind_books_available:
            libs = book_libs_lists_available[book]
            self.model.every_book_once.append(
                pmo.constraint(
                    sum(self.model.lib_books[lib, book] for lib in libs) <= 1))

        self.model.use_books = pmo.constraint_list()
        for book in ind_books_available:
            libs = book_libs_lists_available[book]
            self.model.use_books.append(
                pmo.constraint(self.model.books[book] <= sum(
                    self.model.lib_books[lib, book] for lib in libs)))

        self.model.max_books_per_lib = pmo.constraint_list()
        for lib in ind_libs_available:
            books = self.lib_books_lists[lib]
            num_books = lib_num_books_available[lib]
            self.model.max_books_per_lib.append(
                pmo.constraint(
                    sum(self.model.lib_books[lib, book]
                        for book in books) <= num_books))

        self.model.objective = pmo.objective(sum(
            book_points_available[book] * self.model.books[book]
            for book in ind_books_available),
                                             sense=-1)

        solver = self.get_solver(solverName)
        solver_result = solver.solve(self.model)

        # Can be used to see solver results
        # print(solver_result)

        result = []
        for lib in ind_libs_available:
            books = self.lib_books_lists[lib]
            result.append((lib, [
                book for book in books
                if self.model.lib_books.get((lib, book)) != 0
            ]))

        return result
예제 #18
0
    m.pd[i] = pmo.parameter(k)

# @Parameters_dict
# @Parameters_list
# uses 0-based indexing
# pl[0] = 0, pl[0] = 1, ...
m.pl = pmo.parameter_list()
for j in m.q:
    m.pl.append(pmo.parameter(j))
# @Parameters_list

# @Variables_single
m.v = pmo.variable(value=1, lb=1, ub=4)
# @Variables_single
# @Variables_dict
m.vd = pmo.variable_dict()
for i in m.s:
    m.vd[i] = pmo.variable(ub=9)
# @Variables_dict
# @Variables_list
# used 0-based indexing
m.vl = pmo.variable_list()
for j in m.q:
    m.vl.append(pmo.variable(lb=i))

# @Variables_list

# @Constraints_single
m.c = pmo.constraint(sum(m.vd.values()) <= 9)
# @Constraints_single
# @Constraints_dict
예제 #19
0
파일: blocks.py 프로젝트: pazochoa/pyomo
b = pmo.block()
b.x = pmo.variable()
b.c = pmo.constraint(expr=b.x >= 1)
b.o = pmo.objective(expr=b.x)

# define an optimization model with indexed containers
b = pmo.block()

b.p = pmo.parameter()
b.plist = pmo.parameter_list(pmo.parameter() for i in range(10))
b.pdict = pmo.parameter_dict(
    ((i, j), pmo.parameter()) for i in range(10) for j in range(10))

b.x = pmo.variable()
b.xlist = pmo.variable_list(pmo.variable() for i in range(10))
b.xdict = pmo.variable_dict(
    ((i, j), pmo.variable()) for i in range(10) for j in range(10))

b.c = pmo.constraint(b.x >= 1)
b.clist = pmo.constraint_list(
    pmo.constraint(b.xlist[i] >= i) for i in range(10))
b.cdict = pmo.constraint_dict(((i, j), pmo.constraint(b.xdict[i, j] >= i * j))
                              for i in range(10) for j in range(10))

b.o = pmo.objective(b.x + sum(b.xlist) + sum(b.xdict.values()))

#
# Define a custom tiny_block
#


# The tiny_block class uses more efficient storage for the
예제 #20
0
vl = pmo.variable_list(pmo.variable() for i in range(10))

cl = pmo.constraint_list()
for i in range(10):
    cl.append(pmo.constraint(vl[-1] == 1))

cl.insert(0, pmo.constraint(vl[0]**2 >= 1))

del cl[0]

#
# Dict containers
#

# uses OrderedDict when ordered=True
vd = pmo.variable_dict(((str(i), pmo.variable()) for i in range(10)),
                       ordered=True)

cd = pmo.constraint_dict((i, pmo.constraint(v == 1)) for i, v in vd.items())

cd = pmo.constraint_dict()
for i, v in vd.items():
    cd[i] = pmo.constraint(v == 1)

cd = pmo.constraint_dict()
cd.update((i, pmo.constraint()) for i, v in vd.items())

cd[None] = pmo.constraint()

del cd[None]

#
예제 #21
0
파일: containers.py 프로젝트: Pyomo/pyomo
vl = pmo.variable_list(
    pmo.variable() for i in range(10))

cl = pmo.constraint_list()
for i in range(10):
    cl.append(pmo.constraint(vl[-1] == 1))

cl.insert(0, pmo.constraint(vl[0]**2 >= 1))

del cl[0]

#
# Dict containers
#

vd = pmo.variable_dict(
    ((str(i), pmo.variable()) for i in range(10)))

cd = pmo.constraint_dict(
    (i, pmo.constraint(v == 1)) for i,v in vd.items())

cd = pmo.constraint_dict()
for i, v in vd.items():
    cd[i] = pmo.constraint(v == 1)

cd = pmo.constraint_dict()
cd.update((i, pmo.constraint()) for i,v in vd.items())

cd[None] = pmo.constraint()

del cd[None]
예제 #22
0
vl = pmo.variable_list(pmo.variable() for i in range(10))

cl = pmo.constraint_list()
for i in range(10):
    cl.append(pmo.constraint(vl[-1] == 1))

cl.insert(0, pmo.constraint(vl[0]**2 >= 1))

del cl[0]

#
# Dict containers
#

vd = pmo.variable_dict(((str(i), pmo.variable()) for i in range(10)))

cd = pmo.constraint_dict((i, pmo.constraint(v == 1)) for i, v in vd.items())

cd = pmo.constraint_dict()
for i, v in vd.items():
    cd[i] = pmo.constraint(v == 1)

cd = pmo.constraint_dict()
cd.update((i, pmo.constraint()) for i, v in vd.items())

cd[None] = pmo.constraint()

del cd[None]

#
예제 #23
0
    def get_optimal_ordering_and_books_for_subsection(self,
                                                      ind_libs_available,
                                                      lo,
                                                      hi,
                                                      solverName="scip"):
        days_available = self.num_days
        book_points_available = self.book_points
        ind_books_available = set()
        for lib in ind_libs_available:
            books = self.lib_books_lists[lib]
            for book in books:
                if book_points_available[book] != 0:
                    ind_books_available.add(book)
        ind_books_available = np.array(list(ind_books_available))

        book_libs_lists_available = [[] for _ in range(self.num_books)]
        for lib in ind_libs_available:
            books = self.lib_books_lists[lib]
            for book in books:
                book_libs_lists_available[book].append(lib)

        ind_index_available = np.arange(hi - lo)
        ind_libs_available_reorder = ind_libs_available[lo:hi]
        days_available_reorder = days_available - self.lib_days[
            ind_libs_available[:lo]].sum()

        lib_num_books_available = np.zeros(self.num_libs, dtype=int)
        days_remaining = days_available
        for lib in ind_libs_available:
            days_remaining -= self.lib_days[lib]
            lib_num_books_available[lib] = days_remaining * self.lib_ships[lib]

        self.model = pmo.block()

        self.model.books = pmo.variable_dict()
        for book in ind_books_available:
            self.model.books[book] = pmo.variable(lb=0, ub=1)

        self.model.lib_books = pmo.variable_dict()
        for lib in ind_libs_available:
            for book in self.lib_books_lists[lib]:
                self.model.lib_books[lib, book] = pmo.variable(lb=0, ub=1)

        self.model.lib_index = pmo.variable_dict()
        for lib in ind_libs_available_reorder:
            for index in ind_index_available:
                self.model.lib_index[lib,
                                     index] = pmo.variable(domain=pmo.Binary)

        self.model.times_remaining = pmo.variable_dict()
        for time in ind_index_available:
            self.model.times_remaining[time] = pmo.variable(lb=0,
                                                            ub=self.num_days)

        self.model.lib_times_remaining = pmo.variable_dict()
        for lib in ind_libs_available_reorder:
            self.model.lib_times_remaining[lib] = pmo.variable(lb=0,
                                                               ub=2 *
                                                               self.num_days)

        self.model.every_book_once = pmo.constraint_list()
        for book in ind_books_available:
            libs = book_libs_lists_available[book]
            self.model.every_book_once.append(
                pmo.constraint(
                    sum(self.model.lib_books[lib, book] for lib in libs) <= 1))

        self.model.use_books = pmo.constraint_list()
        for book in ind_books_available:
            libs = book_libs_lists_available[book]
            self.model.use_books.append(
                pmo.constraint(self.model.books[book] <= sum(
                    self.model.lib_books[lib, book] for lib in libs)))

        self.model.one_place_per_lib = pmo.constraint_list()
        for lib in ind_libs_available_reorder:
            self.model.one_place_per_lib.append(
                pmo.constraint(
                    sum([
                        self.model.lib_index[lib, index]
                        for index in ind_index_available
                    ]) == 1))

        self.model.one_lib_per_place = pmo.constraint_list()
        for index in ind_index_available:
            self.model.one_lib_per_place.append(
                pmo.constraint(
                    sum([
                        self.model.lib_index[lib, index]
                        for lib in ind_libs_available_reorder
                    ]) == 1))

        self.model.use_libs = pmo.constraint_list()
        for lib in ind_libs_available_reorder:
            books = self.lib_books_lists[lib]
            for book in books:
                self.model.use_libs.append(
                    pmo.constraint(self.model.lib_books[lib, book] <= sum([
                        self.model.lib_index[lib, index]
                        for index in ind_index_available
                    ])))

        self.model.remaining_times = pmo.constraint_list()
        for time in ind_index_available:
            prev_time = self.model.times_remaining[
                time - 1] if time else days_available_reorder
            self.model.remaining_times.append(
                pmo.constraint(
                    self.model.times_remaining[time] == prev_time - sum([
                        self.model.lib_index[lib, time] * self.lib_days[lib]
                        for lib in ind_libs_available_reorder
                    ])))

        self.model.lib_remaining_times = pmo.constraint_list()
        for time in ind_index_available:
            for lib in ind_libs_available_reorder:
                self.model.lib_remaining_times.append(
                    pmo.constraint(
                        self.model.lib_times_remaining[lib] <=
                        self.model.times_remaining[time] + days_available *
                        (1 - self.model.lib_index[lib, time])))

        self.model.lib_max_num_books = pmo.constraint_list()
        for lib in ind_libs_available_reorder:
            books = self.lib_books_lists[lib]
            self.model.lib_max_num_books.append(
                pmo.constraint(
                    sum([self.model.lib_books[lib, book]
                         for book in books]) <= self.lib_ships[lib] *
                    self.model.lib_times_remaining[lib]))

        self.model.max_books_per_lib = pmo.constraint_list()
        for lib in ind_libs_available:
            if not lib in list(ind_libs_available_reorder):
                books = self.lib_books_lists[lib]
                num_books = lib_num_books_available[lib]
                self.model.max_books_per_lib.append(
                    pmo.constraint(
                        sum(self.model.lib_books[lib, book]
                            for book in books) <= num_books))

        self.model.objective = pmo.objective(sum(
            book_points_available[book] * self.model.books[book]
            for book in ind_books_available),
                                             sense=-1)

        solver = self.get_solver(solverName)
        solver_result = solver.solve(self.model)

        # Can be used to see solver results
        # print(solver_result)

        result = []

        for lib in ind_libs_available[:lo]:
            books = self.lib_books_lists[lib]
            result.append((lib, [
                book for book in books
                if self.model.lib_books.get((lib, book)) != 0
            ]))

        for index in ind_index_available:
            for lib in ind_libs_available_reorder:
                if self.model.lib_index.get((lib, index)) != 0:
                    books = self.lib_books_lists[lib]
                    result.append((lib, [
                        book for book in books
                        if self.model.lib_books.get((lib, book)) != 0
                    ]))

        for lib in ind_libs_available[hi:]:
            books = self.lib_books_lists[lib]
            result.append((lib, [
                book for book in books
                if self.model.lib_books.get((lib, book)) != 0
            ]))

        return result
예제 #24
0
    def _generate_model(self):
        self.model = None
        self.model = pmo.block()
        model = self.model
        model._name = self.description

        model.s = [1,2]
        model.x_unused = pmo.variable()
        model.x_unused.stale = False

        model.x_unused_initialy_stale = pmo.variable()
        model.x_unused_initialy_stale.stale = True

        model.X_unused = pmo.variable_dict(
            (i, pmo.variable()) for i in model.s)
        model.X_unused_initialy_stale = pmo.variable_dict(
            (i, pmo.variable()) for i in model.s)

        for i in model.X_unused:
            model.X_unused[i].stale = False
            model.X_unused_initialy_stale[i].stale = True

        model.x = pmo.variable()
        model.x.stale = False

        model.x_initialy_stale = pmo.variable()
        model.x_initialy_stale.stale = True

        model.X = pmo.variable_dict(
            (i, pmo.variable()) for i in model.s)
        model.X_initialy_stale = pmo.variable_dict(
            (i, pmo.variable()) for i in model.s)
        for i in model.X:
            model.X[i].stale = False
            model.X_initialy_stale[i].stale = True

        model.obj = pmo.objective(model.x + \
                                  model.x_initialy_stale + \
                                  sum(model.X.values()) + \
                                  sum(model.X_initialy_stale.values()))

        model.c = pmo.constraint_dict()
        model.c[1] = pmo.constraint(model.x          >= 1)
        model.c[2] = pmo.constraint(model.x_initialy_stale    >= 1)
        model.c[3] = pmo.constraint(model.X[1]       >= 0)
        model.c[4] = pmo.constraint(model.X[2]       >= 1)
        model.c[5] = pmo.constraint(model.X_initialy_stale[1] >= 0)
        model.c[6] = pmo.constraint(model.X_initialy_stale[2] >= 1)

        # Test that stale flags do not get updated
        # on inactive blocks (where "inactive blocks" mean blocks
        # that do NOT follow a path of all active parent blocks
        # up to the top-level model)
        flat_model = model.clone()
        model.b = pmo.block()
        model.B = pmo.block_dict()
        model.B[1] = pmo.block()
        model.B[2] = pmo.block()
        model.b.b = flat_model.clone()
        model.B[1].b = flat_model.clone()
        model.B[2].b = flat_model.clone()

        model.b.deactivate()
        model.B.deactivate(shallow=False)
        model.b.b.activate()
        model.B[1].b.activate()
        model.B[2].b.deactivate()
        assert model.b.active is False
        assert model.B[1].active is False
        assert model.B[1].active is False
        assert model.b.b.active is True
        assert model.B[1].b.active is True
        assert model.B[2].b.active is False
capacities = 850

model = pmo.block()

# Create the sets
model.set_labels = range(len(values))

# Create the parameters
model.param_label_value = pmo.parameter_dict()
model.param_label_weight = pmo.parameter_dict()
for i in model.set_labels:
    model.param_label_value[i] = pmo.parameter(values[i])
    model.param_label_weight[i] = pmo.parameter(weights[i])

# Create the variables
model.var_pack = pmo.variable_dict()
for i in model.set_labels:
    model.var_pack[i] = pmo.variable(domain=pmo.Binary)

# Create the constraints
model.con_capacity = pmo.constraint(sum(model.var_pack[i] * weights[i] for i in model.set_labels) <= capacities)

# Create the objective
model.obj = pmo.objective(sum(model.var_pack[i] * values[i] for i in model.set_labels), sense=pmo.maximize)

# Solve
opt = pmo.SolverFactory('cplex')
result = opt.solve(model, tee=True)

# Print the solution
packed_items = []
    def __init__(
        self,
        interval_set,
        params: dict,
    ):
        super().__init__()

        ## Setup
        # self.id = uuid4()
        self.id = params["name"]
        self.objective_terms = {}

        ## Parameters
        self.maxMW = aml.parameter(params["maxMW"])
        self.minMW = aml.parameter(params["minMW"])
        self.max_ramp = aml.parameter(params["max_ramp"])
        self.marginal_cost = aml.parameter(params["marginal_cost"])
        self.initial_commit = aml.parameter(params["initial_commit"])

        ## Variables
        self.output = aml.variable_dict()
        for interval in interval_set:
            self.output[interval] = aml.variable(lb=0, ub=self.maxMW)

        self.commit = aml.variable_dict()
        for interval in interval_set:
            self.commit[interval] = aml.variable(domain=aml.Binary)

        ## Expressions - this is where we define a common interface for model resource elements
        # Note in Optopy we have to have a generic and dynamic common interface for market products, different time indices, etc.
        # Will just use net_export as an interface for now
        self.net_export = aml.expression_dict()
        for interval in interval_set:
            self.net_export[interval] = aml.expression(expr=self.output)

        ## Constraints
        # Can express constraints abstractly (lhs, rhs, body, ub, lb, etc.) or with interpreted syntax - see below
        self.con_output_commit_upper_bound = aml.constraint_dict()
        for interval in interval_set:
            # body_expr = self.output[interval] - self.commit[interval] * self.maxMW
            # self.con_output_commit_upper_bound[interval] = aml.constraint(body=body_expr, ub=0)

            self.con_output_commit_upper_bound[interval] = aml.constraint(
                self.output[interval] -
                self.commit[interval] * self.maxMW <= 0)

        self.con_output_commit_lower_bound = aml.constraint_dict()
        for interval in interval_set:
            # body_expr =  self.commit[interval] * self.minMW - self.output[interval]
            # self.con_output_commit_lower_bound[interval] = aml.constraint(body=body_expr, ub=0)

            self.con_output_commit_lower_bound[interval] = aml.constraint(
                self.commit[interval] * self.minMW -
                self.output[interval] <= 0)

        # todo Add constraints/costs for ramping, min up, min down, startup/shutdown costs, etc.

        ## Objective Terms
        # Unclear whether this expression object needs to be added to block/model - may be enough just to have it in the objective
        self.interval_cost = aml.expression_dict()
        for interval in interval_set:
            self.interval_cost[interval] = aml.expression(
                self.marginal_cost * self.output[interval])
        self.objective_terms["total_cost"] = sum(self.interval_cost[interval]
                                                 for interval in interval_set)
예제 #27
0
    def _generate_model(self):
        self.model = pmo.block()
        model = self.model
        model._name = self.description

        model.s = [1, 2]

        model.x_unused = pmo.variable(domain=pmo.IntegerSet)
        model.x_unused.stale = False

        model.x_unused_initialy_stale = pmo.variable(domain=pmo.IntegerSet)
        model.x_unused_initialy_stale.stale = True

        model.X_unused = pmo.variable_dict(
            (i, pmo.variable(domain=pmo.IntegerSet)) for i in model.s)
        model.X_unused_initialy_stale = pmo.variable_dict(
            (i, pmo.variable(domain=pmo.IntegerSet)) for i in model.s)
        for i in model.s:
            model.X_unused[i].stale = False
            model.X_unused_initialy_stale[i].stale = True

        model.x = pmo.variable(domain=RangeSet(None, None))
        model.x.stale = False

        model.x_initialy_stale = pmo.variable(domain=pmo.IntegerSet)
        model.x_initialy_stale.stale = True

        model.X = pmo.variable_dict(
            (i, pmo.variable(domain=pmo.IntegerSet)) for i in model.s)
        model.X_initialy_stale = pmo.variable_dict(
            (i, pmo.variable(domain=pmo.IntegerSet)) for i in model.s)
        for i in model.s:
            model.X[i].stale = False
            model.X_initialy_stale[i].stale = True

        model.obj = pmo.objective(model.x + \
                                  model.x_initialy_stale + \
                                  sum(model.X.values()) + \
                                  sum(model.X_initialy_stale.values()))

        model.c = pmo.constraint_dict()
        model.c[1] = pmo.constraint(model.x >= 1)
        model.c[2] = pmo.constraint(model.x_initialy_stale >= 1)
        model.c[3] = pmo.constraint(model.X[1] >= 0)
        model.c[4] = pmo.constraint(model.X[2] >= 1)
        model.c[5] = pmo.constraint(model.X_initialy_stale[1] >= 0)
        model.c[6] = pmo.constraint(model.X_initialy_stale[2] >= 1)

        # Test that stale flags do not get updated
        # on inactive blocks (where "inactive blocks" mean blocks
        # that do NOT follow a path of all active parent blocks
        # up to the top-level model)
        flat_model = model.clone()
        model.b = pmo.block()
        model.B = pmo.block_dict()
        model.b.b = flat_model.clone()
        model.B[1] = pmo.block()
        model.B[1].b = flat_model.clone()
        model.B[2] = pmo.block()
        model.B[2].b = flat_model.clone()

        model.b.deactivate()
        model.B.deactivate(shallow=False)
        model.b.b.activate()
        model.B[1].b.activate()
        model.B[2].b.deactivate()
        assert model.b.active is False
        assert model.B[1].active is False
        assert model.B[1].active is False
        assert model.b.b.active is True
        assert model.B[1].b.active is True
        assert model.B[2].b.active is False
예제 #28
0
# pl[0] = 0, pl[0] = 1, ...
m.pl = pmo.parameter_list()
for j in m.q:
    m.pl.append(
        pmo.parameter(j))
# @Parameters_list



# @Variables_single
m.v = pmo.variable(value=1,
                   lb=1,
                   ub=4)
# @Variables_single
# @Variables_dict
m.vd = pmo.variable_dict()
for i in m.s:
    m.vd[i] = pmo.variable(ub=9)
# @Variables_dict
# @Variables_list
# used 0-based indexing
m.vl = pmo.variable_list()
for j in m.q:
    m.vl.append(
        pmo.variable(lb=i))

# @Variables_list



# @Constraints_single