import numpy as np
from sklearn.base import BaseEstimator
from sklearn.feature_selection.base import SelectorMixin

class RoughSetsReducer:

    def __size(self, x):
        return (1, x.shape[0]) if x.ndim == 1 else x.shape

    '''
    Calculates indiscernibility relation
    '''
    def indisc(self, a, x):

        def codea(a, x, b):
            yy = 0
            for i in range(0, a):
                yy += x[i] * b**(a-(i+1))
            return yy

        p, q = self.__size(x)
        ap, aq = self.__size(a)
        z = [e for e in range(1, q+1)]
        tt = np.setdiff1d(z, a)
        tt_ind = np.setdiff1d(z, tt)-1
        if x.ndim == 1:
            x = x[tt_ind]
        else:
            x = x[:, tt_ind]
        y = x
        v = [codea(aq, y, 10) for i in range(0, p)] if y.ndim == 1 \
            else [codea(aq, y[i, :], 10) for i in range(0, p)]
        y = np.transpose(v)
        if y.shape[0] == 1 and len(y.shape) == 1:
            I, yy = [1], [y]
            y = np.hstack((y, I))
            b, k, l = [y], [1], [1]
        else:
            ax = 1 if y.ndim > 1 else 0
            yy = np.sort(y, axis=ax)
            I = y.argsort(axis=ax)
            y = np.hstack((yy, I))
            b, k, l = np.unique(yy, return_index=True, return_inverse=True)
        y = np.hstack((l, I))
        m = np.max(l)
        aa = np.zeros((m+1, p), dtype=int)
        for ii in range(0, m+1):
            for j in range(0, p):
                if l[j] == ii:
                    aa[ii, j] = I[j]+1
        return aa

    '''
    Calculates lower approximation set of y
    '''
    def rslower(self, y, a, T):
        z = self.indisc(a, T)
        w = []
        p, q = self.__size(z)
        for u in range(0, p):
            zz = np.setdiff1d(z[u, :], 0)
            if np.in1d(zz, y).all():
                w = np.hstack((w, zz))
        return w.astype(dtype=int)

    '''
    Calculates upper approximation set of y
    '''
    def rsupper(self, y, a, T):
        z = self.indisc(a, T)
        w = []
        p, q = self.__size(z)
        for u in range(0, p):
            zz = np.setdiff1d(z[u, :], 0)
            zzz = np.intersect1d(zz, y)
            if len(zzz) > 0:
                w = np.hstack((w, zz))
        return w.astype(dtype=int)


    def __pospq(self, p, q):
        pm, pn = self.__size(p)
        qm, qn = self.__size(q)
        num = 0
        pp, qq = [[]] * pm, [[]] * qm
        for i in range(0, pm):
            pp[i] = np.unique(p[i, :])
        for j in range(0, qm):
            qq[j] = np.unique(q[j, :])
        b = []
        for i in range(0, qm):
            for j in range(0, pm):
                if np.in1d(pp[j], qq[i]).all():
                    num += 1
                    b = np.hstack((b, pp[j]))
        bb = np.unique(b)
        if bb.size == 0:
            dd = 1
        else:
            _, dd = self.__size(bb)
        y = float(dd - 1)/pn if 0 in bb else float(dd)/pn
        b = np.setdiff1d(bb, 0)
        return y, b

    '''
    Extract core set from C to D
    '''
    def core(self, C, D):
        x = np.hstack((C, D))
        c = np.array(range(1, C.shape[1]+1))
        d = np.array([C.shape[1]+1])
        cp, cq = self.__size(c)
        q = self.indisc(d, x)
        pp = self.indisc(c, x)
        b, w = self.__pospq(pp, q)
        a, k, kk, p = ([[]] * cq for i in range(4))
        y = []
        for u in range(0, cq):
            ind = u+1
            a[u] = np.setdiff1d(c, ind)
            p[u] = self.indisc(a[u], x)
            k[u], kk[u] = self.__pospq(p[u], q)
            if k[u] != b:
                y = np.hstack((y, ind))
        return np.array(y)

    def __sgf(self, a, r, d, x):
        pr = self.indisc(r, x)
        q = self.indisc(d, x)
        b = np.hstack((r, a))
        pb = self.indisc(b, x)
        p1, _ = self.__pospq(pb, q)
        p2, _ = self.__pospq(pr, q)
        return p1 - p2

    '''
    Return the set of irreducible attributes
    '''
    def reduce(self, C, D):

        def redu2(i, re, c, d, x):
            yre = re
            re1, re2 = self.__size(re)
            q = self.indisc(d, x)
            p = self.indisc(c, x)
            pos_cd, _ = self.__pospq(p, q)
            y, j = None, None
            for qi in range(i, re2):
                re = np.setdiff1d(re, re[qi])
                red = self.indisc(re, x)
                pos_red, _ = self.__pospq(red, q)
                if np.array_equal(pos_cd, pos_red):
                    y = re
                    j = i
                    break
                else:
                    y = yre
                    j = i + 1
                    break
            return y, j

        x = np.hstack((C, D))
        c = np.array(range(1, C.shape[1]+1))
        d = np.array([C.shape[1]+1])
        y = self.core(C, D)
        q = self.indisc(d, x)
        p = self.indisc(c, x)
        pos_cd, _ = self.__pospq(p, q)
        re = y
        red = self.indisc(y, x)
        pos_red, _ = self.__pospq(red, q)
        while pos_cd != pos_red:
            cc = np.setdiff1d(c, re)
            c1, c2 = self.__size(cc)
            yy = [0] * c2
            for i in range(0, c2):
                yy[i] = self.__sgf(cc[i], re, d, x)
            cd = np.setdiff1d(c, y)
            d1, d2 = self.__size(cd)
            for i in range(d2, c2, -1):
                yy[i] = []
            ii = np.argsort(yy)
            for v1 in range(c2-1, -1, -1):
                v2 = ii[v1]
                re = np.hstack((re, cc[v2]))
                red = self.indisc(re, x)
                pos_red, _ = self.__pospq(red, q)
        re1, re2 = self.__size(re)
        core = y
        for qi in range(re2-1, -1, -1):
            if re[qi] in core:
                y = re
                break
            re = np.setdiff1d(re, re[qi])
            red = self.indisc(re, x)
            pos_red, _ = self.__pospq(red, q)
            if np.array_equal(pos_cd, pos_red):
                y = re
        y1, y2 = self.__size(y)
        j = 0
        for i in range(0, y2):
            y, j = redu2(j, y, c, d, x)
        return y

