예제 #1
0
 def solve(self, mzn_model, dzn_data):
     """
     :param mzn_model: minizinc template
     :param dzn_data: minizinc data model
     :return: minizinc response
     """
     return pymzn.minizinc(mzn=mzn_model, data=dzn_data)
예제 #2
0
 def _test_model_data_file(self, solver):
     import os
     fn = self.save_as_temp_file(self.model, '.mzn')
     dn = self.save_as_temp_file('k=2;', '.dzn')
     out = list(pymzn.minizinc(fn, dn, solver=solver))
     os.remove(fn)
     self.assertEqual(out, self.solution)
예제 #3
0
 def improve(self, x, x_star, w, alpha=0.2, approx=False):
     try:
         sols = []
         if approx and self.timeout:
             timeout = self.timeout
         else:
             timeout = None
         while len(sols) == 0:
             sols = pymzn.minizinc(self.improve_model,
                                   data={
                                       **self._data,
                                       **input_x(x), 'w': w,
                                       **input_star_x(x_star), 'ALPHA':
                                       alpha
                                   },
                                   output_vars=['x', 'y', 'dx', 'dy'],
                                   mzn_globals_dir='opturion-cpx',
                                   serialize=True,
                                   keep=True,
                                   fzn_fn=pymzn.opturion,
                                   timeout=timeout)
             if timeout is not None:
                 timeout *= 2
         return sols[-1]
     except pymzn.MiniZincUnsatisfiableError:
         # when no improvement possible for noisy users
         return x
예제 #4
0
def solve_it(input_data):
    # Modify this code to run your optimization algorithm

    # parse the input
    lines = input_data.split('\n')
    first_line = lines[0].split()
    node_count = int(first_line[0])
    edge_count = int(first_line[1])
    parents = []
    children = []
    for i in range(1, edge_count + 1):
        line = lines[i]
        parts = line.split()
        parents.append(int(parts[0]))
        children.append(int(parts[1]))

    # build a trivial solution
    # every node has its own color
    solution = pymzn.minizinc('grafos.mzn',
                              data=dict(Nodes=node_count,
                                        Edges=edge_count,
                                        n_p=parents,
                                        n_h=children),
                              output_mode='dict',
                              parallel=4)[0]

    # prepare the solution in the specified output format

    output_data = str(solution['mc'] + 1) + ' ' + str(0) + '\n'
    for i in solution['colors']:
        output_data += str(solution['colors'][i]) + ' '

    return output_data
예제 #5
0
    def infer(self, w, features, template_path, data):
        """Searches for a maximum utility item.

        Parameters
        ----------
        w : numpy.ndarray of shape (num_features,)
            The weight vector.
        features : list or "all" or "attributes"
            The features to be used in the computation.
        template_path : str
            Path to the minizinc problem file.
        data : dict
            Data to be passed to the minizinc solver.

        Returns
        -------
        x : numpy.ndarray of shape (num_attributes,)
            An optimal configuration.
        """
        assert w.shape == (self.num_features, )

        targets = self.enumerate_features(features)
        if (w[targets] == 0).all():
            print("Warning: all-zero w!")

        assignments = minizinc(template_path,
                               data=data,
                               output_vars=["x", "objective"],
                               keep=True)

        return self.assignment_to_array(assignments[0]["x"])
예제 #6
0
 def _test_model_data_file(self, solver):
     mzn_file = _save_as_temp_file(self.model, '.mzn')
     dzn_file = _save_as_temp_file('k=2;', '.dzn')
     out = minizinc(mzn_file, dzn_file, solver=solver)
     self.assertEqual(list(out), self.solution)
     os.remove(mzn_file)
     os.remove(dzn_file)
