Esempio n. 1
0
def check_environment():
    from docplex.mp.environment import Environment
    env = Environment()

    if not env.has_cplex:
        print("CPLEX not installed.")
    else:
        print("CPLEX is installed.\n")
        env.print_information()
Esempio n. 2
0
def main(instances, verbose=False):
    env = Environment()
    env.print_information()

    dir_path = os.path.dirname(os.path.realpath(__file__))

    solutions = []

    for index, instance in enumerate(instances):

        data, h, w, problem_class = instance

        data = sorted(data, key=itemgetter(0), reverse=True)

        try:
            mdl = build_model(data, w, h)

            if verbose:
                print(mdl.export_to_string())
                mdl.print_information()

            mdl.export_as_lp(dir_path + "/" + mdl.name + "_" + str(index) +
                             '.lp')
            if mdl.solve(log_output=verbose):
                if verbose:
                    mdl.float_precision = 3
                    print("* model solved as function:")
                    mdl.print_solution()
                    mdl.report_kpis()

                # Save the CPLEX solution as "solution.json" program output
                with get_environment().get_output_stream(
                        dir_path + "/" + mdl.name + "_" + str(index) +
                        "_solution.json") as fp:
                    mdl.solution.export(fp, "json")
            else:
                print("* model has no solution")

        except Exception as e:
            # Problem with more than 1000 variables
            print(e)
Esempio n. 3
0
    def __init__(self, sc_inputs):
        self._solved = False

        # Import data
        self.import_data(sc_inputs)

        # Initialize cplex
        self._env = Environment()
        self.uc = Model("UnitCommitment", log_output=True)

        # Create variables
        self.build_decision_vars()

        # Create expressions
        self.build_var_expressions()

        # Add constraints
        self.__add_var_limit_cons()
        self.__add_therm_units_cons()
        self.add_demand_cons()

        # Add objective and KPIs
        self.add_objective_and_kpis()
        self._sc_outputs = {}
Esempio n. 4
0
from docplex.mp.environment import Environment
from docplex.mp.model import Model
import pandas as pd

N_DAYS = 2
N_PERIODS_PER_DAY = 24 * 4
N_PERIODS = N_DAYS * N_PERIODS_PER_DAY

df_resources = inputs['resources']
df_demands = inputs['demands']

env = Environment()

mdl = Model("planning")

resources = df_resources['id'].values.tolist()

nb_periods = N_PERIODS

# periods range from 0 to nb_periods excluded
periods = range(0, nb_periods)

# days range from 0 to N_DAYS excluded
days = range(0, N_DAYS)

# start[r,t] is number of resource r starting to work at period t
start = mdl.integer_var_matrix(keys1=resources, keys2=periods, name="start")

# work[r,t] is number of resource r working at period t
work = mdl.integer_var_matrix(keys1=resources, keys2=periods, name="work")
Esempio n. 5
0
def run_docplex_check_list():
    check_platform()
    from docplex.version import latest_cplex_major, latest_cplex_minor
    cplex_latest_version_as_tuple = (latest_cplex_major, latest_cplex_minor)

    diagnostics = []

    # check requirements
    for rm in ["six", "enum", "cloudpickle"]:
        if not check_import(rm):
            diagnostics.append(
                "Module {0} is missing, run: pip install {0}".format(rm))

    # check pandas
    try:
        import pandas as pd  # @UnusedImport
        # noinspection PyUnresolvedReferences
        from pandas import DataFrame
        DataFrame({})
    except ImportError:
        print("-- pandas is not present, some features might be unavailable.")

    from docplex.mp.environment import Environment
    Environment().print_information()

    # check cplex
    try:
        # noinspection PyUnresolvedReferences
        from cplex import Cplex

        cpx = Cplex()
        cpxv = cpx.get_version()
        cpxvt = tuple(float(x) for x in cpx.get_version().split("."))[:2]
        lcpxv = ".".join(str(z) for z in cplex_latest_version_as_tuple)
        if cpxvt < cplex_latest_version_as_tuple:
            print(
                "Warning: Your cplex version {0} is not the latest, {1} is available"
                .format(cpxv, lcpxv))
        elif cpxvt > cplex_latest_version_as_tuple:
            print(
                "* Your cplex version {0} is ahead of the latest DOcplex-compatible version {1}, this might not be compatible."
                .format(cpxv, lcpxv))
        else:
            print("* Your cplex version {0} is the latest available".format(
                cpxv))
        cpx.end()

    except ImportError as ie:
        Cplex = None
        diagnostics.append("No local installation of CPLEX has been found.")
        print("Cplex DLL not found, error importing cplex: {0!s}".format(ie))
        check_python_path(diagnostics)
    # check creation of an empty model...

    try:
        if Cplex:
            # noinspection PyUnresolvedReferences
            from docplex.mp.model import Model
            Model()
            # promotional?
            if Model.is_cplex_ce():
                print(
                    "! Cplex promotional version, limited to 1000 variables, 1000 constraints"
                )
                diagnostics.append(
                    "Your local CPLEX edition is limited. Consider purchasing a full license."
                )

    except ImportError:
        print("Docplex is not present: cannot import class docplex.mp.model")
        diagnostics.append("Your installation of DOcplex may be corrupted.")
    except Exception as e:
        print(
            "Exception raised when creating one model instance: {0!s}".format(
                e))
        diagnostics.append("Your installation of DOcplex may be corrupted.")

    if diagnostics:
        print("\n!! diagnostics: {0}".format(len(diagnostics)))
        for s in diagnostics:
            print("  -- {0}".format(s))
    else:
        print("> No problem found: you're all set!")
Esempio n. 6
0
    def __init__(self, coslocation=None, procedural=True):
        self.procedural = procedural
        env = Environment()
        # get the CPLEX module from specified location
        cplex_module = env.get_cplex_module(coslocation)
        if cplex_module is None:
            location = coslocation if coslocation is not None else "default path"
            raise ImportError("Cannot import cplex from %s" % location)
        self.cplex_module = cplex_module
        subinterfaces = cplex_module._internal._subinterfaces
        cpx = self.cplex_module.Cplex()
        self.cplex_location = dirname(dirname(cplex_module.__file__))
        cpxv = cpx.get_version()
        if cpxv.startswith('12.7.0'):  # pragma: no cover
            del cpx
            # create a safe wrapper for RTC-31555
            cpx = _get_safe_cplex_wrapper(self.cplex_module)
        self.cpx = cpx
        # quick access to constants
        cpx_cst = self.cplex_module._internal._constants
        self.cpx_cst = cpx_cst
        # methods
        self.chgcoeflist = self.cplex_module._internal._procedural.chgcoeflist
        self.chgobj = self.cplex_module._internal._procedural.chgobj
        self.chgrhs = self.cplex_module._internal._procedural.chgrhs
        self.chgqpcoef = self.cplex_module._internal._procedural.chgqpcoef
        self.newcols = self.cplex_module._internal._procedural.newcols
        self.setintparam = self.cplex_module._internal._procedural.setintparam
        self.addindconstr = self.cplex_module._internal._procedural.addindconstr
        self.addrows = self.cplex_module._internal._procedural.addrows
        self.chgrngval = self.cplex_module._internal._procedural.chgrngval
        self.addpwl = self.cplex_module._internal._procedural.addpwl
        self.getnumpwl = self.cplex_module._internal._procedural.getnumpwl
        self.chgcolname = self.cplex_module._internal._procedural.chgcolname
        self.getx = self.cplex_module._internal._procedural.getx
        self.chgctype = self.cplex_module._internal._procedural.chgctype
        self.getprobtype = self.cplex_module._internal._procedural.getprobtype
        self.getnumcols = self.cplex_module._internal._procedural.getnumcols
        self.getnumrows = self.cplex_module._internal._procedural.getnumrows
        self.getrows = self.cplex_module._internal._procedural.getrows
        self.getcolname = self.cplex_module._internal._procedural.getcolname
        try:
            # needs cplex > 12.9
            self.multiobjsetobj = self.cplex_module._internal._procedural.multiobjsetobj
        except AttributeError:
            self.multiobjsetobj = None

        subinterfaces = self.cplex_module._internal._subinterfaces
        self.ct_linear = subinterfaces.FeasoptConstraintType.linear
        self.ct_quadratic = subinterfaces.FeasoptConstraintType.quadratic
        self.ct_indicator = subinterfaces.FeasoptConstraintType.indicator

        # initialize constants etc...
        try:
            cpxv = self.cplex_module.__version__
            cpxv_as_tuples = cpxv.split('.')
            cpxvt = tuple(int(x) for x in cpxv_as_tuples)
            self.is_post1210 = cpxvt >= (12, 10)
        except AttributeError:  # pragma: no cover
            self.is_post1210 = False
        # chbmatrix
        try:
            # from 12.7.1 up
            self.chbmatrix = self.cplex_module._internal._procedural.chbmatrix
        except AttributeError:  # pragma: no cover
            # up to 12.7.0
            try:
                self.chbmatrix = self.cplex_module._internal._matrices.chbmatrix
            except AttributeError:
                self.chbmatrix = None

        # indicator types
        try:
            self.cpx_indicator_type_ifthen = cpx_cst.CPX_INDICATOR_IF
            self.cpx_indicator_type_equiv = cpx_cst.CPX_INDICATOR_IFANDONLYIF
        except AttributeError:  # pragma: no cover
            # handle previous versions without indicator type
            self.cpx_indicator_type_ifthen = None
            self.cpx_indicator_type_equiv = None

        if self.cpx_indicator_type_equiv is None:
            self.supports_typed_indicators = False  # pragma: no cover
        else:
            try:
                IndicatorConstraintInterface = subinterfaces.IndicatorConstraintInterface
                # noinspection PyStatementEffect
                IndicatorConstraintInterface.type_
                self.supports_typed_indicators = True
            except AttributeError:  # pragma: no cover
                self.supports_typed_indicators = False

        # fast methods
        self.fast_add_linear = self.fast_add_linear_1210 if self.is_post1210 else self.fast_add_linear1290

        # exception
        self.CplexError = self.cplex_module.exceptions.CplexError
        self.CplexSolverError = self.cplex_module.exceptions.CplexSolverError
Esempio n. 7
0
import os
print(os.environ)

# Load CSV files into inputs dictionnary
inputs = get_all_inputs()

#dd-cell
food = inputs['diet_food']
nutrients = inputs['diet_nutrients']
food_nutrients = inputs['diet_food_nutrients']
food_nutrients.set_index('Food', inplace=True)
#dd-cell
from docplex.mp.model import Model
from docplex.mp.environment import Environment
Environment().print_information()

# Model
mdl = Model(name='diet')

# Create decision variables, limited to be >= Food.qmin and <= Food.qmax
qty = food[['name', 'qmin', 'qmax']].copy()
qty['var'] = qty.apply(
    lambda x: mdl.continuous_var(lb=x['qmin'], ub=x['qmax'], name=x['name']),
    axis=1)
# make the name the index
qty.set_index('name', inplace=True)

# Limit range of nutrients, and mark them as KPIs
for n in nutrients.itertuples():
    amount = mdl.sum(qty.loc[f.name]['var'] *