Beispiel #1
0
def apply_freeform_two_args(caller, fn, convert, args):
    """non-public"""
    def con(a):
        if isinstance(a, type("")) or isinstance(a, type(u"")):
            return convert(a)
        else:
            return a
    if len(args) == 2:
        if isinstance(con(args[0]), type(0)) and isinstance(con(args[1]), type(0)):
            return fn(con(args[0]), con(args[1]))
        else:
            raise CplexError("apply_freeform_two_args: Wrong argument type to " + caller)
    elif len(args) == 1:
        if isinstance(args[0], type([])) or isinstance(args[0], type(())):
            retval = []
            for member in map(fn, *zip(*make_ranges(map(con, args[0])))):
                retval.extend(member)
            return retval
        if isinstance(con(args[0]), type(0)):
            return fn(con(args[0]), con(args[0]))[0]
        else:
            raise CplexError("apply_freeform_two_args: Wrong argument type to " + caller)
    elif len(args) == 0:
        return fn(0)
    else:
        raise CplexError("apply_freeform_two_args: Wrong number of arguments to " + caller)
Beispiel #2
0
def apply_freeform_one_arg(caller, fn, convert, maxval, args):
    """non-public"""
    def con(a):
        if isinstance(a, type("")):
            return convert(a)
        else:
            return a

    if len(args) == 2:
        if isinstance(con(args[0]), type(0)) and isinstance(
                con(args[1]), type(0)):
            return map(fn, range(con(args[0]), con(args[1]) + 1))
        else:
            raise CplexError(
                "apply_freeform_one_arg: Wrong argument type to " + caller)
    elif len(args) == 1:
        if isinstance(args[0], type([])) or isinstance(args[0], type(())):
            return map(fn, map(con, args[0]))
        elif isinstance(con(args[0]), type(0)):
            return fn(con(args[0]))
        else:
            raise CplexError(
                "apply_freeform_one_arg: Wrong argument type to " + caller)
    elif len(args) == 0:
        return apply_freeform_one_arg(caller, fn, convert, 0,
                                      (range(maxval), ))
    else:
        raise CplexError(
            "apply_freeform_one_arg: Wrong number of arguments to " + caller)
    def __init__(self, outputfile, env, fn=None):
        """OutputStream constructor.

        outputfile must provide methods write(self, str) and
        flush(self).

        If fn is specified, it must be a fuction with signature
        fn(str) -> str.

        """
        self._env = weakref.proxy(env)
        self._fn = fn
        if isinstance(outputfile, type("")):
            self._file = open(outputfile, "w")
        else:
            self._file = outputfile
        if self._file is not None:
            if not hasattr(self._file, "write"):
                raise CplexError("Output object must have write method")
            elif not callable(self._file.write):
                raise CplexError("Output object must have write method")
            if not hasattr(self._file, "flush"):
                raise CplexError("Output object must have flush method")
            elif not callable(self._file.flush):
                raise CplexError("Output object must have flush method")
Beispiel #4
0
    def register_callback(self, callback_class):
        """Registers a callback for use when solving.

        callback_class must be a proper subclass of one of the
        callback classes defined in the module callbacks.  It must
        override the __call__ method with a method that has signature
        __call__(self) -> None.  If callback_class is a subclass of
        more than one callback class, it will only be called when its
        first superclass is called.  register_callback returns the
        instance of callback_class registered for use.  Any previously
        registered callback of the same class will no longer be
        registered.

        """
        cb = callback_class(self)
        if cb._cb_type_string is None:
            raise CplexError(
                str(callback_class) +
                " is not a subclass of a subclassable Callback class.")
        if hasattr(cb, "_unregister"):
            if cb._cb_type_string == "branch":
                _procedural.delpydel(self._e)
            cb._cb_set_function(self._e, None)
        else:
            if cb._cb_type_string == "branch":
                _procedural.setpydel(self._e)
            setattr(self, "_" + cb._cb_type_string + "_callback", cb)
            if cb._cb_type_string == "MIP_info":
                cb._cb_set_function(self._e, self._MIP_info_callback)
            else:
                cb._cb_set_function(self._e, self)
            self._callbacks.append(cb)
        return cb
Beispiel #5
0
def validate_arg_lengths(env, caller, arg_list):
    """non-public"""
    arg_lengths = map(len, arg_list)
    max_length  = max(arg_lengths)
    for arg_length in arg_lengths:
        if arg_length != 0 and arg_length != max_length:
            raise CplexError("validate_arg_lengths: Inconsistent arguments to " + caller)
    return max_length
Beispiel #6
0
 def __init__(self, lolmat, env_lp, r_c, enc):
     """non-public"""
     self._mat = _procedural.Pylolmat_to_CHBmat(lolmat, env_lp, r_c, enc)
     if self._mat is None:
         raise MemoryError
     elif len(self._mat) == 2:
         raise CplexError(" %d: Invalid name -- '%s'\n" % tuple(self._mat))
     elif len(self._mat) == 1:
         raise TypeError(" invalid matrix input type -- ", self._mat[0])
Beispiel #7
0
    def __init__(self, ind = [], val = []):
        """Constructor for SparsePair.

        Takes two arguments, ind and val; ind specifies the indices that
        the SparsePair refers to, and val specifies the float values 
        associated with those indices; ind and val must have the same
        length.

        """
        self.ind = ind
        self.val = val
        if not self.isvalid():
            raise CplexError("Inconsistent input data to SparsePair")
Beispiel #8
0
    def __init__(self, ind1 = [], ind2 = [], val = []):
        """Constructor for SparseTriple.

        Takes three arguments, ind1, ind2 and val, specifying the
        indices that the SparseTriple refers to and the float values
        associated with those indices, respectively.  ind1, ind2, and
        val must all have the same length.

        """
        self.ind1 = ind1
        self.ind2 = ind2
        self.val  = val
        if not self.isvalid():
            raise CplexError("Inconsistent input data to SparseTriple")
 def _write_wrap(self, str_):
     try:
         self._terminate = 0
         self.write(str_)
         self.flush()
         if hasattr(self, "_error_string"):
             msg = self._error_string
             if msg is not None:
                 if not msg.startswith("CPLEX Error  1006"):
                     self._error_string = None
                     raise CplexError("ERROR", msg)
     except Exception, exc:
         self._env._callback_exception = exc
         check_status._pyenv = self._env
         self._terminate = 1
Beispiel #10
0
 def __init__(self, matrix = None):
     """non-public"""
     self.matbeg = []
     self.matind = []
     self.matval = []
     if matrix is not None:
         for vector in matrix:
             if isinstance(vector, SparsePair):
                 v0 = vector.ind
                 v1 = vector.val
             else:
                 v0 = vector[0]
                 v1 = vector[1]
             if len(v0) != len(v1):
                 raise CplexError("Inconsistent input data to _HBMatrix")
             self.matbeg.append(len(self.matind))
             self.matind.extend(v0)
             self.matval.extend(v1)
    def register_callback(self, callback_class):
        """Registers a callback for use when solving.

        callback_class must be a proper subclass of one of the
        callback classes defined in the module callbacks.  It must
        override the __call__ method with a method that has signature
        __call__(self) -> None.  If callback_class is a subclass of
        more than one callback class, it will only be called when its
        first superclass is called.  register_callback returns the
        instance of callback_class registered for use.  Any previously
        registered callback of the same class will no longer be
        registered.

        """
        cb = callback_class(self)
        if cb._cb_type_string is None:
            raise CplexError(
                str(callback_class) +
                " is not a subclass of a subclassable Callback class.")
        if hasattr(cb, "_unregister"):
            cb._cb_set_function(self._e, None)
        else:
            # Count the callbacks that are installed and require a
            # delete callback.
            num_delete = 0
            for c in self._callbacks:
                if self._needs_delete_callback(c):
                    num_delete = num_delete + 1
            old_cb = getattr(self, "_" + cb._cb_type_string + "_callback",
                             None)
            if old_cb is not None:
                self._callbacks.remove(old_cb)
            setattr(self, "_" + cb._cb_type_string + "_callback", cb)
            if cb._cb_type_string == "MIP_info":
                cb._cb_set_function(self._e, self._MIP_info_callback)
            else:
                cb._cb_set_function(self._e, self)
            self._callbacks.append(cb)
            if self._needs_delete_callback(cb) and num_delete < 1:
                # We need a delete callback and did not have one
                # before -> install it.
                _procedural.setpydel(self._e)
        return cb
Beispiel #12
0
    mip_solver.variables.set_upper_bounds([
      ("x%d"%i, 1) for i in range(input_dim) if i not in mus.union(cube)
    ])
    
    # can we make prediction of opposite class?
    if prediction == 1:
        mip_solver.variables.set_upper_bounds([("output", 0)])
        mip_solver.variables.set_lower_bounds([("output", -cplex.infinity)])
    else:
        mip_solver.variables.set_lower_bounds([("output", 0)])
        mip_solver.variables.set_upper_bounds([("output", cplex.infinity)])

    try:
        mip_solver.solve()
        if mip_solver.solution.get_status_string() == "integer infeasible":
            raise CplexError()
        # Solution found when test_feature not fixed 
        # Add it to MUS
        mus.add(test_feature)
        print("in MUS", test_feature)
    except CplexError:
        # No solution despite releasing test_feature 
        print("DROP", test_feature)

print("Found minimal explanation of",len(mus),"pixels")


plt.subplots(1,2)
plt.subplot(1,2,1)
plt.title("Original")
plt.imshow(X[test_index].reshape((28,28)), cmap='gray')