예제 #7
0
def main():
    """Main driver function"""
    activities = []
    data = {}
    quanta = 0
    stime = ''
    if (
            len(argv) == 2 and str(argv[1]).find('.txt') > -1
    ):  # If commandline arguments are detected, read input from the given input file
        activities, data, quanta, stime = read_system(str(argv[1]))
    else:  # If commandline arguments are not found, ask user to give input
        activities, data, quanta, stime = input_system()
    print(
        'Please wait while an AI solver tries to manage your schedule ... ...')
    try:  # Tries to run the model with given data using CoinBC solver
        result = pymzn.minizinc('Routine.mzn',
                                'Null.dzn',
                                data=data,
                                solver=pymzn.cbc)
        schedule = format_mzn_solution(result)
    except (Exception):
        print('Sorry solution cannot be found')
        print('Press ENTER to exit ...')
        input()
        return
    tasklist = []
    for task in schedule:
        tasklist.append(activities[task - 1])  # Prepares a task list
    # comprehensive_output(tasklist, quanta)
    tabular_output(tasklist, quanta, stime)  # Displays output
    return
예제 #8
0
    def phi(self, x, features, template_path, data):
        """Computes the feature representation of x.

        Parameters
        ----------
        x : numpy.ndarray of shape (num_attributes,)
            The object.
        features : list or "all" or "attributes"
            The features to be used in the computation.
        template_path : str
            Path to the minizinc problem file.
        data : dict
            Data to be passed to the minizinc solver.

        Returns
        -------
        phi : numpy.ndarray of shape (num_features,)
            The feature representation of ``x``.
        """
        assert x.shape == (self.num_attributes, )

        assignments = minizinc(template_path,
                               data=data,
                               output_vars=["phi"],
                               keep=True)

        phi = self.assignment_to_array(assignments[0]["phi"])
        mask = np.ones_like(phi, dtype=bool)
        mask[self.enumerate_features(features)] = False
        phi[mask] = 0

        return phi
    def okBtnFunc(self):
        import pymzn

        if (self.fileName):
            #self.textEdit.setEnabled(True)
            #self.textEdit.setText(" One moment Please ...\nConnecting to Minizinc...")
            dictData = {'produce': self.produceList}
            solns = pymzn.minizinc('prodSchedule.mzn',
                                   self.fileName,
                                   data=dictData,
                                   output_mode='dict')
            strOutput = ""
            for key, value in solns[0].items():
                s = '{} = {};\n'.format(key, value)
                strOutput += s

            self.prodScheOutputf = QtWidgets.QWidget()
            self.prodScheOutputfUi = Ui_prodScheOutputForm()
            self.prodScheOutputfUi.setupUi(self.prodScheOutputf)
            self.prodScheOutputfUi.textEdit.setText(strOutput)
            self.prodScheOutputf.show()
            self.form.hide()
            pass
        else:
            strData = self.textEdit.toPlainText()
            fp = open("prodScheDataAuto.dzn", 'w')
            fp.write(strData)
            fp.write("\n")
            fp.write("produce = ")
            fp.write(str(self.produceList))
            fp.write(";\n")
            fp.close()
            solns = pymzn.minizinc('prodSchedule.mzn',
                                   "prodScheDataAuto.dzn",
                                   output_mode='dict')
            strOutput = ""
            for key, value in solns[0].items():
                s = '{} = {};\n'.format(key, value)
                strOutput += s

            self.prodScheOutputf = QtWidgets.QWidget()
            self.prodScheOutputfUi = Ui_prodScheOutputForm()
            self.prodScheOutputfUi.setupUi(self.prodScheOutputf)
            self.prodScheOutputfUi.textEdit.setText(strOutput)
            self.prodScheOutputf.show()
            self.form.hide()
            pass
