Ejemplo n.º 1
0
def DOGS_standlone():
    print('==================================================')

    current_path = os.path.dirname(
        os.path.abspath(inspect.getfile(inspect.currentframe())))

    pre_opt = current_path + "/allpoints/pre_opt_IC.mat"
    pre_opt_path = Path(pre_opt)

    pre_Y = current_path + "/allpoints/Yall.mat"
    pre_Y_path = Path(pre_Y)

    pre_J = current_path + "/allpoints/surr_J_new.dat"
    pre_J_path = Path(pre_J)
    # Check whether or not it is the first iteraiton, if the optimizaton information file pre_opt_IC doesn't exist, then
    # generate that file:
    if not pre_opt_path.is_file():
        Initialize_IC()

    var_opt = io.loadmat("allpoints/pre_opt_IC")
    k = var_opt['iter'][0, 0]
    flag = var_opt['flag'][0, 0]

    # initilizaiton
    if k == 0:  # k is the number of iteration. k = 0 means that the initialization is not finished.

        if pre_Y_path.is_file():  # The file 'Yall' exists.
            # Read from the previous points
            data = io.loadmat("allpoints/Yall")
            yE = data['yE'][0]
            SigmaT = data['SigmaT'][0]
            T = data['T'][0]

            # if sign == 1:
            zs = np.loadtxt("allpoints/surr_J_new.dat")
            xx = uq.data_moving_average(zs, 40).values
            ind = tr.transient_removal(xx)
            sig = np.sqrt(
                uq.stationary_statistical_learning_reduced(xx[ind:], 18)[0])
            t = len(
                zs)  # not needed for Alpha-DOGS  # TODO fix the length of data
            J = np.abs(np.mean(xx[ind:]))

            yE = np.hstack((yE, J))
            SigmaT = np.hstack((SigmaT, sig))
            T = np.hstack((T, t))

            data = {'yE': yE, 'SigmaT': SigmaT, 'T': T}
            io.savemat("allpoints/Yall", data)

            print(' len of yE = ', len(yE))

        else:
            if not pre_J_path.is_file():
                # The very first iteration, the file 'Yall' doesn't exist.
                yE = np.array([])
                print("The first time running the iteration")
                print(' len of yE = ', len(yE))
                print('iter k = ', k)
            else:
                # The second time of running the algorithm.
                yE = np.array([])
                SigmaT = np.array([])
                T = np.array([])

                # Read from surr_J_new.
                zs = np.loadtxt("allpoints/surr_J_new.dat")

                xx = uq.data_moving_average(zs, 40).values
                ind = tr.transient_removal(xx)
                sig = np.sqrt(
                    uq.stationary_statistical_learning_reduced(xx[ind:],
                                                               18)[0])
                t = len(zs)  # not needed for Alpha-DOGS
                J = np.abs(np.mean(xx[ind:]))

                yE = np.hstack((yE, J))
                SigmaT = np.hstack((SigmaT, sig))
                T = np.hstack((T, t))  # not needed for Alpha-DOGS
                data = {'yE': yE, 'SigmaT': SigmaT, 'T': T}
                io.savemat("allpoints/Yall", data)

                print("The second time running the iteration")
                print(' len of yE = ', len(yE))
                print('iter k = ', k)
                print('function evaluation at this iteration: ', J)

        # we read pre_opt_IC.mat
        # untill len(yE) < n+1 then k=1
        # var_opt = io.loadmat("allpoints/pre_opt_IC")
        # The following variables are needed for initialization:

        xE = var_opt['xE']
        n = var_opt['n'][0, 0]

        if len(yE) < xE.shape[1]:
            # Generate the point that we want to evaluate.
            xcurr = np.copy(xE[:, len(yE)])
            fout = open("allpoints/pts_to_eval.dat", 'w')
            keywords = ['Awin', 'lambdain', 'fanglein']
            fout.write(str('flagin') + '=' + str(int(flag)) + "\n")
            fout.write(str('IDin') + '=' + str(int(len(yE))) + "\n")
            for j in range(n):
                fout.write(keywords[j] + '=' + str(float(xcurr[j])) + "\n")
            fout.close()

            var_opt['iter'] = 0
            var_opt['num_point'] = len(yE)
            io.savemat("allpoints/pre_opt_IC", var_opt)

            print('point to eval at this iteration x = ', xcurr)
            print('len of yE = ', len(yE))

            return
        else:

            # Initialization complete
            var_opt['iter'] = 1
            io.savemat("allpoints/pre_opt_IC", var_opt)
            # Run one iteration after initialization.
            if pre_J_path.is_file():
                dogs.DOGS_standalone_IC()
                os.remove(current_path + "/allpoints/surr_J_new.dat")
                return
            else:
                return

    else:
        if pre_J_path.is_file(
        ):  # If surr_J_new exists, function evaluation is succeeded.
            dogs.DOGS_standalone_IC()
            var_opt = io.loadmat("allpoints/pre_opt_IC")
            flag = var_opt['flag'][0, 0]
            if flag != 2:  # If flag == 2, mesh refinement, perform one more iteration.
                os.remove(current_path + "/allpoints/surr_J_new.dat")
            return
        else:  # function evaluation is failed, reperform functon evaluation
            return
Ejemplo n.º 2
0
def __main___:

    n = 3  # Dimension of data
    K = 3  # Tuning parameter for continuous search function
    Nm = 8  # Initial mesh grid size
    L = 1  # Tuning parameter for discrete search function
    flag = 1  # Identify
    method = "NPS"  # The strategy for regression function, you can choose NPS or MAPS
    user = '******'
    # fe_times = np.array([])  # Represents the times of function evaluation at this point.

    # The following lines represents the initial points:
    # bnd1: lower bounds for physical data
    # bnd2: upper bounds for physical data
    # xE: initial interested points
    # y0: estimate value for minimum
    if n == 1:
        xE = np.array([[0.5, 0.75]])
        bnd2 = np.array([30])
        bnd1 = np.array([24])

    elif n == 2:
        xE = np.array([[0.5, 0.75, 0.5], [0.5, 0.5, 0.75]])
        bnd2 = np.array([30, 30])
        bnd1 = np.array([24, 24])
    elif n == 3:
        xE = np.array([[0.5, 0.5, 0.5, 0.75], [0.5, 0.5, 0.75, 0.5], [0.5, 0.75, 0.5, 0.5]])
        bnd2 = np.array([30, 30, 30])
        bnd1 = np.array([24, 24, 24])

    xU = dogs.bounds(np.zeros([n, 1]), np.ones([n, 1]), n)

    xE = dogs.physical_bounds(xE, bnd1, bnd2)
    xU = dogs.physical_bounds(xU, bnd1, bnd2)

    k = 0  # times of iteration, start with 0
    iter_max = 50  # maximum iteration steps
    idx = 0

    print('==================================================')

    current_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))

    pre_opt = current_path + "/allpoints/pre_opt_IC.mat"
    pre_opt_path = Path(pre_opt)

    pre_Y = current_path + "/allpoints/Yall.mat"
    pre_Y_path = Path(pre_Y)

    pre_J = current_path + "/allpoints/surr_J_new.dat"
    pre_J_path = Path(pre_J)
    # Check whether or not it is the first iteraiton, if the optimizaton information file pre_opt_IC doesn't exist, then
    # generate that file:

    var_opt = io.loadmat("allpoints/pre_opt_IC")
    k = var_opt['iter'][0, 0]
    flag = var_opt['flag'][0, 0]

    # initilizaiton
    if k == 0:  # k is the number of iteration. k = 0 means that the initialization is not finished.

        if pre_Y_path.is_file():  # The file 'Yall' exists.
            # Read from the previous points
            data = io.loadmat("allpoints/Yall")
            yE = data['yE'][0]
            SigmaT = data['SigmaT'][0]
            T = data['T'][0]

            # if sign == 1:
            zs = np.loadtxt("allpoints/surr_J_new.dat")
            xx = uq.data_moving_average(zs, 40).values
            ind = tr.transient_removal(xx)
            sig = np.sqrt(uq.stationary_statistical_learning_reduced(xx[ind:], 18)[0])
            t = len(zs)  # not needed for Alpha-DOGS  # TODO fix the length of data
            J = np.abs(np.mean(xx[ind:]))

            yE = np.hstack((yE, J))
            SigmaT = np.hstack((SigmaT, sig))
            T = np.hstack((T, t))

            data = {'yE': yE, 'SigmaT': SigmaT, 'T': T}
            io.savemat("allpoints/Yall", data)

            print(' len of yE = ', len(yE))

        else:
            if not pre_J_path.is_file():
                # The very first iteration, the file 'Yall' doesn't exist.
                yE = np.array([])
                print("The first time running the iteration")
                print(' len of yE = ', len(yE))
                print('iter k = ', k)
            else:
                # The second time of running the algorithm.
                yE = np.array([])
                SigmaT = np.array([])
                T = np.array([])

                # Read from surr_J_new.
                zs = np.loadtxt("allpoints/surr_J_new.dat")

                xx = uq.data_moving_average(zs, 40).values
                ind = tr.transient_removal(xx)
                sig = np.sqrt(uq.stationary_statistical_learning_reduced(xx[ind:], 18)[0])
                t = len(zs)  # not needed for Alpha-DOGS
                J = np.abs(np.mean(xx[ind:]))

                yE = np.hstack((yE, J))
                SigmaT = np.hstack((SigmaT, sig))
                T = np.hstack((T, t))  # not needed for Alpha-DOGS
                data = {'yE': yE, 'SigmaT': SigmaT, 'T': T}
                io.savemat("allpoints/Yall", data)

                print("The second time running the iteration")
                print(' len of yE = ', len(yE))
                print('iter k = ', k)
                print('function evaluation at this iteration: ', J)

        # we read pre_opt_IC.mat
        # untill len(yE) < n+1 then k=1
        # var_opt = io.loadmat("allpoints/pre_opt_IC")
        # The following variables are needed for initialization:

        xE = var_opt['xE']
        n = var_opt['n'][0, 0]

        if len(yE) < xE.shape[1]:
            # Generate the point that we want to evaluate.
            xcurr = np.copy(xE[:, len(yE)])
            fout = open("allpoints/pts_to_eval.dat", 'w')
            keywords = ['Awin', 'lambdain', 'fanglein']
            fout.write(str('flagin') + '=' + str(int(flag)) + "\n")
            fout.write(str('IDin') + '=' + str(int(len(yE))) + "\n")
            for j in range(n):
                fout.write(keywords[j] + '=' + str(float(xcurr[j])) + "\n")
            fout.close()

            var_opt['iter'] = 0
            var_opt['num_point'] = len(yE)
            io.savemat("allpoints/pre_opt_IC", var_opt)

            print('point to eval at this iteration x = ', xcurr)
            print('len of yE = ', len(yE))

            return
        else:

            # Initialization complete
            var_opt['iter'] = 1
            io.savemat("allpoints/pre_opt_IC", var_opt)
            # Run one iteration after initialization.
            if pre_J_path.is_file():
                dogs.DOGS_standalone_IC()
                os.remove(current_path + "/allpoints/surr_J_new.dat")
                return
            else:
                return

    else:
        if pre_J_path.is_file():  # If surr_J_new exists, function evaluation is succeeded.
            dogs.DOGS_standalone_IC()
            var_opt = io.loadmat("allpoints/pre_opt_IC")
            flag = var_opt['flag'][0, 0]
            if flag != 2:  # If flag == 2, mesh refinement, perform one more iteration.
                os.remove(current_path + "/allpoints/surr_J_new.dat")
            return
        else:  # function evaluation is failed, reperform functon evaluation
            return
