Example #1
0
def lagInt_1d_test():
    """
    Test Lagrange inerpolation over a 1D parameter space.
    """
    #----- SETTINGS -------------------
    nNodes = 15  #number of training samples (nodes)
    qBound = [-1, 3]  #range over which the samples are taken
    nTest = 100  #number of test points
    sampType = 'GLL'  #Type of samples, see trainSample class in samping.py
    fType = 'type1'  #Type of model function used as simulator
    #----------------------------------
    # Create the training samples and evaluate the simulator at each sample
    samps_ = sampling.trainSample(sampleType=sampType,
                                  qInfo=qBound,
                                  nSamp=nNodes)
    qNodes = samps_.q
    fNodes = analyticTestFuncs.fEx1D(qNodes, fType, qBound).val
    # Generate the test samples
    qTestFull = np.linspace(qBound[0], qBound[1], nTest)
    qTest = np.linspace(min(qNodes), max(qNodes), nTest)
    # Construct the Lagrange interpolation and evaluate it at the test points
    fInterpTest = lagInt(fNodes=fNodes, qNodes=[qNodes], qTest=[qTest]).val
    # Plot
    fTestFull = analyticTestFuncs.fEx1D(qTestFull, fType, qBound).val
    plt.figure(figsize=(12, 7))
    plt.plot(qTestFull, fTestFull, '--r', lw=2, label='Exact f(q)')
    plt.plot(qTest,
             fInterpTest,
             '-b',
             lw=2,
             label='f(q) by Lagrange Interpolation')
    plt.plot(qNodes, fNodes, 'oc', markersize='8', label='Nodes')
    plt.legend(loc='best', fontsize=17)
    plt.xticks(fontsize=15)
    plt.yticks(fontsize=15)
    plt.grid()
    plt.xlabel(r'$q$', fontsize=26)
    plt.ylabel(r'$f(q)$', fontsize=26)
    plt.show()
Example #2
0
def lagInt_2d_test():
    """
    Test Lagrange inerpolation over a 2D parameter space.
    """
    #----- SETTINGS --------------------------------------------------------------
    nNodes = [
        5, 4
    ]  #number of  training samples nodes in space of parameters q1, q2
    sampType = [
        'GLL',  #Method of drawing samples for q1, q2
        'unifSpaced'
    ]
    qBound = [
        [-0.75, 1.5],  # admissible range of parameters
        [-0.5, 2.5]
    ]

    # Settings of the exact response surface
    domRange = [
        [-2, 2],  #domain range for q1, q2
        [-3, 3]
    ]
    nTest = [100, 101]  #number of test samples
    #-----------------------------------------------------------------------------
    p = len(nNodes)
    # Create the training samples over each parameter space
    qNodes = []
    for i in range(p):
        qNodes_ = sampling.trainSample(sampleType=sampType[i],
                                       qInfo=qBound[i],
                                       nSamp=nNodes[i])
        qNodes.append(qNodes_.q)
    # Evaluate the simulator at each joint sample
    fNodes = analyticTestFuncs.fEx2D(qNodes[0], qNodes[1], 'type1',
                                     'tensorProd').val
    # Generate the test samples
    qTestList = []
    for i in range(p):
        qTest_ = sampling.testSample(sampleType='unifSpaced',
                                     qBound=qBound[i],
                                     nSamp=nTest[i])
        qTestList.append(qTest_.q)
    # Construct the Lagrange interpolation and evaluate it at the test samples
    fTest = lagInt(fNodes=fNodes,
                   qNodes=qNodes,
                   qTest=qTestList,
                   liDict={
                       'testRule': 'tensorProd'
                   }).val
    # Evaluate the exact model response over domRange
    qTestFull = []
    for i in range(p):
        qTestFull_ = np.linspace(domRange[i][0], domRange[i][1], nTest[i])
        qTestFull.append(qTestFull_)
    fTestFull = analyticTestFuncs.fEx2D(qTestFull[0], qTestFull[1], 'type1',
                                        'tensorProd').val
    fTestFullGrid = fTestFull.reshape((nTest[0], nTest[1]), order='F').T
    fTestGrid = fTest.reshape((nTest[0], nTest[1]), order='F').T
    # Plots
    plt.figure(figsize=(16, 8))
    plt.subplot(1, 2, 1)
    ax = plt.gca()
    CS1 = plt.contour(qTestFull[0], qTestFull[1], fTestFullGrid, 35)
    plt.clabel(CS1,
               inline=True,
               fontsize=15,
               colors='k',
               fmt='%0.2f',
               rightside_up=True,
               manual=False)
    qNodesGrid = reshaper.vecs2grid(qNodes)
    plt.plot(qNodesGrid[:, 0], qNodesGrid[:, 1], 'o', color='r', markersize=6)
    plt.xlabel(r'$q_1$', fontsize=25)
    plt.ylabel(r'$q_2$', fontsize=25)
    plt.xticks(fontsize=17)
    plt.yticks(fontsize=17)
    plt.title('Exact Response Surface')
    plt.subplot(1, 2, 2)
    ax = plt.gca()
    CS2 = plt.contour(qTestList[0], qTestList[1], fTestGrid, 20)
    plt.clabel(CS2,
               inline=True,
               fontsize=15,
               colors='k',
               fmt='%0.2f',
               rightside_up=True,
               manual=False)
    plt.plot(qNodesGrid[:, 0], qNodesGrid[:, 1], 'o', color='r', markersize=6)
    plt.xlabel(r'$q_1$', fontsize=25)
    plt.ylabel(r'$q_2$', fontsize=25)
    plt.xticks(fontsize=17)
    plt.yticks(fontsize=17)
    plt.title('Response Surface by Lagrange Interpolation')
    plt.xlim(domRange[0])
    plt.ylim(domRange[1])
    plt.show()