예제 #10
0
def initialize():
    print("initializing")
    print(".......")
    print(".......")
    print("number of intersections:")
    n = int(input())

    data = []
    importance = []
    for i in range(n):
        global adj_list
        print(
            "input the nodes associated with current node and the congestion and importance of the road conncting them in the format \"road cogestion imortance\""
            + str(i + 1))
        inp = input()
        inp = inp.split()
        lst = [int(j) for j in inp]
        final_lst = []
        index = 0
        while index < len(lst):
            final_lst.append([lst[index], lst[index + 1], lst[index + 2]])
            index = index + 3
    # print(final_lst)
        adj_list.append(final_lst)
        lst2 = [0] * (n)
        lst_imp = [0] * (n)
        for j in final_lst:
            # print(j)
            lst2[j[0] - 1] = j[1]
            lst_imp[j[0] - 1] = j[2]
        data.append(lst2)
        importance.append(lst_imp)

    data_max = {'n': n, 'congestion_graph': data, 'importance': importance}
    dzn = pm.dict2dzn(data_max, fout='max_find.dzn')
    sol_max = pm.minizinc('maximum_calculator.mzn', 'max_find.dzn')

    max_cost = sol_max[0]['max_cost']
    max_imp = sol_max[0]['max_imp']
    print("max cost = ", max_cost)
    print("max imp = ", max_imp)
    max_turn = 25
    print("how fast do you want the system to update signals?")
    signal_period = int(input())
    prev = [[0] * (n)] * (n)
    data = {
        'n': n,
        'congestion_graph': data,
        'max_cost': max_cost,
        'max_turn': max_turn,
        'prev': prev,
        'importance': importance,
        'max_imp': max_imp
    }
    #   print(data)
    dzn = pm.dict2dzn(data, fout='datafrompython.dzn')
    dzn = pm.dict2dzn(data, fout='test_data0.dzn')
    return [dzn, signal_period]
예제 #11
0
    def query_improvement(self, x, w_star, features, template_path, data):
        """Searches for a local maximum utility modification.

        If loss(x) is zero, i.e. x is optimal, it is return unmodified; under
        no other circumstances x can be returned unmodified.

        Parameters
        ----------
        x : numpy.ndarray of shape (num_attributes,)
            The configuration.
        w_star : numpy.ndarray of shape (num_features,)
            The (possibly perturbet) user's latent weight vector.
        features : list or "all" or "attributes"
            The features to be used in the computation.
        template_path : str
            Path to the minizinc problem file.
        data : dict
            Data to be passed to the minizinc solver.

        Returns
        -------
        x_bar : numpy.ndarray of shape (n_attributes,)
            The locally optimal modification.
        """
        assert x.shape == (self.num_attributes, )

        if self.utility_loss(x, "all") == 0:
            # XXX this is noiseless
            return "satisfied"

        targets = self.enumerate_features(features)
        assert (w_star[targets] != 0).any()

        try:
            assignments = minizinc(template_path,
                                   data=data,
                                   output_vars=["x", "objective"],
                                   keep=True)
        except MiniZincUnsatisfiableError:
            # this happens when there is no better configuration for the noisy
            # weight vector
            return x

        x_bar = self.assignment_to_array(assignments[0]["x"])
        assert (x != x_bar).any(), (x, x_bar)

        phi = self.phi(x, "all")
        phi_bar = self.phi(x_bar, "all")
        assert (phi != phi_bar).any()

        utility = np.dot(w_star, self.phi(x, targets))
        utility_bar = np.dot(w_star, self.phi(x_bar, targets))
        assert utility_bar > utility, \
            "u^k({}) = {} is not larger than u^k({}) = {}".format(
                x_bar, utility_bar, x, utility)

        return x_bar
예제 #12
0
 def test_minizinc(self):
     out = pymzn.minizinc(self.model,
                          data={
                              'N': 5,
                              'profit': [10, 3, 9, 4, 8],
                              'size': [14, 4, 10, 6, 9],
                              'capacity': 20
                          })
     self.assertEqual(out, [{'x': {3, 5}}])
