Пример #1
0
def UQTkEvaluatePCE(pc_model, pc_coeffs, samples):
    """
    Evaluate PCE at a set of samples of this PCE
    Input:
        pc_model:   PC object with into about PCE
        pc_coeffs:  1D numpy array with PC coefficients of the RV to be evaluated. [npce]
        samples:    2D numpy array with samples of the PCE at which the RV
                    are to be evaluated. Each line is one sample. [n_samples, ndim]
    Output:
        1D Numpy array with PCE evaluations
    """

    #need a 1d array passed into pc_coeffs
    if (len(pc_coeffs.shape) != 1):
        print(
            "UQTkEvaluatePCE only takes one PCE. pc_coeff needs to be 1 dimension."
        )
        exit(1)

    # Get data set dimensions etc.
    n_test_samples = samples.shape[0]
    ndim = samples.shape[1]
    npce = pc_model.GetNumberPCTerms()

    # Put PC samples in a UQTk array
    std_samples_uqtk = uqtkarray.dblArray2D(n_test_samples, ndim)
    std_samples_uqtk.setnpdblArray(np.asfortranarray(samples))

    # Create and fill UQTk array for PC coefficients
    c_k_1d_uqtk = uqtkarray.dblArray1D(npce, 0.0)
    for ip in range(npce):
        c_k_1d_uqtk[ip] = pc_coeffs[ip]

    # Create UQTk array to store outputs in
    rv_from_pce_uqtk = uqtkarray.dblArray1D(n_test_samples, 0.0)

    # Evaluate the PCEs for reach input RV at those random samples
    pc_model.EvalPCAtCustPoints(rv_from_pce_uqtk, std_samples_uqtk,
                                c_k_1d_uqtk)

    # Numpy array to store all RVs evaluated from sampled PCEs
    rvs_sampled = np.zeros((n_test_samples, ))

    # Put evaluated samples in full 2D numpy array
    for isamp in range(n_test_samples):
        rvs_sampled[isamp] = rv_from_pce_uqtk[isamp]

    # return numpy array of PCE evaluations
    return rvs_sampled
Пример #2
0
def transf_coeffs_xi(coeffs,
                     nord,
                     ndim,
                     pc_type,
                     param,
                     R,
                     sf="sparse",
                     pc_alpha=0.0,
                     pc_beta=1.0):
    '''
    Transfer coefficient from eta-space to xi-space to check convergence
    eta-space is the current dimension-reduced space, while
    xi-space is the full dimension expansion space.
    Dimension of Eta is equal to dimension of Xi
    Inputs:
        coeffs: N dimensional numpy array (N is the # of PC terms of ndim dimensional expansion),
                coefficients in eta space
    Output:
        N dimensional numpy array, coefficients projected to xi space
    this function is only used to check the accuracy of adaptation method
    '''

    ##### obtain pc_model of eta space and xi space #####
    pc_model_eta = uqtkpce.PCSet("NISP", nord, ndim, pc_type, pc_alpha,
                                 pc_beta)
    pc_model_xi = uqtkpce.PCSet("NISP", nord, ndim, pc_type, pc_alpha, pc_beta)
    if ndim == 1:
        pc_model_eta.SetQuadRule(pc_type, 'full', param)
        pc_model_xi.SetQuadRule(pc_type, 'full', param)
    else:
        pc_model_eta.SetQuadRule(pc_type, sf, param)
        pc_model_xi.SetQuadRule(pc_type, sf, param)
    qdpts_eta, totquat_eta = pce_tools.UQTkGetQuadPoints(pc_model_eta)

    ##### Obtain Psi_xi at quadrature points of eta #####
    qdpts_xi = eta_to_xi_mapping(qdpts_eta, R)
    qdpts_xi_uqtk = uqtkarray.dblArray2D(totquat_eta, ndim)
    qdpts_xi_uqtk.setnpdblArray(np.asfortranarray(qdpts_xi))

    psi_xi_uqtk = uqtkarray.dblArray2D()
    pc_model_xi.EvalBasisAtCustPts(qdpts_xi_uqtk, psi_xi_uqtk)
    psi_xi = np.zeros((totquat_eta, pc_model_xi.GetNumberPCTerms()))
    psi_xi_uqtk.getnpdblArray(psi_xi)

    ##### Obtian Psi_eta at quadrature points of eta #####
    weight_eta_uqtk = uqtkarray.dblArray1D()
    pc_model_eta.GetQuadWeights(weight_eta_uqtk)
    weight_eta = np.zeros((totquat_eta, ))
    weight_eta_uqtk.getnpdblArray(weight_eta)

    psi_eta_uqtk = uqtkarray.dblArray2D()
    pc_model_eta.GetPsi(psi_eta_uqtk)
    psi_eta = np.zeros((totquat_eta, pc_model_eta.GetNumberPCTerms()))
    psi_eta_uqtk.getnpdblArray(psi_eta)

    return np.dot(coeffs, np.dot(psi_eta.T * weight_eta, psi_xi))
Пример #3
0
def UQTkDrawSamplesPCE(pc_model, pc_coeffs, n_samples):
    """
    Draw samples of the germ underneath the pc_model and evaluates one PCE
    for those samples.

    Input:
        pc_model:   PC object with into about PCE
        pc_coeffs:  1D numpy array with PC coefficients of the RV to be evaluated. [n_dim]
        n_samples:    number of samples to be drawn
    Output:
        1D Numpy array with PCE evaluations

    """

    #need a 1d array passed into pc_coeffs
    if (len(pc_coeffs.shape) != 1):
        print(
            "UQTkEvaluatePCE only takes one PCE. pc_coeff needs to be 1 dimension."
        )
        exit(1)

    #get number of nTerms
    npce = pc_model.GetNumberPCTerms()

    # Create and fill UQTk array for PC coefficients
    p = uqtkarray.dblArray1D(npce, 0.0)
    for ip in range(npce):
        p[ip] = pc_coeffs[ip]

    #create UQTk array to store outputs in
    samples = uqtkarray.dblArray1D(n_samples, 0.0)

    #draw the samples
    pc_model.DrawSampleSet(p, samples)

    #convert samples to a numpy array
    pce_samples = np.zeros(n_samples)
    for isamp in range(n_samples):
        pce_samples[isamp] = samples[isamp]

    #return samples in numpy array
    return pce_samples
Пример #4
0
def UQTkGalerkinProjection(pc_model, f_evaluations):
    """
    Obtain PC coefficients by Galerkin Projection via UQTk

    Note: need to generalize this to allow projecting multiple variables at the time

    Input:
        pc_model : PC object with info about basis to project on
        f_evaluations: 1D numpy array (vector) with function to be projected,
                       evaluated at the quadrature points
    Output:
        1D Numpy array with PC coefficients
    """

    # Get parameters
    if len(f_evaluations.shape) > 1:
        print("This function can only project single variables for now")
        exit(1)

    npce = pc_model.GetNumberPCTerms()
    nqp = f_evaluations.shape[0]  # Number of quadrature points

    # UQTk array for PC coefficients for one variable
    c_k_1d_uqtk = uqtkarray.dblArray1D(npce, 0.0)

    # UQTk array for function evaluations at quadrature points for that variable
    f_uqtk = uqtkarray.dblArray1D(nqp, 0.0)
    for ipt in range(nqp):
        f_uqtk[ipt] = f_evaluations[ipt]

    # Galerkin Projection
    pc_model.GalerkProjection(f_uqtk, c_k_1d_uqtk)

    # Put PC coefficients in numpy array
    c_k = np.zeros(npce)
    for ip in range(npce):
        c_k[ip] = c_k_1d_uqtk[ip]

    # Return numpy array of PC coefficients
    return c_k
Пример #5
0
def UQTkStDv(pc_model, pc_coeffs):
    """
    Compute Standard Deviation of a PCE through UQTk
    Input:
        pc_model: PC object with info about PCE
        pc_coeffs: 1D numpy array with PCE coefficients
    Output:
        pc_stdv: Standard Deviation of the PCE
    """

    # Info about PCE
    n_pce = pc_model.GetNumberPCTerms()

    # Create and fill UQTk array for PC coefficients
    c_k_1d_uqtk = uqtkarray.dblArray1D(n_pce, 0.0)
    for ip in range(n_pce):
        c_k_1d_uqtk[ip] = pc_coeffs[ip]

    pc_stdv = pc_model.StDv(c_k_1d_uqtk)

    return pc_stdv
