Example #1
0
    def __init__(self, f, identifier='DarkGray'):
        """
        Args:
            f (method or function):
                theoretical submodel f(self, x) or f(x) for single data point

            identifier (str, optional):
                object identifier
        """
        super().__init__(identifier=identifier, f=f)
        self._black = Black()
Example #2
0
        model(X=None, Y=None, silent=True, neurons=[], method='-l1')
        y = model(x=model.X)
        print('*' * 20)
        print('*** x:', model.x, 'y:', y)

    if 0 or ALL:
        s = 'Medium gray box model, measured Y(X) = E(mDot, p)'
        print('-' * len(s) + '\n' + s + '\n' + '-' * len(s))

        df = pd.read_csv(raw, sep=',', comment='#')
        df.rename(columns=df.iloc[0])
        df = df.apply(pd.to_numeric, errors='coerce')
        X = np.asfarray(df.loc[:, ['mDot', 'p']])
        Y = np.asfarray(df.loc[:, ['A']])

        model = Black()
        y = model(X=X, Y=Y, neurons=[], x=X)
        print('*** x:', model.x, 'y:', model.y, y)

        plotIsoMap(X.T[0], X.T[1], Y.T[0] * 1e3, title=r'$A_{prc}\cdot 10^3$')
        plotIsoMap(X.T[0], X.T[1], y.T[0] * 1e3, title=r'$A_{blk}\cdot 10^3$')
        plotIsoMap(X.T[0],
                   X.T[1], (Y.T[0] - y.T[0]) * 1e3,
                   title=r'$(A_{prc} - A_{blk})\cdot 10^3$')
        plotWireframe(X.T[0],
                      X.T[1],
                      Y.T[0] * 1e3,
                      title=r'$A_{prc}\cdot 10^3$')
        plotWireframe(X.T[0],
                      X.T[1],
                      y.T[0] * 1e3,
Example #3
0
        x, y = op(x=grid((3, 2), [-10, 0], [1, 19]), y=[0.5])
        op.plot()

    if 0 or ALL:
        s = 'Inverse operation on empirical model'
        print('-' * len(s) + '\n' + s + '\n' + '-' * len(s))

        noise_abs = 0.2
        n = 10
        X = grid(n, [-1, 5], [0, 3])

        Y_exact = White(f)(x=X)
        Y_noise = noise(Y_exact, absolute=noise_abs)

        plot_X_Y_Yref(X, Y_noise, Y_exact, ['X', 'Y_{nse}', 'Y_{exa}'])
        model = Black()
        Y_blk = model(X=X, Y=Y_noise, neurons=[8], n=3, epochs=500, x=X)
        plot_X_Y_Yref(X, Y_blk, Y_exact, ['X', 'Y_{blk}', 'Y_{exa}'])
        op = Inverse(model)
        xInv, yInv = op(y=[0.5], x=[(-10, 0), (1, 19)])
        op.plot()

    if 1 or ALL:
        s = 'Inverse operation on empirical model of tuned theoretial model'
        print('-' * len(s) + '\n' + s + '\n' + '-' * len(s))

        noise_abs = 0.1
        n = 10
        X = grid(n, [-1, 5], [0, 3])

        # synthetic training data
Example #4
0
    res = dp_in_red_mid_exp_out(v1, D1, L1, D2, L2, D3, L3, nu, rho, eps_rough,
                                c0, c1, c2, c3)
    return res[0] * 1e-6  # Pa to MPa


###############################################################################

if __name__ == '__main__':

    # model selection
    models = [
        White(f),
        LightGray(f),
        # MediumGray(f),
        DarkGray(f),
        Black()
    ]
    for model in models:
        model.silent = True
    figsize = (4, 3)  # excluding plotSurface

    # min and max number of hidden neurons for medium gray, dark gray and black
    medNrnRng, drkNrnRng, blkNrnRng = (1, 1), (2, 8), (15, 25)
    relNoise = 10e-2
    trialsLgr = 2

    # shape & ranges of train (X,Y) & test data (x,y), shape:(nPoint,nInp/nOut)
    nX, nY, xTrnRng, yTrnRng = 16 + 1, 4 + 1, [2, 10], [40,
                                                        100]  # [/ / m/s mm2/s
    nx, ny, xTstRng, yTstRng = 128 + 1, 128 + 1, [0, 12], [40, 100]
Example #5
0
class DarkGray(Model):
    """
    Dark gray box model

    Example:
        External function or method is assigned to self.f():
            def f(self, x, *args):
                c0, c1, c3 = args if len(args) > 0 else (1, 1, 1)
                y0 = c0 * x[0]*x[0] + c1 * x[1]
                y1 = x[1] * c3
                return [y0, y1]

            X = [[..], [..], ..]
            Y = [[..], [..], ..]
            x = [[..], [..], ..]

            # expanded form:
            model = DarkGray(f)
            best = model.train(X, Y, neurons=[5])
            y = model.predict(x)

            # compact form:
            y = DarkGray(f)(X=X, Y=Y, x=x, neurons=[5])
    """

    def __init__(self, f, identifier='DarkGray'):
        """
        Args:
            f (method or function):
                theoretical submodel f(self, x) or f(x) for single data point

            identifier (str, optional):
                object identifier
        """
        super().__init__(identifier=identifier, f=f)
        self._black = Black()

    @property
    def silent(self):
        return self._silent

    @silent.setter
    def silent(self, value):
        self._silent = value
        self._black._silent = value

    def train(self, X, Y, **kwargs):
        """
        see Model.train()
        """
        if X is None or Y is None:
            return None

        self.X, self.Y = X, Y
        y = Model.predict(self, self.X, **self.kwargsDel(kwargs, 'x'))
        self.best = self._black.train(np.c_[self.X, y], y-self.Y, **kwargs)

        return self.best

    def predict(self, x, **kwargs):
        """
        Executes Model, stores input x as self.x and output as self.y

        Args:
            x (2D or 1D array_like of float):
                prediction input, shape: (nPoint, nInp) or shape: (nInp,)

            kwargs (dict, optional):
                keyword arguments

        Returns:
            (2D array of float):
                prediction output, shape: (nPoint, nOut)
        """
        if x is None:
            return None
        assert self._black is not None and self._black.ready

        self.x = x
        self._y = Model.predict(self, x, **kwargs)
        self._y -= self._black.predict(np.c_[x, self._y], **kwargs)

        return self.y
Example #6
0
        y = DarkGray(f)(X=X, Y=Y, x=X, silent=True, neurons=[10])

        plotIsoMap(X[:, 0], X[:, 1], Y[:, 0], title='Y(X)')
        plotIsoMap(X[:, 0], X[:, 1], y[:, 0], title='y(X)')
        plotIsoMap(X[:, 0], X[:, 1], y[:, 0]-Y[:, 0], title='y(X)  -Y')

        print('*** X:', X.shape, 'Y:', Y.shape, 'y:', y.shape)

    if 1 or ALL:
        s = 'Black box model, measured Y(X) = E(mDot, p)'
        print('-' * len(s) + '\n' + s + '\n' + '-' * len(s))

        raw.seek(0)
        df = pd.read_csv(raw, sep=',', comment='#')
        df.rename(columns=df.iloc[0])
        df = df.apply(pd.to_numeric, errors='coerce')
        X = np.asfarray(df.loc[:, ['mDot', 'p']])
        Y = np.asfarray(df.loc[:, ['A']])

        y = Black()(X=X, Y=Y, neurons=[], silent=True, x=X)

        plotIsoMap(X.T[0], X.T[1], Y.T[0] * 1e3, title=r'$A_{prc}\cdot 10^3$')
        plotIsoMap(X.T[0], X.T[1], y.T[0] * 1e3, title=r'$A_{blk}\cdot 10^3$')
        plotIsoMap(X.T[0], X.T[1], (Y.T[0] - y.T[0]) * 1e3,
                   title=r'$(A_{prc} - A_{blk})\cdot 10^3$')
        plotWireframe(X.T[0], X.T[1], Y.T[0]*1e3, title=r'$A_{prc}\cdot 10^3$')
        plotWireframe(X.T[0], X.T[1], y.T[0]*1e3, title=r'$A_{blk}\cdot 10^3$')
        plotWireframe(X.T[0], X.T[1], (Y.T[0] - y.T[0]) * 1e3,
                      title=r'$(A_{prc} - A_{blk})\cdot 10^3$')