예제 #13
0
    def _infer(
        self, x, *args, model=None, problem='map', return_phi=False, **kwargs
    ):
        if self._x_vars is None:
            self._x_vars = list(x.keys())

        y_true = None
        if len(args) >= 1:
            y_true = args[0]
            if self._y_vars is None:
                self._y_vars = list(y_true.keys())

        if problem == 'phi':
            assert y_true is not None
            return self._phi(x, y_true, **kwargs)

        if model is None:
            model = BaseModel(self)

        args = {
            **self.args, **kwargs, 'params': model.params, 'problem': problem
        }

        output_vars = None
        if problem and self._y_vars:
            output_vars = self._y_vars + [self.feature_var]

        if y_true is not None:
            args['y_true'] = y_true

        _timeout = self.timeout
        stream = None
        while not stream:
            try:
                stream = pymzn.minizinc(
                    self.domain_file, data=x, args=args,
                    output_vars=output_vars, timeout=_timeout
                )
            except pymzn.MiniZincError:
                if _timeout is not None:
                    _timeout *= 2
                else:
                    raise

        if len(stream) == 0:
            raise InferenceError('Inference returned no solution.')

        y, res = dictsplit(stream[-1], self._y_vars)

        if return_phi:
            phi = None
            if self.feature_var in res:
                phi = np.array(res[self.feature_var])
            else:
                phi = self._phi(x, y, **kwargs)
            return y, phi
        return y
 def infer(self, x, w):
     _frx = freeze(x), freeze(w)
     if _frx not in self._infers:
         _argmax = pymzn.minizinc(self.mzn_infer,
                                  data={
                                      **x, 'w': w
                                  },
                                  solver=pymzn.opturion)[0]
         self._infers[_frx] = _argmax
     return self._infers[_frx]
    def infer(self, x, w, features=None, timeout=600):
        results = pymzn.minizinc(
            self.inference_file,
            data={
                **x, "w": w
            },
            timeout=timeout,
            output_vars=Rooms._inference_vars,
            #parse_output=False,
            solver=pymzn.opturion,
            suppress_segfault=True)

        return results[-1]
 def phi(self, x, y):
     _frx = freeze(x), freeze(y)
     if _frx not in self._phis:
         ykeys = ['x', 'y', 'dx', 'dy']
         _phi = pymzn.minizinc(
             self.mzn_phi,
             output_vars=['phi'],
             data={
                 **self.inputize(subdict(y, ykeys), ykeys),
                 **x
             },
             solver=pymzn.opturion)[0]['phi']
         self._phis[_frx] = np.array(_phi, dtype=np.float64)
     return self._phis[_frx]
    def improve(self, x, phi, changed):
        """Returns an object with the given phi.

        This is used to get a new object after the user changes some feature.
        """
        _frx = freeze(x), freeze(phi)
        if _frx not in self._improves:
            _impr = pymzn.minizinc(self.mzn_improve,
                                   data={
                                       **x, 'input_phi': phi,
                                       'changed': changed + 1
                                   },
                                   solver=pymzn.opturion)[0]
            self._improves[_frx] = _impr
        return self._improves[_frx]
예제 #18
0
def mzn_solver(mzn_content, opt_info):
    """Calls the minizinc optimizer.

    """
    args = opt_info['solverArgs']
    solver = get_mzn_solver(args.pop('solver'))
    mzn_opts = dict()

    try:
        file_name = persist_opt_data(opt_info)
        mzn_opts.update(args)
        return minizinc(mzn_content, file_name, **mzn_opts, solver=solver)

    finally:
        delete_file_folder(file_name)
예제 #19
0
def runMinizinc(dznFile, mznFile, variables, numExample):
    outputDic = []
    for sol in pymzn.minizinc(mznFile,
                              all_solutions=True,
                              output_vars=variables,
                              timeout=5):
        if sol is None:
            continue
        if 'shipping' in dznFile:
            tmp = copy.deepcopy(sol)
            tmp['ship'] = to_matrix(sol['ship'], sol['W'])
            outputDic.append(tmp)
        elif 'number_of_days' in dznFile:
            tmp = copy.deepcopy(sol)
            tmp['data'] = to_matrix(sol['data'], 2)
            outputDic.append(tmp)
        elif 'rostering' in dznFile:
            tmp = copy.deepcopy(sol)
            tmp['on_duty'] = to_matrix(sol['on_duty'], sol['num_shifts'])
            outputDic.append(tmp)
        elif 'curriculum' in dznFile:
            tmp = copy.deepcopy(sol)
            tmp['x'] = to_matrix(sol['x'], sol['n_courses'])
            outputDic.append(tmp)
        elif 'stuckey_assignment' in dznFile:
            tmp = copy.deepcopy(sol)
            tmp['profit'] = to_matrix(sol['profit'], sol['num_products'])
            tmp['x'] = to_matrix(sol['x'], sol['num_products'])
            outputDic.append(tmp)
        elif 'golfers' in dznFile:
            tmp = copy.deepcopy(sol)
            tmp['assign'] = to_matrix(sol['assign'], sol['weeks'])
            outputDic.append(tmp)
        elif 'assignment' in dznFile:
            tmp = copy.deepcopy(sol)
            tmp['cost'] = to_matrix(sol['cost'], sol['cols'])
            tmp['x'] = to_matrix(sol['x'], sol['cols'])
            outputDic.append(tmp)
        else:
            outputDic.append(sol)

    num = 2000
    if len(outputDic) < 1000:
        num = len(outputDic)
    data = helper.list_sample(outputDic[:num], numExample)
    print("...Randomly Selected", len(data), "examples...")
    #    print(data[0])
    return data