Пример #6
0
def UQTkMap2PCE(pc_model, rvs_in, verbose=0):
    """Obtain PC representation for the random variables that are described by samples.
    Employ a Rosenblatt transformation to build a map between the input RVs and the space
    of the PC germ.
    Input:
        pc_model: object with properties of the PCE to be constructed
        rvs_in    : numpy array with input RV samples. Each line is a sample. The columns
                  represent the dimensions of the input RV.
        verbose : verbosity level (more output for higher values)

    Output:
        Numpy array with PC coefficients for each RV in the original rvs_in input
    """

    # Dimensionality and number of samples of input RVs
    ndim = rvs_in.shape[1]
    nsamp = rvs_in.shape[0]

    # Algorithm parameters
    bw = -1  # KDE bandwidth for Rosenblatt (on interval 0.1)
    iiout = 50  # interval for output to screen

    # Number of PCE terms
    npce = pc_model.GetNumberPCTerms()

    # Get the default quadrature points
    qdpts = uqtkarray.dblArray2D()
    pc_model.GetQuadPoints(qdpts)

    totquat = pc_model.GetNQuadPoints()
    print("Total number of quadrature points =", totquat)

    # Set up transpose of input data for the inverse Rosenblatt transformation in a UQTk array
    ydata_t = uqtkarray.dblArray2D(ndim, nsamp)
    ydata_t.setnpdblArray(np.asfortranarray(rvs_in.T))

    # Set up numpy array for mapped quadrature points
    invRosData = np.zeros((totquat, ndim))

    # Map all quadrature points in chosen PC set to the distribution given by the data
    # using the inverse Rosenblatt transformation
    for ipt in range(totquat):

        # print("Converting quadrature point #",ipt)

        # Set up working arrays
        quadunif = uqtkarray.dblArray1D(ndim, 0.0)
        invRosData_1s = uqtkarray.dblArray1D(ndim, 0.0)

        # First map each point to uniform[0,1]
        # PCtoPC maps to [-1,1], which then gets remapped to [0,1]
        for idim in range(ndim):
            quadunif[idim] = (uqtktools.PCtoPC(
                qdpts[ipt, idim], pc_model.GetPCType(), pc_model.GetAlpha(),
                pc_model.GetBeta(), "LU", 0.0, 0.0) + 1.0) / 2.0

        # Map each point from uniform[0,1] to the distribution given by the original samples via inverse Rosenblatt
        if bw > 0:
            uqtktools.invRos(quadunif, ydata_t, invRosData_1s, bw)
        else:
            uqtktools.invRos(quadunif, ydata_t, invRosData_1s)

        # Store results
        for idim in range(ndim):
            invRosData[ipt, idim] = invRosData_1s[idim]

        # Screen diagnostic output
        if ((ipt + 1) % iiout == 0) or ipt == 0 or (ipt + 1) == totquat:
            print("Inverse Rosenblatt for Galerkin projection:", (ipt + 1),
                  "/", totquat, "=", (ipt + 1) * 100 / totquat, "% completed")

    # Get PC coefficients by Galerkin projection
    # Set up numpy array for PC coefficients (one column for each transformed random variable)
    c_k = np.zeros((npce, ndim))

    # Project each random variable one by one
    # Could replace some of this with the UQTkGalerkinProjection function below
    for idim in range(ndim):

        # UQTk array for PC coefficients for one variable
        c_k_1d = uqtkarray.dblArray1D(npce, 0.0)

        # UQTk array for map evaluations at quadrature points for that variable
        invRosData_1d = uqtkarray.dblArray1D(totquat, 0.0)
        # invRosData_1d.setnpdblArray(np.asfortranarray(invRosData[:,idim])
        for ipt in range(totquat):
            invRosData_1d[ipt] = invRosData[ipt, idim]

        # Galerkin Projection
        pc_model.GalerkProjection(invRosData_1d, c_k_1d)

        # Put coefficients in full array
        for ip in range(npce):
            c_k[ip, idim] = c_k_1d[ip]

    # Return numpy array of PC coefficients
    return c_k
Пример #7
0
[7.745966692414834043e-01, -9.061798459386638527e-01],
[7.745966692414834043e-01, -7.745966692414832933e-01],
[7.745966692414834043e-01, -5.384693101056832187e-01],
[7.745966692414834043e-01, 0.000000000000000000e+00],
[7.745966692414834043e-01, 5.384693101056829967e-01],
[7.745966692414834043e-01, 7.745966692414834043e-01],
[7.745966692414834043e-01, 9.061798459386638527e-01],
[8.360311073266353254e-01, 0.000000000000000000e+00],
[9.061798459386638527e-01, -7.745966692414832933e-01],
[9.061798459386638527e-01, 0.000000000000000000e+00],
[9.061798459386638527e-01, 7.745966692414834043e-01],
[9.681602395076263079e-01, 0.000000000000000000e+00]])

# initiate uqtk arrays for quad points and weights
x = uqtkarray.dblArray2D()
w = uqtkarray.dblArray1D()

# create instance of quad class and output
# points and weights
print('Create an instance of Quad class')
ndim = 2
level = 3
q = uqtkquad.Quad('LU','sparse',ndim,level,0,1)
print('Now set and get the quadrature rule...')
q.SetRule()
q.GetRule(x,w)

# print out x and w
print('Displaying the quadrature points and weights:\n')
x_np = uqtk2numpy(x)
print(x_np)
Пример #8
0
		# check if compiled
		self.__compiled = False
		self.compile()

		self.__cv_flag = False

	def compile(self,l_init=0.0,adaptive=0,optimal=1,scale=.1,verbose=0):
		'''
		Setting up variables for the BCS algorithm. Most of the variables do not need to be set. Default settings are sufficient for more cases. See the C++ code for more information about variables.
		'''
		# now we begin BCS routine
		# set work variables
		self.__newmindex_uqtk = uqtkarray.intArray2D() # for uporder iteration
		self.__sigma2_p = uqtktools.new_doublep() # initial noise variance
		self.__lambda_init = uqtkarray.dblArray1D() # hierarchical prior parameter
		self.__adaptive, self.__optimal, self.__scale, self.__verbose = adaptive,optimal,scale,verbose
		self.__weights_uqtk = uqtkarray.dblArray1D() # weights/ coefficients for basis
		self.__used_uqtk = uqtkarray.intArray1D() # index of weights retained (nonzero)
		self.__errbars_uqtk = uqtkarray.dblArray1D() # error bars for each weight
		self.__nextbasis_uqtk = uqtkarray.dblArray1D() # if adaptive
		self.__alpha_uqtk = uqtkarray.dblArray1D() # prior hyperparameter (1/gamma)
		self.__lambda_p = uqtktools.new_doublep()

		uqtktools.doublep_assign(self.__lambda_p,l_init)

		self.__compiled = True

	def leastsq(self,X,y):
		'''
		perform simple least squares based on the original
Пример #9
0
# try to import uqtk array library and 
# functions to convert between uqtk and numpy arrays
try:
	import uqtkarray
	from uqtkarray import numpy2uqtk
	from uqtkarray import uqtk2numpy
except ImportError:
	print "PyUQTk array module not found"
	print "If installing in a directory other than the build directory, make sure PYTHONPATH includes the install directory"

import unittest

''' Test converting 1d numpy array to 1d uqtk array '''
# create 1d array
N = 35
x = uqtkarray.dblArray1D(N,0)

# create 1d numpy array
x_np = random.randn(N)

# set uqtk array to numpy array
x.setnpdblArray(x_np)

# test to make sure array elements are the same
for i in range(N):
	assert x[i] == x_np[i]

''' Test converting 2d numpy array to 2d uqtk array '''
# create 2d array in uqtk
m = 100
n = 3