示例#1
0
    def saveDict(self):
        sd = dict()
        sd['ID'] = self.ID
        sd['numSamples'] = self.numSamples
        sd['origNumSamples'] = self.origNumSamples
        sd['numSamplesAdded'] = self.numSamplesAdded
        sd['fromFile'] = self.fromFile
        sd['sampleMethod'] = SamplingMethods.getPsuadeName(self.sampleMethod)
        sd['model'] = self.model.saveDict()
        if isinstance(self.inputData, numpy.ndarray):
            sd['inputData'] = self.inputData.tolist()
        else:
            sd['inputData'] = self.inputData

        if isinstance(self.outputData, numpy.ndarray):
            sd['outputData'] = self.outputData.tolist()
        else:
            sd['outputData'] = self.outputData
        sd['runState'] = self.runState.tolist()
        sd['legendreOrder'] = self.legendreOrder
        sd['fromFile'] = self.fromFile
        sd['sampleRSType'] = ResponseSurfaces.getPsuadeName(self.sampleRSType)
        sd["turbineJobIds"] = self.turbineJobIds
        sd["turbineSession"] = self.turbineSession
        sd["turbineResub"] = self.turbineResub
        sd['analyses'] = []
        for analysis in self.analyses:
            sd['analyses'].append(analysis.saveDict())

        return sd
示例#2
0
    def getAdditionalInfo(self):
        info = OrderedDict()
        if not isinstance(self.responseSurface, (tuple, list)):
            rs = ResponseSurfaces.getEnumValue(self.responseSurface)
            if rs == ResponseSurfaces.LEGENDRE:
                if self.rsOptions is not None:
                    if isinstance(self.rsOptions, dict):
                        info['Legendre Polynomial Order'] = self.rsOptions[
                            'legendreOrder']
                    else:
                        info['Legendre Poynomial Order'] = self.rsOptions
            elif rs in [ResponseSurfaces.MARS,
                        ResponseSurfaces.MARSBAG]:  #MARS
                if self.rsOptions is not None:
                    info['Number of MARS basis functions'] = self.rsOptions[
                        'marsBases']
                    info['MARS degree of interaction'] = self.rsOptions[
                        'marsInteractions']
            elif rs == ResponseSurfaces.USER:
                if self.userRegressionFile is not None:
                    info['User Regression File'] = os.path.basename(
                        self.userRegressionFile)

        # xprior info
        if self.xprior is not None:
            info['xprior'] = self.xprior

        return info
示例#3
0
    def showResults(self):
        rsIndex = ResponseSurfaces.getEnumValue(self.responseSurface)
        userMethod = (rsIndex == ResponseSurfaces.USER)
        if userMethod:
            mfile = 'RSTest_hs.m'
        else:
            mfile = 'RSFA_CV_err.m'
        self.restoreFromArchive(mfile)

        RSAnalyzer.plotValidate(self.ensemble, self.outputs[0],
                                self.responseSurface, userMethod, mfile)
示例#4
0
    def analyze(self):
        data = self.ensemble  
        fnameRS = Common.getLocalFileName(RSAnalyzer.dname, data.getModelName().split()[0], '.rsdat')
        index = ResponseSurfaces.getEnumValue(self.responseSurface)
        fixedAsVariables = index == ResponseSurfaces.USER
        data.writeToPsuade(fnameRS, fixedAsVariables=fixedAsVariables)
        cmd = RSSensitivityAnalysis.psuadeNames[self.subType]
        mfile = RSAnalyzer.performSA(fnameRS, self.outputs[0], cmd, self.showErrorBars,
                                     self.responseSurface, self.rsOptions,
                                     self.userRegressionFile, self.xprior)

        if mfile is not None:
            self.archiveFile(mfile)
        return mfile
示例#5
0
 def analyze(self):
     fname = Common.getLocalFileName(
         RSInferencer.dname,
         self.ensemble.getModelName().split()[0], '.dat')
     fixedAsVariables = ResponseSurfaces.USER in [
         ResponseSurfaces.getEnumValue(rs) for rs in self.responseSurface
     ]
     self.ensemble.writeToPsuade(fname, fixedAsVariables=fixedAsVariables)
     self.inferencer.infer(fname,
                           self.ytable,
                           self.xtable,
                           self.obsTable,
                           genPostSample=self.genPostSample,
                           addDisc=self.addDisc,
                           show=self.showList,
                           endFunction=self.newEndFunction,
                           disableWhilePlotting=self.disableWhilePlotting,
                           userRegressionFile=self.userRegressionFile)
示例#6
0
    def analyze(self):
        data = self.ensemble
        fname = Common.getLocalFileName(RSAnalyzer.dname,
                                        data.getModelName().split()[0], '.dat')
        index = ResponseSurfaces.getEnumValue(self.responseSurface)
        fixedAsVariables = index == ResponseSurfaces.USER
        data.writeToPsuade(fname, fixedAsVariables=fixedAsVariables)

        mfile = RSAnalyzer.validateRS(fname, self.outputs[0],
                                      self.responseSurface, self.rsOptions,
                                      self.genCodeFile, self.nCV,
                                      self.userRegressionFile, self.testFile)

        if mfile is None:
            return None

        mfile = mfile[0]
        self.archiveFile(mfile)
        return mfile
示例#7
0
    def analyze(self):
        Common.initFolder(Visualizer.dname)

        data = self.ensemble
        data = data.getValidSamples(
        )  # filter out samples that have no output results

        fname = Common.getLocalFileName(Visualizer.dname,
                                        data.getModelName().split()[0], '.dat')
        index = ResponseSurfaces.getEnumValue(self.responseSurface)
        fixedAsVariables = index == ResponseSurfaces.USER
        data.writeToPsuade(fname, fixedAsVariables=fixedAsVariables)
        rsdim = len(self.inputs)

        inNames = data.getInputNames()
        plotInNames = [inNames[i - 1] for i in self.inputs]
        if self.legendreOrder is not None:
            mfile = Visualizer.showRS(
                fname,
                self.outputs[0],
                plotInNames,
                rsdim,
                self.responseSurface,
                vmin=self.minVal,
                vmax=self.maxVal,
                rsOptions=self.rsOptions,
                userRegressionFile=self.userRegressionFile)
        else:
            mfile = Visualizer.showRS(
                fname,
                self.outputs[0],
                plotInNames,
                rsdim,
                self.responseSurface,
                vmin=self.minVal,
                vmax=self.maxVal,
                userRegressionFile=self.userRegressionFile)
        if mfile is not None:
            self.archiveFile(mfile)
        return mfile
示例#8
0
 def analyze(self):
     data = self.ensemble
     fnameRS = Common.getLocalFileName(RSAnalyzer.dname,
                                       data.getModelName().split()[0],
                                       '.rsdat')
     index = ResponseSurfaces.getEnumValue(self.responseSurface)
     fixedAsVariables = index == ResponseSurfaces.USER
     data.writeToPsuade(fnameRS, fixedAsVariables=fixedAsVariables)
     if self.subType == RSUncertaintyAnalysis.ALEATORY_ONLY:
         (sfile, mfile) = RSAnalyzer.performUA(fnameRS, self.outputs[0],
                                               self.responseSurface,
                                               self.rsOptions,
                                               self.userRegressionFile,
                                               self.xprior)
         self.archiveFile(sfile)
     else:
         mfile = RSAnalyzer.performAEUA(fnameRS, self.outputs[0],
                                        self.responseSurface,
                                        self.rsOptions,
                                        self.userRegressionFile,
                                        self.xprior)
     if mfile is not None:
         self.archiveFile(mfile)
     return mfile
示例#9
0
    def readSampleFromPsuadeFile(fileName, returnModelOnly = False):
        f = open(fileName, 'r')
        lines = f.readlines()
        f.close()

        model = Model()
        path, fname = os.path.split(fileName)  # exclude path from file name
        model.setName(fname)

        namesIncludeNodes = False
        hasSampleData = False
        readData = False
        readInputs = False
        readOutputs = False
        numInputs = None
        driverName = None
        optDriverName = None
        auxDriverName = None
        sampleType = None
        legendreOrder = None
        sampleMethod = None
        inputData = None
        outputData = None
        runState = None

        inputNames = []
        outputNames = []
        inputTypes = []
        inputMins = []
        inputMaxs = []
        inputDefaults = []
        inputDists = []
        inputDistParam1s = []
        inputDistParam2s = []
    
        for line in lines:
            if line[0] == '#' and 'NAMESHAVENODES' in line:
                namesIncludeNodes = True
            if len(line) > 0 and line[0] != '#': #Not comment
                if line.startswith('PSUADE_IO'):
                    readData = not readData
                    hasSampleData = True
                elif line.startswith('INPUT'):
                    readInputs = True
                elif line.startswith('OUTPUT'):
                    readOutputs = True
                elif line.startswith('END'):
                    if readInputs:
                        readInputs = False
                    elif readOutputs:
                        readOutputs = False
                elif readData: # Read samples
                    if numInputs is None: #Have not read number of inputs
                        nums = line.split()
                        numInputs = int(nums[0])
                        numOutputs = int(nums[1])
                        numSamples = int(nums[2])
                        runState = [False]*numSamples
                        inputData = [0]*numSamples
                        outputData = [0]*numSamples
                        readSampleData = False
                    elif not readSampleData: # Sample number and run state
                        nums = line.split()
                        sampleNum = int(nums[0]) - 1
                        runState[sampleNum] = bool(int(nums[1]))
                        readSampleData = True
                        numValuesRead = 0
                        sampleInputs = [0] * numInputs
                        sampleOutputs = [0] * numOutputs
                    else:
                        if numValuesRead < numInputs: #Input value
                            if line.strip() in ['9.9999999999999997e+34', '9.9999999999999997e+034']:
                                line = 'nan'
                            sampleInputs[numValuesRead] = float(line)
                            numValuesRead = numValuesRead + 1
                        else: #Output value
                            if line.strip() in ['9.9999999999999997e+34', '9.9999999999999997e+034']:
                                line = 'nan'
                            sampleOutputs[numValuesRead - numInputs] = float(line)
                            numValuesRead = numValuesRead + 1
                            if numValuesRead - numInputs == numOutputs:
                                inputData[sampleNum] = sampleInputs
                                outputData[sampleNum] = sampleOutputs
                                readSampleData = False
                elif readInputs: # Read inputs
                    stripped = line.strip()
                    values = stripped.split()
                    if values[0] == 'variable': # Variable name min max
                        inputNames = inputNames + [values[2]]
                        inputTypes = inputTypes + [Model.VARIABLE]
                        inputMins = inputMins + [float(values[4])]
                        inputMaxs = inputMaxs + [float(values[5])]
                        inputDefaults = inputDefaults + [(float(values[4]) + float(values[5])) / 2]
                        inputDists = inputDists + ['U']
                        inputDistParam1s = inputDistParam1s + [None]
                        inputDistParam2s = inputDistParam2s + [None]
                    elif values[0] == 'fixed': # Fixed variable
                        inputNames = inputNames + [values[2]]
                        inputTypes = inputTypes + [Model.FIXED]
                        fixedVal = float(values[4])
                        inputMins = inputMins + [fixedVal]
                        inputMaxs = inputMaxs + [fixedVal]
                        inputDefaults = inputDefaults + [fixedVal]
                        inputDists = inputDists + ['U']
                        inputDistParam1s = inputDistParam1s + [None]
                        inputDistParam2s = inputDistParam2s + [None]
                        # Insert input values
                        if hasSampleData:
                            for i in xrange(len(inputData)):
                                inputRow = inputData[i]
                                inputRow.insert(len(inputNames) - 1, fixedVal)
                                inputData[i] = inputRow
                    elif values[0] == 'PDF': # Distribution
                        index = int(values[1]) - 1
                        inputDists[index] = values[2]
                        if len(values) > 3:
                            if values[2] == Distribution.getPsuadeName(Distribution.SAMPLE):
                                inputDistParam1s[index] = values[3]
                            else:
                                inputDistParam1s[index] = float(values[3])
                            if len(values) > 4:
                                inputDistParam2s[index] = float(values[4])
                            
                elif readOutputs: # Read outputs
                    stripped = line.strip() # Variable name
                    if stripped.startswith('variable'):
                        values = stripped.split()
                        outputNames = outputNames + [values[2]]
                else:
                    stripped = line.strip()
                    values = stripped.split()
                    if values[0] == 'sampling': #Sampling method
                        sampleMethod = values[2]
                    elif values[0] == 'driver': #Driver
                        if values[2] == 'NONE':
                            values[2] = None
                        driverName = values[2]
                        if values[2] is not None and values[2] != 'PSUADE_LOCAL' and not os.path.exists(driverName):
                            # Check if driver exists in same directory as this file
                            if os.path.exists(os.path.join(path, driverName)):
                                driverName = os.path.join(path, driverName)
                            else: # Don't set the name because the file does not exist
                                driverName = None
                    elif values[0] == 'opt_driver': #Optimization driver
                        if values[2] == 'NONE':
                            values[2] = None
                        optDriverName = values[2]
                        if values[2] is not None and values[2] != 'PSUADE_LOCAL' and not os.path.exists(optDriverName):
                            # Check if driver exists in same directory as this file
                            if os.path.exists(os.path.join(path, optDriverName)):
                                optDriverName = os.path.join(path, optDriverName)
                            else: # Don't set the name because the file does not exist
                                optDriverName = None
                    elif values[0] == 'aux_opt_driver': #Batch simulation driver
                        if values[2] == 'NONE':
                            values[2] = None
                        auxDriverName = values[2]
                        if values[2] is not None and not os.path.exists(auxDriverName):
                            # Check if driver exists in same directory as this file
                            if os.path.exists(os.path.join(path, auxDriverName)):
                                auxDriverName = os.path.join(path, auxDriverName)
                            else: # Don't set the name because the file does not exist
                                auxDriverName = None
                    elif values[0] == 'num_samples': #Number of samples
                        numSamples = int(values[2])
                    elif values[0] == 'analyzer': # Analysis values
                        if values[1] == 'rstype':
                            sampleType = values[3]
                            sampleType = ResponseSurfaces.getEnumValue(sampleType)
                        elif values[1] == 'rs_legendre_order':
                            legendreOrder = int(values[3])
                            
                        
        model.setInputNames(inputNames)
        model.setOutputNames(outputNames)
        model.setNamesIncludeNodes(namesIncludeNodes)
        model.setInputTypes(inputTypes)
        model.setInputMins(inputMins)
        model.setInputMaxs(inputMaxs)
        model.setInputDefaults(inputDefaults)
        model.setSelectedOutputs(range(len(outputNames)))
        model.setDriverName(driverName)
        model.setOptDriverName(optDriverName)
        model.setAuxDriverName(auxDriverName)
        model.setRunType(Model.LOCAL) 
##        print model.getInputNames()
##        print model.getOutputNames()
##        print model.getInputDistributions()
##        print model.getNumSamples()
##        print model.getNumInputs()
##        print model.getNumOutputs()
##        print model.getInputMins()
##        print model.getInputMaxs()
##        from SamplingMethods import SamplingMethods
##        print SamplingMethods.getFullName(model.getSampleMethod())
##        print model.getDriver()
        if returnModelOnly:
            return model

        data = SampleData(model)
        data.setFromFile(True)
        data.setNumSamples(numSamples)
        if sampleMethod is None:
            data.setSampleMethod(SamplingMethods.MC)
        else:
            data.setSampleMethod(sampleMethod)
        data.setInputDistributions(inputDists, inputDistParam1s, inputDistParam2s)
        data.setSampleRSType(sampleType)
        data.setLegendreOrder(legendreOrder)
        if inputData:
            data.setInputData(inputData)
        if outputData:
            data.setOutputData(outputData)
        if runState:
            data.setRunState(runState)
        return data
示例#10
0
    def writeToPsuade(self, filename, fixedAsVariables=False):
        outf = open(filename, 'w')
        if self.getNamesIncludeNodes():
            outf.write('# NAMESHAVENODES\n')
        outf.write('PSUADE_IO (Note : inputs not true inputs if pdf ~=U)\n')
        types = self.getInputTypes()

        if fixedAsVariables:
            numInputs = self.getNumInputs()
        else:
            numInputs = types.count(Model.VARIABLE)
        outf.write('%d %d %d\n' %
                   (numInputs, self.getNumOutputs(), self.getNumSamples()))

        #Write out data
        hasOutputData = False
        if self.outputData is not None:
            if isinstance(self.outputData, numpy.ndarray):
                if self.outputData.size > 0:
                    hasOutputData = True
            elif self.outputData:
                if isinstance(self.outputData[0], list) and len(
                        self.outputData[0]) == 0:
                    hasOutputData = False
                else:
                    hasOutputData = True
        for i in xrange(self.getNumSamples()):
            outf.write('%d %d\n' % (i + 1, self.runState[i]))
            for j in xrange(self.getNumInputs()):
                if types[j] == Model.VARIABLE or fixedAsVariables:
                    outf.write(' % .16e\n' % self.inputData[i][j])
            for j in xrange(self.getNumOutputs()):
                if hasOutputData and not numpy.isnan(self.outputData[i][j]):
                    outf.write(' % .16e\n' % self.outputData[i][j])
                else:
                    outf.write(' 9.9999999999999997e+34\n')

        outf.write('PSUADE_IO\n')
        outf.write('PSUADE\n')

        #Write inputs
        outf.write('INPUT\n')
        numFixed = self.getNumInputs() - numInputs
        if numFixed > 0:
            outf.write('   num_fixed %d\n' % numFixed)
        #outf.write('   dimension = %d\n' % self.getNumInputs())
        outf.write('   dimension = %d\n' % numInputs)
        names = self.getInputNames()
        mins = self.getInputMins()
        maxs = self.getInputMaxs()
        defaults = self.getInputDefaults()
        distributions = self.getInputDistributions()
        if not distributions or len(distributions) == 0:
            self.setInputDistributions([Distribution.UNIFORM] *
                                       self.getNumInputs())
            distributions = self.getInputDistributions()
            self.setInputDistributions([])

        fixedIndex = 1
        variableIndex = 1
        for name, minimum, maximum, inType, dist, default in map(
                None, names, mins, maxs, types, distributions, defaults):
            if not fixedAsVariables and inType == Model.FIXED:
                outf.write('   fixed %d %s =  % .16e\n' %
                           (fixedIndex, name, default))
                fixedIndex = fixedIndex + 1
            else:
                outf.write('   variable %d %s  =  % .16e  % .16e\n' %
                           (variableIndex, name, minimum, maximum))
                if dist is not None:
                    distType = dist.getDistributionType()
                    distParams = dist.getParameterValues()
                    if distType != Distribution.UNIFORM:
                        outf.write('   PDF %d %c' %
                                   (variableIndex,
                                    Distribution.getPsuadeName(distType)))
                        if distType == Distribution.SAMPLE:
                            fileString = distParams[0]
                            import platform
                            if platform.system() == 'Windows':
                                import win32api
                                fileString = win32api.GetShortPathName(
                                    fileString)
                            outf.write(' %s %d' % (fileString, distParams[1]))
                        else:
                            if distParams[0] is not None:
                                outf.write(' % .16e' % distParams[0])
                            if distParams[1] is not None:
                                outf.write(' % .16e' % distParams[1])
                        outf.write('\n')
                variableIndex = variableIndex + 1
        outf.write('END\n')

        #Write outputs
        outf.write('OUTPUT\n')
        outf.write('   dimension = %d\n' % self.getNumOutputs())
        names = self.getOutputNames()
        indices = range(self.getNumOutputs())
        for i, name in zip(indices, names):
            outf.write('   variable %d %s\n' % (i + 1, name))
        outf.write('END\n')

        #Write Method
        outf.write('METHOD\n')
        if self.getSampleMethod() != None:
            outf.write('   sampling = %s\n' %
                       SamplingMethods.getPsuadeName(self.getSampleMethod()))
        outf.write('   num_samples = %d\n' % self.getNumSamples())
        outf.write('   num_replications = 1\n')
        outf.write('   num_refinements = 0\n')
        outf.write('   refinement_size = 10000000\n')
        outf.write('   reference_num_refinements = 0\n')
        outf.write('END\n')

        #Write Application
        outf.write('APPLICATION\n')
        driverString = self.getDriverName()
        if driverString is None or not os.path.exists(driverString):
            driverString = 'NONE'
        else:
            import platform
            if platform.system() == 'Windows':
                import win32api
                driverString = win32api.GetShortPathName(driverString)
        outf.write('   driver = %s\n' % driverString)
        driverString = self.getOptDriverName()
        if driverString != 'PSUADE_LOCAL':
            if driverString is None or not os.path.exists(driverString):
                driverString = 'NONE'
            else:
                import platform
                if platform.system() == 'Windows':
                    import win32api
                    driverString = win32api.GetShortPathName(driverString)
        outf.write('   opt_driver = %s\n' % driverString)
        driverString = self.getEnsembleOptDriverName()
        if driverString != 'PSUADE_LOCAL':
            if driverString is None or not os.path.exists(driverString):
                driverString = 'NONE'
            else:
                import platform
                if platform.system() == 'Windows':
                    import win32api
                    driverString = win32api.GetShortPathName(driverString)
        outf.write('   ensemble_opt_driver = %s\n' % driverString)
        driverString = self.getAuxDriverName()
        if driverString is None or not os.path.exists(driverString):
            driverString = 'NONE'
        else:
            import platform
            if platform.system() == 'Windows':
                import win32api
                driverString = win32api.GetShortPathName(driverString)
        outf.write('   aux_opt_driver = %s\n' % driverString)
        outf.write('   max_job_wait_time = 1000000\n')
        outf.write('   save_frequency = 1\n')
        outf.write('END\n')

        #Write Analysis
        outf.write('ANALYSIS\n')
        outf.write('   analyzer output_id  = 1\n')
        rs = self.getSampleRSType()
        if rs == None:
            rs = 'MARS'
        else:
            rs = ResponseSurfaces.getPsuadeName(rs)
        outf.write('   analyzer rstype = %s\n' % rs)

        order = self.getLegendreOrder()
        if order is not None:
            outf.write('   analyzer rs_legendre_order = %d\n' %
                       self.getLegendreOrder())
        outf.write('   analyzer threshold = 1.000000e+00\n')
        outf.write('   diagnostics 1\n')
        outf.write('END\n')

        outf.write('END\n')
        outf.close()
示例#11
0
 def setSampleRSType(self, RSType):
     # print RSType
     if isinstance(RSType, str):
         self.sampleRSType = ResponseSurfaces.getEnumValue(RSType)
     else:
         self.sampleRSType = RSType
示例#12
0
    def loadDict(self, sd):
        self.model = Model()
        try:
            self.model.loadDict(sd['model'])
        except:
            pass

        self.setID(sd.get('ID', ''))
        self.setNumSamples(sd.get('numSamples', 0))
        self.origNumSamples = sd.get('origNumSamples', self.getNumSamples())
        self.setNumSamplesAdded(sd.get('numSamplesAdded', 0))
        self.setFromFile(sd.get('fromFile', False))
        self.setSampleMethod(sd.get('sampleMethod', None))
        self.setInputData(sd.get('inputData', None))
        self.setOutputData(sd.get('outputData', None))
        self.setRunState(sd.get('runState', None))
        self.legendreOrder = sd.get('legendreOrder', None)
        self.fromFile = sd.get('fromFile', False)
        self.sampleRSType = ResponseSurfaces.getEnumValue(
            sd.get('sampleRSType'))
        self.turbineJobIds = sd.get("turbineJobIds", [])
        self.turbineSession = sd.get("turbineSession", None)
        self.turbineResub = sd.get("turbineResub", [])
        inputDists = []
        if 'inputDists' in sd:
            for distDict in sd['inputDists']:
                distr = Distribution(Distribution.UNIFORM)
                distr.loadDict(distDict)
                inputDists.append(distr)
        self.setInputDistributions(inputDists)
        self.analyses = []
        if 'analyses' in sd:
            for analDict in sd['analyses']:
                type = UQAnalysis.getTypeEnumValue(analDict['type'])
                if type == UQAnalysis.PARAM_SCREEN:
                    from ParameterScreening import ParameterScreening
                    anal = ParameterScreening(self, analDict['outputs'],
                                              analDict['subType'])
                elif type == UQAnalysis.UNCERTAINTY:
                    from UncertaintyAnalysis import UncertaintyAnalysis
                    anal = UncertaintyAnalysis(self, analDict['outputs'])
                elif type == UQAnalysis.CORRELATION:
                    from CorrelationAnalysis import CorrelationAnalysis
                    anal = CorrelationAnalysis(self, analDict['outputs'])
                elif type == UQAnalysis.SENSITIVITY:
                    from SensitivityAnalysis import SensitivityAnalysis
                    anal = SensitivityAnalysis(self, analDict['outputs'],
                                               analDict['subType'])
                elif type == UQAnalysis.VISUALIZATION:
                    from Visualization import Visualization
                    anal = Visualization(self, analDict['outputs'],
                                         analDict['inputs'])
                else:  #RS Analyses
                    userRegressionFile = analDict[
                        'userRegressionFile'] if 'userRegressionFile' in analDict else None
                    if type == UQAnalysis.RS_VALIDATION:
                        from RSValidation import RSValidation
                        testFile = analDict[
                            'testFile'] if 'testFile' in analDict else None
                        anal = RSValidation(self, analDict['outputs'],
                                            analDict['rs'],
                                            analDict['rsOptions'],
                                            analDict['genCodeFile'],
                                            analDict['nCV'],
                                            userRegressionFile, testFile)
                    elif type == UQAnalysis.RS_UNCERTAINTY:
                        from RSUncertaintyAnalysis import RSUncertaintyAnalysis
                        anal = RSUncertaintyAnalysis(self, analDict['outputs'],
                                                     analDict['subType'],
                                                     analDict['rs'],
                                                     analDict['rsOptions'],
                                                     userRegressionFile,
                                                     analDict['xprior'])
                    elif type == UQAnalysis.RS_SENSITIVITY:
                        from RSSensitivityAnalysis import RSSensitivityAnalysis
                        anal = RSSensitivityAnalysis(self, analDict['outputs'],
                                                     analDict['subType'],
                                                     analDict['rs'],
                                                     analDict['rsOptions'],
                                                     userRegressionFile,
                                                     analDict['xprior'])
                    elif type == UQAnalysis.INFERENCE:
                        from RSInference import RSInference
                        anal = RSInference(
                            self,
                            analDict['ytable'],
                            analDict['xtable'],
                            analDict['obsTable'],
                            analDict['genPostSample'],
                            analDict['addDisc'],
                            analDict['showList'],
                            userRegressionFile=userRegressionFile)
                    elif type == UQAnalysis.RS_VISUALIZATION:
                        from RSVisualization import RSVisualization
                        anal = RSVisualization(
                            self, analDict['outputs'], analDict['inputs'],
                            analDict['rs'], analDict['minVal'],
                            analDict['maxVal'], analDict['rsOptions'],
                            userRegressionFile)

                anal.loadDict(analDict)
                self.analyses.append(anal)
