How to use docplex - 10 common examples

To help you get started, we’ve selected a few docplex examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Qiskit / qiskit-aqua / test / aqua / test_docplex.py View on Github external
def test_validation(self):
        """ Validation Test """
        num_var = 3
        # validate an object type of the input.
        with self.assertRaises(AquaError):
            docplex._validate_input_model("Model")

        # validate the types of the variables are binary or not
        with self.assertRaises(AquaError):
            mdl = Model(name='Error_integer_variables')
            x = {i: mdl.integer_var(name='x_{0}'.format(i)) for i in range(num_var)}
            obj_func = mdl.sum(x[i] for i in range(num_var))
            mdl.maximize(obj_func)
            docplex.get_qubitops(mdl)

        # validate types of constraints are equality constraints or not.
        with self.assertRaises(AquaError):
            mdl = Model(name='Error_inequality_constraints')
            x = {i: mdl.binary_var(name='x_{0}'.format(i)) for i in range(num_var)}
            obj_func = mdl.sum(x[i] for i in range(num_var))
            mdl.maximize(obj_func)
            mdl.add_constraint(mdl.sum(x[i] for i in range(num_var)) <= 1)
            docplex.get_qubitops(mdl)
github Qiskit / qiskit-aqua / test / aqua / test_docplex.py View on Github external
def test_docplex_integer_constraints(self):
        """ Docplex Integer Constraints test """
        # Create an Ising Homiltonian with docplex
        mdl = Model(name='integer_constraints')
        x = {i: mdl.binary_var(name='x_{0}'.format(i)) for i in range(1, 5)}
        max_vars_func = mdl.sum(x[i] for i in range(1, 5))
        mdl.maximize(max_vars_func)
        mdl.add_constraint(mdl.sum(i * x[i] for i in range(1, 5)) == 3)
        qubit_op, offset = docplex.get_qubitops(mdl)

        e_e = ExactEigensolver(qubit_op, k=1)
        result = e_e.run()

        expected_result = -2

        # Compare objective
        self.assertEqual(result['energy'] + offset, expected_result)
github Qiskit / qiskit-aqua / test / aqua / test_docplex.py View on Github external
def test_docplex_constant_and_quadratic_terms_in_object_function(self):
        """ Docplex Constant and Quadratic terms in Object function test """
        # Create an Ising Homiltonian with docplex
        laplacian = np.array([[-3., 1., 1., 1.],
                              [1., -2., 1., -0.],
                              [1., 1., -3., 1.],
                              [1., -0., 1., -2.]])

        mdl = Model()
        n = laplacian.shape[0]
        bias = [0] * 4
        x = {i: mdl.binary_var(name='x_{0}'.format(i)) for i in range(n)}
        couplers_func = mdl.sum(
            2 * laplacian[i, j] * (2 * x[i] - 1) * (2 * x[j] - 1)
            for i in range(n - 1) for j in range(i, n))
        bias_func = mdl.sum(float(bias[i]) * x[i] for i in range(n))
        ising_func = couplers_func + bias_func
        mdl.minimize(ising_func)
        qubit_op, offset = docplex.get_qubitops(mdl)

        e_e = ExactEigensolver(qubit_op, k=1)
        result = e_e.run()

        expected_result = -22
github ekhoda / optimization-tutorial / optimization_model_docplex.py View on Github external
"""
        If CPLEX is installed locally, we can use that to solve the problem.
        Otherwise, we can use DOcplexcloud. For docloud solve, we need valid 'url' and 'key'.
        Note, that if 'url' and 'key' parameters are present,
        the solve will be started on DOcplexcloud even if CPLEX is available.
            e.g. this forces the solve on DOcplexcloud:
            model.solve(url='https://foo.com', key='bar')

        Using 'docplex.mp.context.Context', it is possible to control how to solve.
        """

        if model_params['write_lp']:
            logger.info('Writing the lp file!')
            self.model.export_as_lp('./{}.lp'.format(self.model.name))

        ctx = Context()
        ctx.solver.docloud.url = model_params['url']
        ctx.solver.docloud.key = model_params['api_key']
        agent = 'docloud' if model_params['cplex_cloud'] else 'local'

        # There are several ways to set the parameters. Here are two ways:
        # method 1:
        if model_params['mip_gap']:
            self.model.parameters.mip.tolerances.mipgap = model_params['mip_gap']
        if model_params['time_limit']:
            self.model.set_time_limit(model_params['time_limit'])

        # # method 2:
        # cplex_parameters = {'mip.tolerances.mipgap': model_params['mip_gap'],
        #                     'timelimit': model_params['time_limit']}
        # ctx.update(cplex_parameters, create_missing_nodes=True)