class RoughSetsSelector(BaseEstimator, SelectorMixin):

    def _get_support_mask(self):
        return self.mask_

    def fit(self, X, y=None):
        # Missing values are not supported yet!
        if np.isnan(X).any():
            raise ValueError("X must not contain any missing values")
        if np.isnan(y).any():
            raise ValueError("y must not contain any missing values")
        # Check that X and Y contains only integer values
        if not np.all(np.equal(np.mod(X, 1), 0)):
            raise ValueError("X must contain only integer values")
        if not np.all(np.equal(np.mod(y, 1), 0)):
            raise ValueError("y must contain only integer values")

        reducer = RoughSetsReducer()
        selected_ = reducer.reduce(X, y)
        B_unique_sorted, B_idx = np.unique(np.array(range(X.shape[1])), return_index=True)
        B_unique_sorted = B_unique_sorted + 1  # Shift elements by one, as RS index array starts by one
        self.mask_ = np.in1d(B_unique_sorted, selected_, assume_unique=True)

        if self.mask_.size == 0:
            raise ValueError("No features were selected by rough sets reducer")
        return self

y = np.array([[1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]]).T
X = np.array([[1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1],
              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              [1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0],
              [0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1],
              [1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0],
              [0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1],
              [1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1],
              [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1],
              [1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1],
              [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1],
              [1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1],
              [1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1]])

selector = RoughSetsSelector()
X_selected = selector.fit(X, y).transform(X)
print(X_selected) 

Python Online Compiler

Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.

Taking inputs (stdin)

OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.

import sys
name = sys.stdin.readline()
print("Hello "+ name)

About Python

Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.

Tutorial & Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition IF-ELSE is used.

if conditional-expression
    #code
elif conditional-expression
    #code
else:
    #code

Note:

Indentation is very important in Python, make sure the indentation is followed correctly

2. For:

For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.

Example:

mylist=("Iphone","Pixel","Samsung")
for i in mylist:
    print(i)

3. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while condition  
    #code 

Collections

There are four types of collections in Python.

1. List:

List is a collection which is ordered and can be changed. Lists are specified in square brackets.

Example:

mylist=["iPhone","Pixel","Samsung"]
print(mylist)

2. Tuple:

Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.

Example:

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)

Below throws an error if you assign another value to tuple again.

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)

3. Set:

Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.

Example:

myset = {"iPhone","Pixel","Samsung"}
print(myset)

4. Dictionary:

Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.

Example:

mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11"
}
print(mydict)

Supported Libraries

Following are the libraries supported by OneCompiler's Python compiler

NameDescription
NumPyNumPy python library helps users to work on arrays with ease
SciPySciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation
SKLearn/Scikit-learnScikit-learn or Scikit-learn is the most useful library for machine learning in Python
PandasPandas is the most efficient Python library for data manipulation and analysis
DOcplexDOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling