Beispiel #1
0
 def runModel(self,x):
   inputs = uq.stdVec()
   for loopA in xrange(len(x)):
     inputs.push_back(x[loopA])
   outputs = uq.stdVec()
   errorCode = uq.stdIntVec()
   res = self.model.evalModelError(inputs,outputs,errorCode)
   return res
Beispiel #2
0
def buildMultiresolutionMatrix(xTrain,maxOrder,maxDetailLevel):
  # Construct samples
  samples = uq.uqSamples(xTrain.shape[1])
  currSample = uq.stdVec()
  for loopA in range(xTrain.shape[0]):
    currSample.clear()
    for loopB in range(xTrain.shape[1]):
      currSample.push_back(xTrain[loopA,loopB])
    samples.addOneSample(currSample)

  # Set Parameters for multiresolution basis
  maxOrder                = maxOrder
  addLegendrePoly         = True
  addMW                   = True
  useBinaryPartitions     = False
  mwMatType               = uq.kMWFixedMaxDetailLevel
  mwMatIncludeNullColumns = True
  useExactMW              = False
  mwQuadOrder             = 10
  measure                 = npToStdMat(np.ones((2*mwQuadOrder,1)))
  # print np.array(measure)
  maxColumns              = 0
  maxDetailLevel          = maxDetailLevel

  # Construct Multiresolution Matrix on samples
  mwMat = uq.uqMWMatrix(maxOrder,samples, \
                        addLegendrePoly,addMW,useBinaryPartitions, \
                        mwMatType,mwMatIncludeNullColumns, \
                        useExactMW,mwQuadOrder,measure, \
                        maxColumns,maxDetailLevel)
  # Return Matrix
  return mwMat
Beispiel #3
0
def npToStdMat(npMat):
  res = uq.stdMat()
  aux = uq.stdVec()
  for loopA in range(npMat.shape[1]):
    aux.clear()
    for loopB in range(npMat.shape[0]):
      aux.push_back(npMat[loopB,loopA])
    res.push_back(aux)
  return res
Beispiel #4
0
 def setInitialParamGuess(self,useStartingParameterFromFile,startFromCentre,startParameterFile):
   if(useStartingParameterFromFile):
     # Set Boolean Variable
     self.paramsFromFile = True
     self.paramsFile = startParameterFile
     # Read Parameters from file
     self.x0 = np.loadtxt(startParameterFile)
   elif(startFromCentre):
     # Start from the average parameters
     limits = uq.stdVec()
     self.model.getParameterLimits(limits)
     numParams = self.model.getParameterTotal()
     self.x0 = np.zeros((numParams,))
     for loopA in xrange(numParams):
       self.x0[loopA] = 0.5*(limits[2*loopA + 0] + limits[2*loopA + 1])
   else:
     # Start from the default parameters
     params = uq.stdVec()
     self.model.getDefaultParams(params)
     self.x0 = params
Beispiel #5
0
def buildRegressionMatrix(pTrainVals,ord):
  # Construct samples
  samples = uq.uqSamples(pTrainVals.shape[1])
  currSample = uq.stdVec()
  for loopA in range(pTrainVals.shape[0]):
    currSample.clear()
    for loopB in range(pTrainVals.shape[1]):
      currSample.push_back(pTrainVals[loopA,loopB])
    samples.addOneSample(currSample)
  # Construct Polynomial Matrix on samples
  polyMat = uq.uqPolyMatrix(samples,ord,uq.kPolyLegendre,uq.kMIPartialOrder)
  # Return Matrix
  return polyMat
Beispiel #6
0
  def train(self,pMat,qTrainVals):
    # Eval functional value with simple function
    rhs = uq.stdVec()
    for loopA in range(len(qTrainVals)):
      rhs.push_back(qTrainVals[loopA])
    
    # Construct the regression algorithm
    bcs = uq.uqAlgorithmBCS();
    # Set options: Print Progress to screen
    bcs.opts.printProgressToScreen = True;
    bcs.opts.printDBGMessages      = False;
    bcsCoeffs = uq.stdVec()
    coeffPrec = uq.stdMat()
    resNorm = 0.0
    bcsReturn = bcs.run(pMat.getRowCount(),pMat.getColCount(), 
                        rhs,pMat.getMatrix(),
                        bcsCoeffs,coeffPrec,resNorm);

    # Print coefficients on screen
    coeffs = np.array(bcsCoeffs)
    # Return
    return np.array(bcsCoeffs),np.array(coeffPrec),bcsReturn
Beispiel #7
0
# =============
# MAIN FUNCTION
# =============
if __name__ == "__main__":

    # Construct samples
    samples = uq.uqSamples()
    samples.addVariable('Var1', uq.kSAMPLEUniform, -1.0, 1.0)
    samples.addVariable('Var2', uq.kSAMPLEUniform, -1.0, 1.0)
    samples.generateCartesianGrid(10, uq.kCC, uq.kHaarRange)

    # Construct Polynomial Matrix on samples
    polyMat = uq.uqPolyMatrix(samples, 5, uq.kPolyLegendre, uq.kMIPartialOrder)

    # Eval functional value with simple function
    rhs = uq.stdVec()
    rhs.resize(polyMat.getRowCount())
    for loopA in xrange(polyMat.getRowCount()):
        rhs[loopA] = samples.getValuesAt(loopA, 0) + samples.getValuesAt(
            loopA, 1)

    # Construct the regression algorithm
    bcs = uq.uqAlgorithmBCS()

    # Set options: Print Progress to screen
    bcs.opts.printProgressToScreen = False
    bcs.opts.printDBGMessages = False

    bcsCoeffs = uq.stdVec()
    coeffPrec = uq.stdMat()
    resNorm = 0.0
    polyIntLegendre = uq.uqPolyBasis(uq.kPolyLegendre, currOrder + 1)
    polyIntHermite = uq.uqPolyBasis(uq.kPolyHermite, currOrder + 1)

    currentLoc = 0.0
    for loopA in xrange(steps):
        currentLoc = loopA / float(steps - 1)
        results[loopA, 0] = polyIntMonomial.evaluate(currentLoc, currOrder)
        results[loopA, 1] = polyIntLegendre.evaluate(currentLoc, currOrder)
        results[loopA, 2] = polyIntHermite.evaluate(currentLoc, currOrder)

    # ORTHOGONAL POLYNOMIALS
    # Define the number of quadrature points
    quadLevel = 10

    # Define the Uniform Measure
    measureAtQuadPoints = uq.stdVec(2 * quadLevel, 0.0)
    for loopA in xrange(2 * quadLevel):
        measureAtQuadPoints[loopA] = 1.0

    orthoPoly = uq.uqOrthoPolyBasis(currOrder + 1, quadLevel,
                                    measureAtQuadPoints)

    currentLoc = 0.0
    for loopA in xrange(steps):
        currentLoc = loopA / float(steps - 1)
        results[loopA, 3] = orthoPoly.evaluate(currentLoc, currOrder)

    # MULTIWAVELETS
    mwInt = uq.uqMWBasis(currOrder + 1, quadLevel)
    currentLoc = 0.0
    for loopA in xrange(steps):
    # EVALUATE RANGE
    #tmpLimits = uq.stdVec()
    #approx.getExtremes(tmpLimits)
    #measureSize = fabs(tmpLimits[1] - tmpLimits[0])
    #print 'CURRENT LIMITS: %f %f' % (tmpLimits[0],tmpLimits[1])

    # FORM SAMPLES USING INTEGRATION GRID IN 1D
    mwOrder = 2
    mwQuadOrder = 30
    measure1DGridPoints = uq.uqSamples()
    measure1DGridPoints.addVariable('grid1D', uq.kSAMPLEUniform, 0.0, 1.0)
    measure1DGridPoints.generateCartesianGrid(mwQuadOrder, uq.kDoubleCC,
                                              uq.kHaarRange)

    intLocations = uq.stdVec()
    #scale1DGridOnPartition(measure1DGridPoints,tmpLimits[0],tmpLimits[1],intLocations);
    scale1DGridOnPartition(measure1DGridPoints, 0.0, 1.0, intLocations)

    # EVALUATE MARGINAL AT QUADRATURE POINTS
    measure = uq.stdMat()
    tmp = uq.stdVec()
    currInt = 0.0
    currLoc = 0.0
    currVal = 0.0
    for loopA in xrange(intLocations.size()):
        currLoc = intLocations[loopA]
        #currVal = approx.evaluate(currLoc);
        currVal = 1.0
        currInt += currVal * measure1DGridPoints.getWeightAt(
            loopA, measure1DGridPoints.getMaxWeightOrder())
Beispiel #10
0
# =============
if __name__ == "__main__":

    # Assign Dataset
    data = da.daData_Scalar_MultiplePatients()
    data.readFromFile('tutorial.csv')

    # Construct Specific Model
    myModel = cm.cmTutorial()

    # Assign Dataset
    currentColumn = 1
    myModel.setData(data, currentColumn)

    # Get Default Input Parameter Values
    inputs = uq.stdVec()
    myModel.getDefaultParams(inputs)

    # Solve Model
    outputs = uq.stdVec()
    errorCodes = uq.stdIntVec()
    ll = myModel.evalModelError(inputs, outputs, errorCodes)

    print 'Model Results'
    print ''
    print 'Final Location: %f' % (outputs[0])
    print 'Total Time: %f' % (outputs[1])
    print 'Maximum Height: %f' % (outputs[2])
    print ''
    print 'Resulting Log-likelihod: %f' % (ll)
def main(fileName, power, comm):

    # MPI Init
    rank = comm.Get_rank()
    size = comm.Get_size()

    # Set Model
    model = cm.cmBertiniSolverModel(fileName)

    modelType = fileName.split("_")[1]
    # SEt power
    model.setExponent(1 / power)
    # add solution
    sol = uq.stdVec()

    # for loopA in range(9):
    #   sol.push_back(0.0)
    # model.addSolution(sol) # Set DREAM Parameters

    totChains = size
    totGenerations = 30000
    totalCR = 3
    totCrossoverPairs = 5
    dreamGRThreshold = 1.2
    dreamJumpStep = 10
    dreamGRPrintStep = 10

    # Set OUTPUT Files
    dreamChainFileName = 'chain_GR_000000.txt'
    dreamGRFileName = 'gr_GR.txt'

    # Set Restart File
    # No restart Simulation
    dreamRestartReadFileName = ''
    # string dreamRestartReadFileName = "restart_read_GR.txt";
    # Write restart file just in case
    dreamRestartWriteFileName = 'restart_write_GR.txt'

    # Set Prior Information
    usePriorFromFile = False
    priorFileName = ''
    priorModelType = 0

    # Initialize DREAM Action
    dream = ac.acActionDREAM(totChains, totGenerations, totalCR,
                             totCrossoverPairs, dreamChainFileName,
                             dreamGRFileName, dreamGRThreshold, dreamJumpStep,
                             dreamGRPrintStep, dreamRestartReadFileName,
                             dreamRestartWriteFileName, usePriorFromFile,
                             priorFileName, priorModelType)

    # Set Model
    dream.setModel(model)

    # Run MCMC Simulation
    dream.go()

    # Add Barrier
    comm.Barrier()

    # Post Process the Results
    if (rank == 0):
        debugMode = False
        burnInPercent = 0.1
        dream.postProcess(debugMode, burnInPercent)
        # Rename File
        shutil.move('paramTraces.txt',
                    'Datafiles/paramTraces_' + str(modelType))