Example #3
0
def lagInt_3d_test():
    """
    Test Lagrange inerpolation over a 3D parameter space.
    """
    #----- SETTINGS -------------------
    nNodes = [8, 7, 6]  #number of training samples for q1, q2, q3
    sampType = [
        'GLL',  #Type of samples for q1, q2, q3
        'unifSpaced',
        'Clenshaw'
    ]
    qBound = [
        [-0.75, 1.5],  #range of parameters q1, q2, q3
        [-0.5, 2.5],
        [1, 3]
    ]
    nTest = [10, 11, 12]  #number of test samples for q1, q2, q3
    fOpts = {'a': 7, 'b': 0.1}  #parameters in Ishigami function
    #----------------------------------
    p = len(nNodes)
    # Generate the training samples
    qNodes = []
    for i in range(p):
        qNodes_ = sampling.trainSample(sampleType=sampType[i],
                                       qInfo=qBound[i],
                                       nSamp=nNodes[i])
        qNodes.append(qNodes_.q)
    # Run the simulator at the training samples
    fNodes = analyticTestFuncs.fEx3D(qNodes[0], qNodes[1], qNodes[2],
                                     'Ishigami', 'tensorProd', fOpts).val
    # Create the test samples and run the simultor at them
    qTest = []
    for i in range(p):
        qTest_ = sampling.testSample(sampleType='unifSpaced',
                                     qBound=qBound[i],
                                     nSamp=nTest[i])
        qTest.append(qTest_.q)
    fTestEx = analyticTestFuncs.fEx3D(qTest[0], qTest[1], qTest[2], 'Ishigami',
                                      'tensorProd', fOpts).val
    # Construct the Lagrange interpolation an evaluate it at the test samples
    fInterp = lagInt(fNodes=fNodes,
                     qNodes=qNodes,
                     qTest=qTest,
                     liDict={
                         'testRule': 'tensorProd'
                     }).val
    # Plot
    plt.figure(figsize=(14, 8))
    plt.subplot(2, 1, 1)
    fInterp_ = fInterp.reshape(np.asarray(np.prod(np.asarray(nTest))),
                               order='F')
    plt.plot(fInterp_, '-ob', mfc='none', label='Lagrange Interpolation')
    plt.plot(fTestEx, '--xr', ms=5, label='Exact Value')
    plt.ylabel(r'$f(q_1,q_2,q_3)$', fontsize=18)
    plt.xlabel(r'Test Sample Number', fontsize=14)
    plt.legend(loc='best', fontsize=14)
    plt.grid(alpha=0.4)
    plt.subplot(2, 1, 2)
    plt.plot(abs(fInterp_ - fTestEx), '-sk')
    plt.ylabel(r'$|f_{Interp}(q)-f_{Exact}(q)|$', fontsize=15)
    plt.xlabel(r'Test Sample Number', fontsize=14)
    plt.grid(alpha=0.4)
    plt.show()
Example #4
0
def lagIntAtGQs(fValM1, qM1, spaceM1, nM2, spaceM2, distType):
    """    
    Given response values `fValM1` at `nM1` arbitrary samples over the p-D `spaceM1`, the values at 
    `nM2` Gauss quadrature points over `spaceM2` are computed using Lagrange interpolation. 

       * Both `spaceM1` and `spaceM2` have the same dimension `p`.
       * At each of the p dimensions, ||`spaceM2`||<||`spaceM1`|| at each dimension.
       * The Gauss quadrature nodes over 'spaceM2' can be the abscissa of different types of 
         polynomials based on the `distType` and the gPCE rule. 
       * A tensor-product grid from the GQ nodes on `spaceM2` is created

    args:    
      `qM1`: List of length p 
         List of samples on `spaceM1`; qM1=[qM1_1,qM1_2,...,qM1_p] where `qM1_i` is a 1D numpy 
         array of size nM1_i, for i=1,2,...,p. 
      `fValM1`: numpy p-D array of shape (nM1_1,nM1_2,...,nM1_p).
         Response values at `qM1`
      `spaceM1`: List of length p.
         =[spaceM1_1,spaceM1_2,...,spaceM1_p] where spaceM1_i is a list of two elements, 
         specifying the admissible range of qM1_i, for i=1,2,...,p.
      `nM2` List of length p,
         Containing the number of Gauss quadrature samples `qM2` in each parameter dimension, 
         nM2=[nM2_1,nM2_2,...,nM2_p]
      `spaceM2`: List of length p.
         =[spaceM2_1,spaceM2_2,...,spaceM2_p] where spaceM2_i is a list of two elements, 
         specifying the admissible range of qM2_i, for i=1,2,...,p.
      `distType`: List of length p with string members
         The i-th element specifies the distribution type of the i-th parameter according to 
         the gPCE rule.

    Returns:
      `qM2`: List of length p 
         List of samples on `spaceM2`; qM2=[qM2_1,qM2_2,...,qM2_p] where `qM2_i` is a 1D numpy 
         array of size nM2_i, for i=1,2,...,p. 
      `xiM2`: numpy array of shape (nM2_1*nM2_2*...*nM2_p,p)   
         Tensor-product grid of Gauss-quadrature nodes on the mapped space of `spaceM2`
      `fValM2`: 1D numpy array of size (nM1_1*nM1_2*...*nM1_p).
         Interpolated response values at `xiM2`
    """
    # (1) Check the inputs
    ndim = len(spaceM1)
    if (ndim != len(spaceM2) or ndim != len(qM1)):
        raise ValueError(
            'SpaceM1 and SpaceM2 should have the same dimension, p.')
    for idim in range(ndim):
        d1 = spaceM1[idim][1]-spaceM1[idim][0]
        d2 = spaceM2[idim][1]-spaceM2[idim][0]
        if (d2 > d1):
            print("Wrong parameter range in direction ", ldim+1)
            raise ValueError("||spaceM2|| should be smaller than ||spaceM1||.")
    # (2) Construct the Gauss-quadrature stochastic samples for model2
    qM2 = []
    xiM2 = []
    for i in range(ndim):
        xi_, w = pce.gqPtsWts(nM2[i], distType[i])
        qM2_ = pce.mapFromUnit(xi_, spaceM2[i])
        qM2.append(qM2_)
        xiM2.append(xi_)
    if (ndim == 1):
        qM2 = qM2[0]
        xiM2 = xiM2[0]
    elif (ndim > 1):
        xiM2 = reshaper.vecs2grid(xiM2)
    # (3) Use lagrange interpolation to find values at q2, given fVal1 at q1
    if ndim == 1:
        fVal2Interp = lagInt(fNodes=fValM1, qNodes=[qM1[0]], qTest=[qM2]).val
    elif (ndim > 1):
        fVal2Interp_ = lagInt(fNodes=fValM1, qNodes=qM1, qTest=qM2, liDict={
                              'testRule': 'tensorProd'}).val
        nM2_ = fVal2Interp_.size
        fVal2Interp = fVal2Interp_.reshape(nM2_, order='F')
    return qM2, xiM2, fVal2Interp
Example #5
0
def lagIntAtGQs_2d_test():
    """
       Test pce2pce_GQ(...) for 2D uncertain parameter space
    """
    #------ SETTINGS ----------------------------------------------------
    #Space 1
    nSamp1 = [6, 10]  #number of samples in PCE1, parameter 1,2
    space1 = [
        [-2, 1.5],  #admissible space of PCE1 (both parameters)
        [-3, 2.5]
    ]
    sampleType1 = ['GLL', 'unifRand']  #see trainSample class in sampling.py
    #Space 2
    nSamp2 = [4, 5]  #number of samples in PCE2, parameter 1,2
    space2 = [
        [-0.5, 1],  #admissible space of PCEw (both parameters)
        [-2., 1.5]
    ]
    #Test samples
    nTest = [100, 101]  #number of test samples of parameter 1,2
    #model function
    fType = 'type1'  #Type of simulator
    #---------------------------------------------------------------------
    p = 2
    distType2 = ['Unif', 'Unif']
    #(1) Generate samples from space 1
    q1 = []
    for i in range(p):
        q1_ = sampling.trainSample(sampleType=sampleType1[i],
                                   qInfo=space1[i],
                                   nSamp=nSamp1[i])
        space1[i] = [
            min(q1_.q), max(q1_.q)
        ]  #correction for uniform samples (otherwise contours are not plotted properly)
        q1.append(q1_.q)
    #Response values at the GL points
    fVal1 = analyticTestFuncs.fEx2D(q1[0], q1[1], fType, 'tensorProd').val
    #(2) Lagrange interpolation from samples 1 to GQ nodes on space 2
    q2, xi2, fVal2 = lagIntAtGQs(fVal1, q1, space1, nSamp2, space2, distType2)
    #(3) Construct a PCE on space 2
    pceDict = {
        'p': p,
        'sampleType': 'GQ',
        'pceSolveMethod': 'Projection',
        'truncMethod': 'TP',
        'distType': distType2
    }
    pce2 = pce(fVal=fVal2, xi=xi2, pceDict=pceDict, nQList=nSamp2)
    #(4) Evaluate the surrogates: Lagrange interpolation over space 1
    #                             PCE over space 2
    #test samples
    qTest1 = []
    xiTest2 = []
    qTest2 = []
    for i in range(p):
        testSamps1 = sampling.testSample('unifSpaced',
                                         qBound=space1[i],
                                         nSamp=nTest[i])
        qTest1.append(testSamps1.q)
        testSamps2 = sampling.testSample('unifSpaced',
                                         GQdistType=distType2[i],
                                         qBound=space2[i],
                                         nSamp=nTest[i])
        xiTest2.append(testSamps2.xi)
        qTest2.append(testSamps2.q)
    #evaluation
    #space 1
    fTest1_ex = analyticTestFuncs.fEx2D(qTest1[0], qTest1[1], fType,
                                        'tensorProd').val
    fTest1 = lagInt(fNodes=fVal1,
                    qNodes=q1,
                    qTest=qTest1,
                    liDict={
                        'testRule': 'tensorProd'
                    }).val
    #space 2
    pceEval2 = pceEval(coefs=pce2.coefs,
                       xi=xiTest2,
                       distType=distType2,
                       kSet=pce2.kSet)
    fTest2 = pceEval2.pceVal
    #(5) 2d contour plots
    plt.figure(figsize=(20, 8))
    plt.subplot(1, 3, 1)
    ax = plt.gca()
    fTest_Grid = fTest1_ex.reshape(nTest, order='F').T
    CS1 = plt.contour(qTest1[0], qTest1[1], fTest_Grid,
                      35)  #,cmap=plt.get_cmap('viridis'))
    plt.clabel(CS1,
               inline=True,
               fontsize=13,
               colors='k',
               fmt='%0.2f',
               rightside_up=True,
               manual=False)
    plt.xlabel('q1')
    plt.ylabel('q2')
    plt.title('Exact response surface over space 1')
    #
    plt.subplot(1, 3, 2)
    ax = plt.gca()
    fTest1_Grid = fTest1.reshape(nTest, order='F').T
    CS2 = plt.contour(qTest1[0], qTest1[1], fTest1_Grid,
                      35)  #,cmap=plt.get_cmap('viridis'))
    plt.clabel(CS2,
               inline=True,
               fontsize=13,
               colors='k',
               fmt='%0.2f',
               rightside_up=True,
               manual=False)
    q1Grid = reshaper.vecs2grid(q1)
    plt.plot(q1Grid[:, 0], q1Grid[:, 1], 'ob', markersize=6)
    q2_ = reshaper.vecs2grid(q2)
    plt.plot(q2_[:, 0], q2_[:, 1], 'sr', markersize=6)
    plt.xlabel('q1')
    plt.ylabel('q2')
    plt.title(
        'Response surface by Lagrange Int.\n over space-1 using blue circles')
    #
    plt.subplot(1, 3, 3)
    ax = plt.gca()
    fTest2_Grid = fTest2.reshape(nTest, order='F').T
    CS3 = plt.contour(qTest2[0], qTest2[1], fTest2_Grid,
                      20)  #,cmap=plt.get_cmap('viridis'))
    plt.clabel(CS3,
               inline=True,
               fontsize=13,
               colors='k',
               fmt='%0.2f',
               rightside_up=True,
               manual=False)
    plt.plot(q2_[:, 0], q2_[:, 1], 'sr', markersize=6)
    plt.xlabel('q1')
    plt.ylabel('q2')
    plt.title('Response surface by PCE over space-2 \n using red squares')
    plt.xlim(space1[0][:])
    plt.ylim(space1[1][:])
    plt.show()