github kosticlab / aether / lp / ilp.py View on Github external
avoid_names = map(lambda x: x[0],avoidp)
    serversp = zip(names,max_cost_in_previous_time_window,[0]*num_types,account_limits)
    server_characteristicsp = zip(names,procs,gbRAM,freestorage)
    servers = filter(lambda x: x[0] not in avoid_names,serversp)
    server_characteristics = filter(lambda x: x[0] not in avoid_names,server_characteristicsp)
    job_parameters = []
    job_parameters.append(("min_cores",min_cores,min_cores*5))
    job_parameters.append(("min_ram",min_ram,min_ram*5))
    job_parameters.append(("min_free_storage",min_free_storage,min_free_storage*5))
    Server = namedtuple("Instance", ["name","cost","qmin","qmax"])
    Job_param = namedtuple("Param", ["name","qmin","qmax"])
    server = [Server(*s) for s in servers]
    assert(len(server) > 0)
    params = [Job_param(*j) for j in job_parameters]
    server_info = {(sc[0], params[j].name): sc[1+j] for sc in server_characteristics for j in range(len(job_parameters))}
    mdl = Model(name='Instance Bidding')
    qty = {s: mdl.integer_var(lb=s.qmin,ub=s.qmax,name=s.name) for s in server}
    for p in params:
        amount = mdl.sum(qty[s] * server_info[s.name,p.name] for s in server)
        mdl.add_range(p.qmin,amount,p.qmax)
        mdl.add_kpi(amount, publish_name="Total %s" % p.name)
    mdl.minimize(mdl.sum(qty[s] * s.cost for s in server))
    mdl.print_information()
    url = None
    key = None
    if not mdl.solve(url=url, key=key):
        print("*** Problem has no solution")
    else:
        mdl.float_precision = 3
        print("* model solved as function:")
        mdl.report()
        mdl.print_solution()
github ekhoda / optimization-tutorial / execute_docplex.py View on Github external
I_0: initial_inventory
c_t: unit production cost in month t
d_t: demand of month t

Variables:
X_t: Amount produced in month t
I_t: Inventory at the end of period t

Constraints:
Inventory Constraints: I_{t-1} + X_t - d_t = I_t
Capacity Constraints: X_t <= p

Objective: Min Sum(h*I_t + c_t*X_t)
"""

model = cpx.Model('prod_planning')

start = time()

# ================== Decision variables ==================
production_variables = model.continuous_var_dict(input_df_dict['input_data'].index, name="X")
inventory_variables = model.continuous_var_dict(input_df_dict['input_data'].index, name="I")

# Alternative way of creating the variables
# production_variables = {index: model.continuous_var(name='X_' + str(row['period']))
#                         for index, row in input_df_dict['input_data'].iterrows()}
#
# inventory_variables = {index: model.continuous_var(name='I_' + str(row['period']))
#                        for index, row in input_df_dict['input_data'].iterrows()}

logger.debug("var declaration time: {:.6f}".format(time() - start))
github hzjken / crypto-arbitrage-framework / crypto / path_optimizer.py View on Github external
from docplex.mp.model import Model
import numpy as np
from itertools import combinations
from .info import fiat, trading_fee, tokens
from .utils import get_withdrawal_fees, get_crypto_prices, multiThread
import re
from copy import deepcopy


class PathOptimizer(Model):
    '''
    optimization model class for solving multi-lateral arbitrage path that maximizes profit.
    It outputs value zero when no arbitrage opportunity is found. When an opportunity is found,
    the model outputs the profit percentage as well as the arbitrage path.
    Arbitrage output considers the transaction spread as well as commission rates.
    Users can change parameter settings through modifying function set_params or inherit in subclass.

    Example Use:
    m = PathOptimizer()
    m.find_arbitrage()
    '''
    length = None  # number n, the number of currencies included.
    path_length = None  # the upper bound of arbitrage path length
    currency_set = None  # a set of length n, where n is the number of currencies included.
    exchanges = None  # the dict for storing clients towards each exchanges
github Qiskit / qiskit-aqua / qiskit / optimization / ising / docplex.py View on Github external
def _validate_input_model(mdl):
    """
    Check whether an input model is valid. If not, raise an AquaError

    Args:
         mdl (docplex.mp.model.Model): A model of DOcplex for a optimization problem.

    Raises:
        AquaError: Unsupported input model
    """
    valid = True

    # validate an object type of the input.
    if not isinstance(mdl, Model):
        raise AquaError('An input model must be docplex.mp.model.Model.')

    # raise an error if the type of the variable is not a binary type.
    for var in mdl.iter_variables():
        if not var.is_binary():
            logger.warning('The type of Variable %s is %s. It must be a binary variable. ',
                           var, var.vartype.short_name)
            valid = False

    # raise an error if the constraint type is not an equality constraint.
    for constraint in mdl.iter_constraints():
        if not constraint.sense == ComparisonType.EQ:
            logger.warning('Constraint %s is not an equality constraint.', constraint)
            valid = False

    if not valid:
github ekhoda / optimization-tutorial / optimization_model_docplex.py View on Github external
def __init__(self, input_data, input_params):
        self.input_data = input_data
        self.input_params = input_params
        self.model = cpx.Model('prod_planning')
        self._create_decision_variables()
        self._create_main_constraints()
        self._set_objective_function()
github kosticlab / aether / lp / ilp.py View on Github external
mdl.minimize(mdl.sum(qty[s] * s.cost for s in server))
    mdl.print_information()
    url = None
    key = None
    if not mdl.solve(url=url, key=key):
        print("*** Problem has no solution")
    else:
        mdl.float_precision = 3
        print("* model solved as function:")
        mdl.report()
        mdl.print_solution()
        mdl.report_kpis()
        mdl.export_as_lp("cplex.lp")
        os.system("cat cplex.lp")
        # Save the CPLEX solution as "solution.json" program output
        with get_environment().get_output_stream("instances.json") as fp:
            mdl.solution.export(fp, "json")
    return

docplex

The IBM Decision Optimization CPLEX Modeling for Python

Apache-2.0
Latest version published 9 days ago

Package Health Score

68 / 100
Full package analysis

Similar packages