예제 #20
0
    def _phi(self, x, y, **kwargs):
        if self._x_vars is None:
            self._x_vars = list(x.keys())
        if self._y_vars is None:
            self._y_vars = list(y.keys())

        stream = pymzn.minizinc(
            self.domain_file, data={**x, **y},
            args={**self.args, **kwargs, 'problem': 'phi'},
            output_vars=[self.feature_var]
        )

        if len(stream) == 0:
            raise InferenceError('Inference returned no solution.')

        return np.array(stream[-1][self.feature_var])
예제 #21
0
    def phi(self, x, y):
        """Returns the feature vector of (x, y)."""
        _frx = freeze({**x, **y})
        if _frx in self._phis:
            return self._phis[_frx]

        model = MiniZincModel(self.template)
        for attr, value in y.items():
            model.par(attr, value)
        features, phi_type = self._mzn_features()
        model.par('FEATURES', set(range(1, self.num_features + 1)))
        model.var('array[FEATURES] of {}'.format(phi_type), 'phi', features)
        model.solve('satisfy')
        _phi = minizinc(model, data={**x}, output_vars=['phi'],
                        keep=self.keep)[0]['phi']
        self._phis[_frx] = np.array(_phi, dtype=float)
        return self._phis[_frx]
예제 #22
0
    def phi(self, x):
        _frx = freeze(x)
        if _frx in self._phis:
            return self._phis[_frx]

        _phi = pymzn.minizinc(self.phi_model,
                              data={
                                  **self._data,
                                  **input_x(x)
                              },
                              output_vars=['phi'],
                              serialize=True,
                              mzn_globals_dir='opturion-cpx',
                              keep=True,
                              fzn_fn=pymzn.opturion)[0]['phi']
        self._phis[_frx] = np.array(_phi)
        return self._phis[_frx]
예제 #23
0
    def n_features(self, **kwargs):
        """Return the number of features in the feature vector.

        Parameters
        ----------
        kwargs
            Additional arguments needed by the domain file.
        """
        args = {'problem': 'n_features', **self.args, **kwargs}
        stream = pymzn.minizinc(
            self.domain_file, problem='n_features', args=args,
            output_vars=[self.n_features_var]
        )

        if len(stream) == 0 or self.n_features_var not in stream[-1]:
            raise InferenceError('Problem n_features not supported.')

        return stream[-1][self.n_features_var]