Ejemplo n.º 3
0
def DOGS_standlone():
    print('==================================================')

    current_path = os.path.dirname(
        os.path.abspath(inspect.getfile(inspect.currentframe())))

    pre_opt = current_path + "/allpoints/pre_opt_IC.mat"
    pre_opt_path = Path(pre_opt)

    pre_Y = current_path + "/allpoints/Yall.mat"
    pre_Y_path = Path(pre_Y)

    pre_J = current_path + "/allpoints/surr_J_new.dat"
    pre_J_path = Path(pre_J)
    # Check whether or not it is the first iteraiton, if the optimizaton information file pre_opt_IC doesn't exist, then
    # generate that file:
    if not pre_opt_path.is_file():
        Initialize_IC()

    var_opt = io.loadmat("allpoints/pre_opt_IC")
    k = var_opt['iter'][0, 0]
    idx = var_opt['num_point'][0, 0]
    flag = var_opt['flag'][0, 0]
    # fe_times = var_opt['fe_times']

    # initilizaiton
    if k == 0:  # k is the number of iteration. k = 0 means that the initialization is not finished.

        if pre_Y_path.is_file():  # The file 'Yall' exists.
            # sign = dogs.function_evaluation_sign()
            # read the previous points
            data = io.loadmat("allpoints/Yall")
            yE = data['yE'][0]
            SigmaT = data['SigmaT'][0]
            T = data['T'][0]

            # if sign == 1:
            zs = np.loadtxt("allpoints/surr_J_new.dat")
            xx = uq.data_moving_average(zs, 40).values
            ind = tr.transient_removal(xx)
            sig = np.sqrt(
                uq.stationary_statistical_learning_reduced(xx[ind:], 18)[0])
            t = len(zs)  # not needed for Alpha-DOGS
            J = np.abs(np.mean(xx[ind:]))

            yE = np.hstack((yE, J))
            SigmaT = np.hstack((SigmaT, sig))
            T = np.hstack((T, t))
            # fe_times = np.hstack((fe_times, 1))

            data = {'yE': yE, 'SigmaT': SigmaT, 'T': T}
            io.savemat("allpoints/Yall", data)

            print(' len of yE = ', len(yE))

            # elif sign == 0 and fe_times[idx] == 3:
            #     # Already performed 3 function evaluation, set this point to be inf.
            #     yE = np.hstack((yE, np.inf))
            #     SigmaT = np.hstack((SigmaT, 0))
            #     T = np.hstack((T, 1))
            #
            #     data = {'yE': yE, 'SigmaT': SigmaT, 'T': T}
            #     io.savemat("allpoints/Yall", data)
            #
            # elif sign == 0 and fe_times[idx] < 3:
            #     fe_times[idx] += 1
            #     var_opt['fe_times'] = fe_times
            #     io.savemat("allpoints/pre_opt_IC", var_opt)
            #
            #     return

        else:
            if not pre_J_path.is_file():
                # The very first iteration, the file 'Yall' doesn't exist.
                yE = np.array([])
                # fe_times = np.array([])
                print("The first time running the iteration")
                print(' len of yE = ', len(yE))
                print('iter k = ', k)
            else:
                # The second time of running the algorithm.
                # First check the function evaluation is successful or not:
                # sign = dogs.function_evaluation_sign()
                # if sign == 1:
                yE = np.array([])
                SigmaT = np.array([])
                T = np.array([])

                # Read from surr_J_new.
                zs = np.loadtxt("allpoints/surr_J_new.dat")

                xx = uq.data_moving_average(zs, 40).values
                ind = tr.transient_removal(xx)
                sig = np.sqrt(
                    uq.stationary_statistical_learning_reduced(xx, 18)[0])
                t = len(zs)  # not needed for Alpha-DOGS
                J = np.abs(np.mean(xx[ind:]))

                yE = np.hstack((yE, J))
                SigmaT = np.hstack((SigmaT, sig))
                T = np.hstack((T, t))  # not needed for Alpha-DOGS
                data = {'yE': yE, 'SigmaT': SigmaT, 'T': T}
                io.savemat("allpoints/Yall", data)

                print("The second time running the iteration")
                print(' len of yE = ', len(yE))
                print('iter k = ', k)
                print('function evaluation at this iteration: ', J)
                # elif sign == 0 and fe_times[idx] == 3:
                #     # Already performed 3 function evaluation, set this point to be inf.
                #     yE = np.array([np.inf])
                #     SigmaT = np.array([0])
                #     T = np.array([1])
                #
                #     data = {'yE': yE, 'SigmaT': SigmaT, 'T': T}
                #     io.savemat("allpoints/Yall", data)
                #
                # elif sign == 0 and fe_times[idx] < 3:
                #     fe_times[idx] += 1
                #     var_opt['fe_times'] = fe_times
                #     io.savemat("allpoints/pre_opt_IC", var_opt)
                #
                #     return

        # we read pre_opt_IC.mat
        # untill len(yE) < n+1 then k=1
        # var_opt = io.loadmat("allpoints/pre_opt_IC")
        # The following variables are needed for initialization:

        xE = var_opt['xE']
        n = var_opt['n'][0, 0]

        if len(yE) < n + 1:
            # Generate the point that we want to evaluate.
            xcurr = np.copy(xE[:, len(yE)])
            fout = open("allpoints/pts_to_eval.dat", 'w')
            keywords = ['Awin', 'lambdain', 'fanglein']
            fout.write(str('flagin') + '=' + str(int(flag)) + "\n")
            fout.write(str('IDin') + '=' + str(int(len(yE))) + "\n")
            for j in range(n):
                fout.write(keywords[j] + '=' + str(float(xcurr[j])) + "\n")
            fout.close()

            # fe_times = np.hstack((fe_times, 1))
            var_opt['iter'] = 0
            var_opt['num_point'] = len(yE)
            # var_opt['fe_times'] = fe_times
            io.savemat("allpoints/pre_opt_IC", var_opt)

            print('point to eval at this iteration x = ', xcurr)
            print('len of yE = ', len(yE))

            return
        else:

            # Initialization complete
            var_opt['iter'] = 1

            io.savemat("allpoints/pre_opt_IC", var_opt)

            # The following are just for displaying:
            print('==================================================')
            print('==================================================')
            print('iter k = ', var_opt['iter'])
            # r = input('Initializtion complete, type anything to continue: ')

            # Run one iteration after initialization.
            if pre_J_path.is_file():
                dogs.DOGS_standalone_IC()
                os.remove(current_path + "/allpoints" + "/" + "surr_J_new.dat")
                return
            else:
                return

    else:
        if pre_J_path.is_file():
            # TODO: delete the surr_J_new.dat
            dogs.DOGS_standalone_IC()
            var_opt = io.loadmat("allpoints/pre_opt_IC")
            flag = var_opt['flag'][0, 0]
            if flag != 2:
                os.remove(current_path + "/allpoints" + "/" + "surr_J_new.dat")
            return
        else:
            return
Ejemplo n.º 4
0
def DOGS_standalone_IC():
    '''
    This function reads the set of evaluated points and writes them into the desired file to perform function evaluations
    Note: DOGS_standalone() only exists at the inactivated iterations.
    :return: points that needs to be evaluated
    '''
    # For future debugging, remind that xc and xd generate by DOGS_standalone() is set to be a one dimension row vector.
    # While lb and ub should be a two dimension matrix, i.e. a column vector.
    # The following lines will read input from 'pre_opt_IC' file:
    var_opt = io.loadmat("allpoints/pre_opt_IC")
    n = var_opt['n'][0, 0]
    K = var_opt['K'][0, 0]
    L = var_opt['L'][0, 0]
    Nm = var_opt['Nm'][0, 0]
    bnd2 = var_opt['ub'][0]
    bnd1 = var_opt['lb'][0]
    lb = np.zeros(n)
    ub = np.ones(n)
    user = var_opt['user'][0]
    idx = var_opt['num_point'][0, 0]
    flag = var_opt['flag'][0, 0]
    method = var_opt['inter_par_method']
    xE = var_opt['xE']
    xU = var_opt['xU']
    k = var_opt['iter'][0, 0]
    iter_max = var_opt['iter_max'][0, 0]

    if xU.shape[1] == 0:
        xU = xU.reshape(n, 0)

    Data = io.loadmat("allpoints/Yall")
    yE = Data['yE'][0]
    SigmaT = Data['SigmaT'][0]
    T = Data['T'][0]

    # Read the result from 'surr_J_new.dat' file that generated by solver_lorenz:
    if k != 1:

        zs = np.loadtxt("allpoints/surr_J_new.dat")

        xx = uq.data_moving_average(zs, 40).values
        ind = tr.transient_removal(xx)
        sig = np.sqrt(
            uq.stationary_statistical_learning_reduced(xx[ind:], 18)[0])

        J = np.abs(np.mean(xx[ind:]))

        if flag == 1:  # New point

            yE = np.hstack([yE, J])
            SigmaT = np.hstack([SigmaT, sig])
            T = np.hstack([T, len(zs)])

        elif flag == 0:  # existing point

            yE[idx] = J
            SigmaT[idx] = sig
            T[idx] = len(zs)

    #############################################################################
    # The following only for displaying information.
    # NOTICE : Deleting following lines won't cause any affect.
    print('========================  Iteration = ', k,
          '=======================================')
    print('point to evaluate at this iteration, x = ', xE[:, idx], "flag = ",
          flag)
    print(
        '==== flag 1 represents new point, 0 represents existed point  =====')
    print('Function Evaluation at this iter: y = ', yE[idx] + SigmaT[idx])
    print('Minimum of all data points(yE + SigmaT): min = ',
          np.min(yE + SigmaT))
    print('argmin: x_min = ', xE[:, np.argmin(yE + SigmaT)])
    print('Mesh size = ', Nm)
    #############################################################################
    # Normalize the bounds of xE and xU
    xE = normalize_bounds(xE, bnd1, bnd2)
    xU = normalize_bounds(xU, bnd1, bnd2)

    Ain = np.concatenate((np.identity(n), -np.identity(n)), axis=0)
    Bin = np.concatenate((np.ones((n, 1)), np.zeros((n, 1))), axis=0)
    # Calculate the Regression Function
    inter_par = Inter_par(method=method)
    [inter_par, yp] = regressionparametarization(xE, yE, SigmaT, inter_par)
    K0 = 20  # K0 = np.ptp(yE, axis=0)

    # Calculate the discrete function.
    ind_out = np.argmin(yp + SigmaT)
    sd = np.amin((yp, 2 * yE - yp), 0) - L * SigmaT

    ind_min = np.argmin(yp + SigmaT)

    yd = np.amin(sd)
    ind_exist = np.argmin(sd)

    xd = xE[:, ind_exist]

    if ind_min != ind_min:
        # yE[ind_exist] = ((fun(xd)) + yE[ind_exist] * T[ind_exist]) / (T[ind_exist] + 1)
        # T[ind_exist] = T[ind_exist] + 1

        return
    else:

        if SigmaT[ind_exist] < 0.01 * np.ptp(yE,
                                             axis=0) * (np.max(ub - lb)) / Nm:
            yd = np.inf

        # Calcuate the unevaluated support points:
        yu = np.zeros([1, xU.shape[1]])
        if xU.shape[1] != 0:
            for ii in range(xU.shape[1]):
                tmp = interpolate_val(xU[:, ii], inter_par) - np.amin(yp)
                yu[0, ii] = tmp / mindis(xU[:, ii], xE)[0]

        if xU.shape[1] != 0 and np.amin(yu) < 0:
            ind = np.argmin(yu)
            xc = np.copy(xU[:, ind])
            yc = -np.inf
            xU = scipy.delete(
                xU, ind, 1
            )  # delete the minimum element in xU, which is going to be incorporated in xE
        else:
            while 1:
                xc, yc = tringulation_search_bound_constantK(
                    inter_par, np.hstack([xE, xU]), K * K0, ind_min)
                yc = yc[0, 0]
                if interpolate_val(xc, inter_par) < min(yp):
                    xc = np.round(xc * Nm) / Nm
                    break

                else:
                    xc = np.round(xc * Nm) / Nm
                    if mindis(xc, xE)[0] < 1e-6:
                        break
                    xc, xE, xU, success, _ = points_neighbers_find(
                        xc, xE, xU, Bin, Ain)
                    xc = xc.T[0]
                    if success == 1:
                        break
                    else:
                        yu = np.hstack([
                            yu, (interpolate_val(xc, inter_par) - min(yp)) /
                            mindis(xc, xE)[0]
                        ])

            if xU.shape[1] != 0 and mindis(xc, xE)[0] > 1e-10:
                tmp = (interpolate_val(xc, inter_par) - min(yp)) / mindis(
                    xc, xE)[0]
                if np.amin(yu) < tmp:
                    ind = np.argmin(yu)
                    xc = np.copy(xU[:, ind])
                    yc = -np.inf
                    xU = scipy.delete(
                        xU, ind, 1
                    )  # delete the minimum element in xU, which is incorporated in xE
        # Generate the stop file at this iteration:
        if k + 1 <= iter_max:
            stop = 0
        elif k + 1 > iter_max:
            stop = 1

        fout = open("allpoints/stop.dat", 'w')
        fout.write(str(stop) + "\n")
        fout.close()

        # MESH REFINEMENT ITERATION:
        if mindis(xc, xE)[0] < 1e-6:
            K = 2 * K
            Nm = 2 * Nm
            L += 1
            flag = 2  # flag = 2 represents mesh refinement, in this step we don't have function evaluation.

            # Reconstruct the physical bound of xE and xU
            xE = physical_bounds(xE, bnd1, bnd2)
            xU = physical_bounds(xU, bnd1, bnd2)

            # Store the updated information about iteration to the file 'pre_opt_IC.dat'
            var_opt['K'] = K
            var_opt['Nm'] = Nm
            var_opt['L'] = L
            var_opt['xE'] = xE
            var_opt['xU'] = xU
            var_opt['num_point'] = xE.shape[
                1] - 1  # Doesn't matter, flag = 2, no function evaluation.
            var_opt['flag'] = flag
            var_opt['iter'] = k + 1
            io.savemat("allpoints/pre_opt_IC", var_opt)

            # Store the function evaluations yE, sigma and time length T:
            data = {'yE': yE, 'SigmaT': SigmaT, 'T': T}
            io.savemat("allpoints/Yall", data)

            # Generate the pts_to_eval file for solver_lorenz
            fout = open("allpoints/pts_to_eval.dat", 'w')
            if user == 'Imperial College':
                keywords = ['Awin', 'lambdain', 'fanglein']
                fout.write(str('flagin') + '=' + str(int(flag)) + "\n")
                fout.write(str('IDin') + '=' + str(int(idx)) + "\n")
                for i in range(n):
                    fout.write(str(keywords[i]) + '=' + str(xc[i]) + "\n")
            fout.close()

            return

        if yc < yd:
            if mindis(xc, xE)[0] > 1e-6:

                xE = np.concatenate([xE, xc.reshape(-1, 1)], axis=1)
                flag = 1  # new point
                idx = xE.shape[1] - 1

                # Reconstruct the physical bound of xE and xU
                xE = physical_bounds(xE, bnd1, bnd2)
                xU = physical_bounds(xU, bnd1, bnd2)
                xc = physical_bounds(xc.reshape(-1, 1), bnd1, bnd2)
                xc = xc.T[0]

                # Store the updated information about iteration to the file 'pre_opt_IC.dat'
                var_opt['K'] = K
                var_opt['Nm'] = Nm
                var_opt['L'] = L
                var_opt['xE'] = xE
                var_opt['xU'] = xU
                var_opt['num_point'] = idx
                var_opt['flag'] = flag
                var_opt['iter'] = k + 1
                io.savemat("allpoints/pre_opt_IC", var_opt)

                # Store the function evaluations yE, sigma and time length T:
                data = {'yE': yE, 'SigmaT': SigmaT, 'T': T}
                io.savemat("allpoints/Yall", data)

                # Generate the pts_to_eval file for solver_lorenz
                fout = open("allpoints/pts_to_eval.dat", 'w')
                if user == 'Imperial College':
                    keywords = ['Awin', 'lambdain', 'fanglein']
                    fout.write(str('flagin') + '=' + str(int(flag)) + "\n")
                    fout.write(str('IDin') + '=' + str(int(idx)) + "\n")
                    for i in range(n):
                        fout.write(str(keywords[i]) + '=' + str(xc[i]) + "\n")
                fout.close()

                return
        else:
            if mindis(xd, xE)[0] < 1e-10:

                flag = 0  # existing point

                # Reconstruct the physical bound of xE and xU
                xE = physical_bounds(xE, bnd1, bnd2)
                xU = physical_bounds(xU, bnd1, bnd2)
                xd = physical_bounds(xd.reshape(-1, 1), bnd1, bnd2)
                xd = xd.T[0]

                # Store the updated information about iteration to the file 'pre_opt_IC.dat'
                var_opt['K'] = K
                var_opt['Nm'] = Nm
                var_opt['L'] = L
                var_opt['xE'] = xE
                var_opt['xU'] = xU
                var_opt['num_point'] = ind_exist
                var_opt['flag'] = flag
                var_opt['iter'] = k + 1
                io.savemat("allpoints/pre_opt_IC", var_opt)

                # Store the function evaluations yE, sigma and time length T:
                data = {'yE': yE, 'SigmaT': SigmaT, 'T': T}
                io.savemat("allpoints/Yall", data)

                # Generate the pts_to_eval file for solver_lorenz
                fout = open("allpoints/pts_to_eval.dat", 'w')
                if user == 'Imperial College':
                    keywords = ['Awin', 'lambdain', 'fanglein']
                    fout.write(str('flagin') + '=' + str(int(flag)) + "\n")
                    fout.write(str('IDin') + '=' + str(int(ind_exist)) + "\n")
                    for i in range(n):
                        fout.write(str(keywords[i]) + '=' + str(xd[i]) + "\n")
                fout.close()

                return