Example #6
0
def lagIntAtGQs_1d_test():
    """
    lagIntAtGQs test for 1D parameter
    """
    #------ SETTINGS --------------------
    #space 1
    nSampMod1 = [7]  #number of samples in PCE1
    space1 = [[-0.5, 2.]]  #admissible space of param in PCE1
    sampleType1 = 'GLL'  #see trainSample class in sampling.py
    #space 2
    distType2 = ['Unif']  #distribution type of the RV
    nSampMod2 = [5]  #number of samples in PCE2
    space2 = [[0.0, 1.5]]  #admissible space of param in PCE2
    #model function
    fType = 'type1'  #Type of simulator
    #test samples
    nTest = 100  #number of test samples
    #------------------------------------
    #(1) Generates samples from SpaceMod1
    qInfo_ = space1[0]
    samps1 = sampling.trainSample(sampleType=sampleType1,
                                  qInfo=qInfo_,
                                  nSamp=nSampMod1[0])
    q1 = samps1.q
    xi1 = samps1.xi
    qBound1 = samps1.qBound
    #Evaluate the simulator at samples1
    fEx = analyticTestFuncs.fEx1D(q1, fType, qInfo_)
    fVal1 = fEx.val
    #(2) Lagrange interpolation from samples 1 to GQ nodes on space 2
    q2, xi2, fVal2 = lagIntAtGQs(fVal1, [q1], space1, nSampMod2, space2,
                                 distType2)
    #(3) Construct a PCE over space 2 using the GQ nodes
    pceDict = {
        'p': 1,
        'sampleType': 'GQ',
        'pceSolveMethod': 'Projection',
        'distType': distType2
    }
    pce2 = pce(fVal=fVal2, xi=xi2[:, None], pceDict=pceDict)
    #(4) Evaluate the surrogates: Lagrange interpolation over space 1
    #                             PCE over space 2
    testSamps1 = sampling.testSample(sampleType='unifSpaced',
                                     qBound=space1[0],
                                     nSamp=nTest)
    qTest1 = testSamps1.q
    fTest1_ex = analyticTestFuncs.fEx1D(qTest1, fType, space1).val
    fTest1 = lagInt(fNodes=fVal1, qNodes=[q1], qTest=[qTest1]).val
    #
    testSamps2 = sampling.testSample(sampleType='unifSpaced',
                                     qBound=space2[0],
                                     nSamp=nTest)
    qTest2 = testSamps2.q
    xiTest2 = testSamps2.xi
    pcePred_ = pceEval(coefs=pce2.coefs, xi=[xiTest2], distType=distType2)
    fTest2 = pcePred_.pceVal
    #(5) Plot
    plt.figure(figsize=(15, 8))
    plt.plot(qTest1, fTest1_ex, '--k', lw=2, label=r'Exact $f(q)$')
    plt.plot(q1,
             fVal1,
             'ob',
             markersize=8,
             label='Original samples over space1')
    plt.plot(qTest1, fTest1, '-b', lw=2, label='Lagrange Int. over space 1')
    plt.plot(q2, fVal2, 'sr', markersize=8, label='GQ samples over space2')
    plt.plot(qTest2, fTest2, '-r', lw=2, label='PCE over space 2')
    plt.xlabel(r'$q$', fontsize=26)
    plt.ylabel(r'$f(q)$', fontsize=26)
    plt.xticks(fontsize=20)
    plt.yticks(fontsize=20)
    plt.grid(alpha=0.4)
    plt.legend(loc='best', fontsize=20)
    plt.show()