def model(weights, problem, all_solutions=False):
    nb_types = problem.types
    nb_areas = problem.areas
    nb_room_types = problem.roomtypes
    nb_of_rooms = problem.max_rooms
    nb_layout_features = problem.features
    nb_layout_options = problem.options
    type_weights_mzn = np.array2string(
        weights[0],
        separator=',',
        formatter={'float_kind': lambda x: "%.2f" % x})
    area_weights_mzn = np.array2string(
        weights[1],
        separator=',',
        formatter={'float_kind': lambda x: "%.2f" % x})
    room_weights_mzn = convert_for_minizinc_2d(weights[2].astype(float),
                                               nb_room_types, nb_of_rooms)
    layout_weights_mzn = convert_for_minizinc_2d(weights[3].astype(float),
                                                 nb_layout_features,
                                                 nb_layout_options)

    data = {
        'nb_types': nb_types,
        'nb_areas': nb_areas,
        'nb_room_types': nb_room_types,
        'nb_of_rooms': nb_of_rooms,
        'nb_layout_features': nb_layout_features,
        'nb_layout_options': nb_layout_options,
        'type_weights': type_weights_mzn,
        'area_weights': area_weights_mzn,
        'room_weights': room_weights_mzn,
        'layout_weights': layout_weights_mzn,
        'price': problem.upper_price,
        'total': problem.options
    }
    # print('Minizinc input: ', str(data).replace(' , ', ',').replace(', ', '; ').replace(': ', '= ').replace('{', '"').replace('}','"').replace("'", ''))

    solns = pymzn.minizinc('minizinc_files/features_real_estate.mzn',
                           data=data,
                           all_solutions=all_solutions)
    # object = np.array(features[0]['feature_rep'])
    # phi = np.array(features[0]['terms'])
    return Real_estate_object(solns)
예제 #25
0
 def infer(self, w, approx=False):
     sols = []
     if approx and self.timeout:
         timeout = self.timeout
     else:
         timeout = None
     while len(sols) == 0:
         sols = pymzn.minizinc(self.infer_model,
                               data={
                                   **self._data, 'w': w
                               },
                               output_vars=['x', 'y', 'dx', 'dy'],
                               mzn_globals_dir='opturion-cpx',
                               serialize=True,
                               keep=True,
                               fzn_fn=pymzn.opturion,
                               timeout=timeout)
         if timeout is not None:
             timeout *= 2
     return sols[-1]
예제 #26
0
    def phi(self, x, y, features=None):
        """The feature map.

        Returns the feature vector of the object y in the context x with respect
        to the given features. This function is cached, there is an overhead for
        computing the feature vector only the first time it is called with the
        same parameters.

        Parameters
        ----------
        x : dict
            The context of the current iteration. This dictionary is given to
            the MiniZinc problem as additional data.
        y : dict
            The object to calculate the feature vector on.
        features : list
            The list of features to calculate the feature vector with.

        Returns
        -------
        numpy.ndarray
            The computed feature vector.
        """
        if features is None:
            features = self.features

        _frx = (freeze(x), freeze(y), tuple(sorted(features)))
        if _frx in self._phis:
            return self._phis[_frx]
        print("called")
        model = pymzn.MiniZincModel(self.template)
        model.parameters(y.items())

        feat_type = self.feat_type
        model.parameter('FEATURES', mzn_range(features))
        model.array_variable('phi', 'FEATURES', feat_type, features, output=True)
        model.satisfy()
        sol = pymzn.minizinc(model, data=x)
        _phi = sol[0]['phi']
        self._phis[_frx] = np.array(_phi, dtype=np.float64)
        return self._phis[_frx]
예제 #27
0
    def infer(self, x, w, features=None):
        """Solve an inference problem.

        Returns the object y that maximizes the utility with respect to the
        given weights w and the given features, in context x.

        Parameters
        ----------
        x : dict
            The context of the current iteration. This dictionary is given to
            the MiniZinc problem as additional data.
        w : numpy.ndarray
            The weight vector to use for the utility function.
        features : list
            The list of features to calculate the feature vector with.

        Returns
        -------
        dict
            The optimal object y.
        """
        if features is None:
            features = self.features

        model = pymzn.MiniZincModel(self.template)

        # CONVERTIRE IN PESI INTERI if self.feat_type == 'int'
        model.parameter('w', w)
        for attr, attr_type in self.attributes.items():
            model.variable(attr, attr_type)

        feat_type = self.feat_type
        model.parameter('FEATURES', mzn_range(features))
        model.array_variable('phi', 'FEATURES', feat_type, features)

        model.constraints(self.constraints)

        dtype = dot_type(w, feat_type)
        model.variable('obj', dtype, mzn_dot('w', 'phi'))
        model.maximize('obj')
        return pymzn.minizinc(model, data=x, parse_output=False, parallel=8)[0]
