How to use the docplex.mp.model.Model function in docplex

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 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 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:

docplex

The IBM Decision Optimization CPLEX Modeling for Python

Apache-2.0
Latest version published 4 months ago

Package Health Score

68 / 100
Full package analysis

Similar packages