Ejemplo n.º 5
0
def solver(x, fun_arg, flag=1):
    # the noise level
    sigma0 = 0.3
    T0 = 1
    if fun_arg == 1:  # Quadratic
        funr = lambda x: 5 * np.linalg.norm(x - 0.3)**2
        fun = lambda x: 5 * np.linalg.norm(x - 0.3
                                           )**2 + sigma0 * np.random.randn()

    elif fun_arg == 2:  # Schwefel
        funr = lambda x: -sum(
            np.multiply(500 * x, np.sin(np.sqrt(abs(500 * x))))) / 250
        fun = lambda x: -sum(
            np.multiply(500 * x, np.sin(np.sqrt(abs(500 * x))))
        ) / 250 + sigma0 * np.random.randn()
        if flag == 1:  # new point

            y = fun(x)
            T = T0
            sigmaT = sigma0 / np.sqrt(T)
            return y, sigmaT, T

        else:

            fin = open("PtsToEval/surr_J_new.dat", "r")
            T_exist = int(fin.readline())
            y_exist = float(fin.readline())
            fin.close()

            T = T_exist + T0
            y = (fun(x) + y_exist * T_exist) / T
            # UQ method...!!!!!!
            sigmaT = sigma0 / np.sqrt(T)

            return y, sigmaT, T

        # rastinginn
    elif fun_arg == 3:
        A = 3
        funr = lambda x: sum((x - 0.7)**2 - A * np.cos(2 * np.pi * (x - 0.7)))
        fun = lambda x: sum(
            (x - 0.7)**2 - A * np.cos(2 * np.pi *
                                      (x - 0.7))) + sigma0 * np.random.randn()

    elif fun_arg == 4:
        #     lorenz attractor
        var_opt = io.loadmat("allpoints/pre_opt")
        idx = var_opt['num_point'][0, 0]
        flag = var_opt['flag'][0, 0]
        bnd1 = var_opt['lb'][0]
        bnd2 = var_opt['ub'][0]
        T_lorenz = var_opt['T_lorenz'][0, 0]
        h = var_opt['h_lorenz'][0, 0]
        y0 = np.array([23.5712])
        time_method = 1
        DT = 10

        if flag == 1:  # flag 1 : new point

            J, zs, ys, xs = lorenz.lorenz_lost2(x, T_lorenz, h, bnd2, bnd1, y0,
                                                time_method)
            xx = uq.data_moving_average(zs, 40).values
            sigmaT = np.sqrt(
                uq.stationary_statistical_learning_reduced(xx, 18)[0])

            return J, zs, ys, xs, sigmaT, T_lorenz

        else:  # flag = 0: existing point

            data = io.loadmat("allpoints/pt_to_eval" + str(idx) + ".mat")
            T_zs_lorenz = data['T'][0]

            J, zs, ys, xs = lorenz.lorenz_lost2(x, T_zs_lorenz + DT, h, bnd2,
                                                bnd1, y0, time_method, idx)
            xx = uq.data_moving_average(zs, 40).values
            sigmaT = np.sqrt(
                uq.stationary_statistical_learning_reduced(xx, 18)[0])

            return J, zs, ys, xs, sigmaT, T_zs_lorenz + DT
Ejemplo n.º 6
0
A = var['A']
theta = var['theta']

fname = "data/dragdata0" + str(1) + ".dat"
zs = np.loadtxt(fname)

for ii in range(1, 12):
    print(ii)
    # go to datadrag files
    pname = os.listdir('./data')
    fname = './data/' + pname[ii]
    zs = np.loadtxt(fname)

    trans_samples = int(np.ceil(len(zs) * 0.005))
    print(trans_samples)
    xx = uq.data_moving_average(zs, trans_samples).values
    ind = tr.transient_removal(xx)

    # sig = np.sqrt(uq.stationary_statistical_learning_reduced(xx[ind:], 18)[0])
    t = len(zs)  # not needed for Alpha-DOGS
    T = np.hstack((T, t))  # not needed for Alpha-DOGS
    print("-------------------")
    print(' len of transient = ', int(ind / len(xx) * T[ii - 1]))
    print(' total  len is: ', T[ii - 1])
    J = np.abs(np.mean(xx[ind:]))

    yE = np.hstack((yE, J))
    # SigmaT = np.hstack((SigmaT, sig))

    IND = np.hstack((IND, int(ind / len(xx) * T[ii - 1])))