예제 #28
0
def main() -> int:
    '''
    Sequential operation:
        - load .dzn file
        - process it and save it in a new file
        - try to find solutions with MiniZinc and Gecode solver (optional)
        - plot in a graph all path obtained for visual feedback (optional)
    '''
    data = load_dataset(args.dzn_path)

    if not data:
        raise Exception(f"an error occurred while loading the dataset")

    data = process(data, args.dzn_path, args.order)
    # Save processed data to {args.output}.dzn file
    pymzn.dict2dzn(data, fout=args.output)

    print("Preprocessing completed.")
    if not args.solve:
        return -1

    if not file_exists(args.model, MZN_EXT):
        return -1

    print(f"Running {args.model} with {args.output}({args.dzn_path})...")
    # Default solver is Gecode (pymzn.Solver)
    sols = pymzn.minizinc(args.model,
                          args.output,
                          timeout=args.limit,
                          all_solutions=True)

    if not sols:
        print("No solutions found.")
        return -1

    path, vehicle = print_solution(sols)
    if args.plot:
        plot_path(data, path, vehicle)

    return 0
    def phi(self, x, y, features=None):
        if features is None:
            features = self.features

        _frx = (freeze(x), freeze(y), tuple(sorted(features)))
        if _frx in self._phis:
            return self._phis[_frx]

        sol = pymzn.minizinc(
            self.phi_file,
            data={
                **inputize(subdict(y, keys=Rooms._phi_keys), Rooms._phi_keys),
                **x
            },
            output_vars=Rooms._phi_vars,
            solver=pymzn.opturion,
            suppress_segfault=True)
        _phi = [
            p * n for p, n in zip(sol[-1]['phi'], sol[-1]['all_normalizers'])
        ]
        self._phis[_frx] = np.array(_phi, dtype=np.float64)
        return self._phis[_frx]
예제 #30
0
def solver(service, length, env):
    """
    Python wrapper calls minizinc model(.mzn) using python variables instead of stored data file(.dzn). To execute
    the model as standalone use:

    ./minizinc -c placement.mzn placement.dzn   It generates placement.fzn (Flatzinc model)
    ./fzn-gecode placement.fzn

    Args:
        service[length] -- Collects the service chain
        length(int) -- Length of the service
        env(obj) -- Instance of the environment
    """

    chain = service.tolist()
    chain = chain[:length]
    chain = [x + 1 for x in chain]  # Minizinc array indexes start at 1

    weights = [
        env.service_properties[i]['size'] for i in range(env.numDescriptors)
    ]

    s = pymzn.minizinc('placement.mzn',
                       solver='gecode',
                       timeout=30,
                       parallel=4,
                       data={
                           'numBins': env.numBins,
                           'numSlots': env.numSlots,
                           'chainLen': length,
                           'chain': chain,
                           'numDescriptors': env.numDescriptors,
                           'weights': weights
                       })
    placement = s[0]['placement']
    placement = [x - 1 for x in placement]

    return placement
예제 #31
0
 def test_minizinc(self):
     out = minizinc(self.model, data=self.data_dict_3)
     self.assertEqual(list(out), [{'x': {3, 5}}])
예제 #32
0
 def _test_data_str(self, solver):
     out = minizinc(solver=solver, mzn=self.model, data='k=2;')
     self.assertEqual(list(out), self.solution)
예제 #33
0
 def test_gecode(self):
     out = minizinc(self.model, solver=gecode, all_solutions=True)
     self.assertEqual(len(out), 120)
예제 #34
0
 def test_minizinc(self):
     out = pymzn.minizinc(self.model,
                          data={'N': 5, 'profit': [10, 3, 9, 4, 8],
                                'size': [14, 4, 10, 6, 9],
                                'capacity': 20})
     self.assertEqual(out, [{'x': {3, 5}}])
예제 #35
0
 def _test_data_obj(self, solver):
     out = minizinc(self.model, solver=solver, data=self.data)
     self.assertEqual(list(out), self.solution)