示例#13
0
    def showRS(fnameRS, y, x, rsdim, rsMethodName, **kwargs):

        from ResponseSurfaces import ResponseSurfaces

        # read data
        data = LocalExecutionModule.readSampleFromPsuadeFile(fnameRS)   # rstype/order written to data
        nSamples = SampleData.getNumSamples(data)
        order = SampleData.getLegendreOrder(data)

        types = data.getInputTypes()
        inputNames = data.getInputNames()
        variableIndices = []
        variableNames = []
        for i in xrange(len(types)):
            if types[i] == Model.VARIABLE:
                variableIndices.append(i + 1)
                variableNames.append(inputNames[i])

        rsIndex = ResponseSurfaces.getEnumValue(rsMethodName)

        # process keyworded arguments
        vmax = np.inf
        vmin = -vmax
        userRegressionFile = None
        setMARS = False
        for key in kwargs:
            k = key.lower()
            if k == 'rsoptions': 
                rsOptions = kwargs[key]
                if rsIndex == ResponseSurfaces.LEGENDRE: 
                    if rsOptions is None:
                        error = 'Visualizer: In function showRS(), "legendreOrder" is required for LEGENDRE response surface.'
                        Common.showError(error)
                        return None
                    else:
                        if isinstance(rsOptions, dict):
                            legendreOrder = rsOptions['legendreOrder']
                        else:
                            legendreOrder = rsOptions
                        if type(legendreOrder) == int:
                            order = legendreOrder
                        else:
                            error = 'Visualizer: In function showRS(), "legendreOrder" is required for LEGENDRE response surface.'
                            Common.showError(error)
                            return None
                elif rsIndex in [ResponseSurfaces.MARS, ResponseSurfaces.MARSBAG]: # check for MARS options
                    if rsOptions is not None:
                        from RSAnalyzer import RSAnalyzer
                        marsOptions = RSAnalyzer.checkMARS(data, rsOptions)
                        if marsOptions is not None:
                            marsBases, marsInteractions, marsNormOutputs = marsOptions
                            setMARS = True
            elif k == 'vmin':
                vmin = kwargs[key]
            elif k == 'vmax':
                vmax = kwargs[key]
            elif k == 'userregressionfile':
                userRegressionFile = kwargs[key]

        # check user arguments
        if rsdim < 1 or rsdim > 3:
            error = 'Visualizer: showRS() supports only rs1, rs2 and rs3.'
            Common.showError(error)
            return None
        nx = len(x)
        if nx != rsdim:
            error = 'Visualizer: showRS() expects x to be a list of length %d.' % rsdim
            Common.showError(error)
            return None
        uniqx = list(set(x))
        if nx != len(uniqx):
            error = 'Visualizer: showRS() expects unique elements in x.'
            Common.showError(error)
            return None
        if vmin >= vmax:
            error = 'Visualizer: showRS() requires vmin to be less than vmax.'
            Common.showError(error)
            return None

        # write script
        cmd = 'rs%d' % rsdim
        f = tempfile.SpooledTemporaryFile()
        if setMARS:
            f.write('rs_expert\n')
        if platform.system() == 'Windows':
            import win32api
            fnameRS = win32api.GetShortPathName(fnameRS)
        f.write('load %s\n' % fnameRS)
        if nSamples > 4000:
            f.write('rsmax %d\n' % nSamples)
        f.write('%s\n' % cmd)
        ngrid = 0
        if rsdim == 2:
            ngrid = 256              # select grid resolution (32-256)
            f.write('%d\n' % ngrid)
        elif rsdim == 3:
            ngrid = 32               # select grid resolution (16-32)
            f.write('%d\n' % ngrid)
        f.write('%d\n' % rsIndex)    # select response surface
        if rsIndex == ResponseSurfaces.USER and userRegressionFile is not None:
            f.write('1\n')                         # number of basis functions
            f.write('%s\n' % userRegressionFile)   # surrogate file
            f.write('y\n')                         # apply auxillary arg (output index)
            outVarNames = data.getOutputNames()
            outName = outVarNames[y - 1]
            outName = Common.getUserRegressionOutputName(outName, userRegressionFile, data)
            f.write('%s\n' % outName)              # output name
        elif setMARS:
            if rsIndex == ResponseSurfaces.MARSBAG:
                f.write('0\n')    # mean (0) or median (1) mode
                f.write('100\n')   # number of MARS instantiations [range:10-5000, default=100]
                                  ### TO DO: revert back to 100 for deployment
            f.write('%d\n' % marsBases)
            f.write('%d\n' % marsInteractions)
            if rsIndex == ResponseSurfaces.MARS:
                f.write('%s\n' % marsNormOutputs)
        nInputs = SampleData.getNumInputs(data)
        if nInputs > rsdim:
            for d in xrange(0,rsdim):
                #f.write('%d\n' % (variableIndices.index(x[d]) + 1))   # select input
                f.write('%d\n' % (variableNames.index(x[d]) + 1))   # select input
            f.write('y\n')               # set nominal values for other inputs
        elif nInputs == rsdim:
            for d in xrange(0,rsdim-1):  # psuade can infer last remaining input
                #f.write('%d\n' % (variableIndices.index(x[d]) + 1))   # select input
                f.write('%d\n' % (variableNames.index(x[d]) + 1))   # select input
        elif nInputs < rsdim:
            error = 'Visualizer: In showRS(), %s cannot be performed on a %d-input system.' % (cmd.upper(), nInputs)
            Common.showError(error)
            return None
        f.write('%d\n' % y)   # select output
        if rsIndex == ResponseSurfaces.LEGENDRE:
            f.write('%d\n' % order)
        f.write('n\n')            # select no for selecting lower threshold
        f.write('n\n')            # select no for selecting upper threshold
        f.write('quit\n')
        f.seek(0)

        # print the psuade script to screen
        #for line in f:
        #    print line.strip()
        #f.seek(0)

        # invoke psuade
        out, error = Common.invokePsuade(f)
        f.close()

        # process error
        if error:
            return None

        # check output file
        mfile = 'matlab' + cmd + '.m'
        if os.path.exists(mfile):
            mfile_ = Visualizer.dname + os.path.sep + mfile
            os.rename(mfile, mfile_)
            mfile = mfile_
        else:
            error = 'Visualizer: %s does not exist.' % mfile
            Common.showError(error, out)
            return None

        Visualizer.showRSPlot(data, y, x, rsdim, ngrid, rsMethodName, vmin, vmax, mfile)
        return mfile