Esempio n. 1
0
    def __init__(
            self,
            value=0,
            vmin=0,
            vmax=1,
            vdflt=0,
            # vector=dict(),
            ipvname=None,
            opvname=None,
            unit="",
            vst="user",
            vdesc="",
            tags=[],
            dtype=float,
            dist=Distribution(Distribution.UNIFORM),
    ):
        """
        Initialize the variable list

        Args:
            value: variable value
            vmin: min value
            vmax: max value
            vdflt: default value
            unit: string description of units of measure
            vst: A sring description of a group for the variable {"user", "sinter"}
            vdesc: A sentence or so describing the variable
            tags: List of string tags for the variable
            dtype: type of data {float, int, str, object}
            dist: distribution type for UQ
        """
        self.dtype = dtype
        value = value

        if vmin is None:
            vmin = value
        if vmax is None:
            vmax = value
        if vdflt is None:
            vdflt = value
        self.min = vmin  # maximum value
        self.max = vmax  # minimum value
        self.default = vdflt  # default value
        self.unit = unit  # units of measure
        self.set = vst  # variable set name user or sinter so I know if
        # user added it or from sinter configuration file
        self.desc = vdesc  # variable description
        self.scaled = 0.0  # scaled value for the variable
        self.scaling = "None"  # type of variable scaling
        self.minScaled = 0.0  # scaled minimum
        self.maxScaled = 0.0  # scaled maximum
        self.tags = tags  # set of tags for use in heat integration or
        # other searching and sorting
        self.con = False  # true if the input is set through connection
        self.setValue(value)  # value of the variable
        # self.setVector(vector) # dictionary for vector variables
        self.setType(dtype)
        self.setname(ipvname, opvname)
        self.dist = copy.copy(dist)
Esempio n. 2
0
    def createPsuadeInFile(data, filename, includePDF=True):
        outf = open(filename, 'w')
        outf.write('PSUADE\n')

        #Write inputs
        outf.write('INPUT\n')
        outf.write('   dimension = %d\n' % data.getNumInputs())
        names = data.getInputNames()
        mins = data.getInputMins()
        maxs = data.getInputMaxs()
        indices = list(range(data.getNumInputs()))
        for i, name, minimum, maximum in zip(indices, names, mins, maxs):
            outf.write('   variable %d %s = %e %e\n' %
                       (i + 1, name, minimum, maximum))
        distributions = data.getInputDistributions()
        for i, dist in zip(indices, distributions):
            distType = dist.getDistributionType()
            distParams = dist.getParameterValues()
            if distType == Distribution.SAMPLE:
                outf.write('   PDF %d %c' %
                           (i + 1, Distribution.getPsuadeName(distType)))
                if distParams[0] is not None:
                    filename = distParams[0]
                    if platform.system() == 'Windows':
                        import win32api
                        filename = win32api.GetShortPathName(filename)
                    outf.write(' %s' % filename)
                if distParams[1] is not None:
                    outf.write(' %d' % distParams[1])
                outf.write('\n')
            elif includePDF:  # write out PDF info for all non-uniform PDF types
                if distType != Distribution.UNIFORM:
                    outf.write('   PDF %d %c' %
                               (i + 1, Distribution.getPsuadeName(distType)))
                    if distParams[0] is not None:
                        outf.write(' %e' % distParams[0])
                    if distParams[1] is not None:
                        outf.write(' %e' % distParams[1])
                    outf.write('\n')
        outf.write('END\n')

        #Write outputs
        outf.write('OUTPUT\n')
        if data.getNumOutputs() == 0:
            outf.write('   dimension = 1\n')
            names = ['ghostOuput']
            indices = list(range(1))
            for i, name in zip(indices, names):
                outf.write('   variable %d %s\n' % (i + 1, name))
        else:
            outf.write('   dimension = %d\n' % data.getNumOutputs())
            names = data.getOutputNames()
            indices = list(range(data.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')
        outf.write('   sampling = %s\n' %
                   SamplingMethods.getPsuadeName(data.getSampleMethod()))
        outf.write('   num_samples = %d\n' % data.getNumSamples())
        if data.getSampleMethod() != SamplingMethods.GMOAT:
            outf.write('   randomize\n')
        outf.write('END\n')

        #Write Application
        outf.write('APPLICATION\n')
        driverString = data.getDriverName()
        if driverString is None:
            driverString = 'NONE'
        elif platform.system() == 'Windows':
            if os.path.exists(driverString):
                import win32api
                driverString = win32api.GetShortPathName(driverString)
            else:
                driverString = 'NONE'
        driverString = 'NONE'

        outf.write('   driver = %s\n' % driverString)
        outf.write('   save_frequency = 1\n')
        outf.write('END\n')

        #Write Analysis
        outf.write('ANALYSIS\n')
        outf.write('   diagnostics 2\n')
        outf.write('END\n')

        outf.write('END\n')
        outf.close()
Esempio n. 3
0
    def generateSamples(self):
        # self.setModal(False)

        # Gather all info into SampleData object
        if isinstance(self.model, Model):
            model = copy.deepcopy(self.model)
        #            runData = SampleData(self.model)
        else:
            model = copy.deepcopy(self.model.model)
        #            runData = copy.deepcopy(self.model)

        # Gather distributions from distribution table
        types = []
        modelTypes = self.model.getInputTypes()
        defaults = []
        modelDefaults = self.model.getInputDefaults()
        mins = []
        modelMins = self.model.getInputMins()
        maxs = []
        modelMaxs = self.model.getInputMaxs()
        dists = []
        selectedInputs = []
        # Set sampling scheme to selected or monte carlo if adaptive
        if self.chooseSchemeRadio.isChecked():
            scheme = self.schemesList.currentItem().text()
        else:
            scheme = "Monte Carlo"

        # First get parameters for the model
        row = 0
        for inputNum in range(self.model.getNumInputs()):
            if modelTypes[inputNum] == Model.VARIABLE:
                # Type
                combobox = self.distTable.cellWidget(row, 1)
                if combobox is None:
                    text = self.distTable.item(row, 1).text()
                else:
                    text = combobox.currentText()

                if text == "Fixed":
                    value = Model.FIXED
                else:
                    value = Model.VARIABLE

                types.append(value)
                if value == Model.VARIABLE:
                    selectedInputs.append(inputNum)

                # Defaults
                item = self.distTable.item(row, 2)
                if item is None or len(item.text()) == 0:
                    defaults.append(None)
                else:
                    defaults.append(float(item.text()))

                # Mins
                item = self.distTable.item(row, 3)
                mins.append(float(item.text()))

                # Maxs
                item = self.distTable.item(row, 4)
                maxs.append(float(item.text()))

                row += 1
            else:  # Fixed
                types.append(Model.FIXED)
                defaults.append(modelDefaults[inputNum])
                mins.append(modelMins[inputNum])
                maxs.append(modelMaxs[inputNum])

        # Update model
        model.setInputTypes(types)
        model.setInputDefaults(defaults)
        model.setInputMins(mins)
        model.setInputMaxs(maxs)

        # Create SampleData object
        runData = SampleData(model, self.session)
        runData.setModelName(
            self.session.flowsheet.results.incrimentSetName("UQ_Ensemble"))
        runData.setFromFile(False)

        # Now get distributions for the SampleData object
        numSampleFromFile = 0
        row = 0
        for inputNum in range(self.model.getNumInputs()):
            if modelTypes[inputNum] == Model.VARIABLE:
                # Only collect those that are not fixed to generate inputs
                combobox = self.distTable.cellWidget(row, 5)
                dist = combobox.currentIndex()
                # Check non-uniform distribution and non-Monte Carlo scheme
                if (
                        False
                ):  # dist != Distribution.UNIFORM and SamplingMethods.getEnumValue(scheme) != SamplingMethods.MC:
                    msgbox = QMessageBox()
                    msgbox.setWindowTitle("UQ/Opt GUI Warning")
                    msgbox.setText(
                        "Non-Uniform distributions are not compatible with any "
                        +
                        "sampling scheme other than Monte Carlo!  Please change "
                        +
                        "all distributions back to uniform or select Monte Carlo "
                        + "sampling scheme.")
                    msgbox.setIcon(QMessageBox.Warning)
                    msgbox.exec_()
                    return

                if dist == Distribution.SAMPLE:
                    numSampleFromFile += 1

                dists += [self.distTable.getDistribution(row)]

                row += 1
            else:  # Fixed
                dist = Distribution(Distribution.UNIFORM)
                dists = dists + [dist]

        runData.setInputDistributions(dists)

        numSamples = int(self.numSamplesBox.value())
        runData.setNumSamples(numSamples)
        runData.setSampleMethod(scheme)

        # Check number of samples
        scheme = runData.getSampleMethod()
        newNumSamples = SamplingMethods.validateSampleSize(
            scheme, len(selectedInputs), numSamples)
        if scheme == SamplingMethods.LSA:
            if newNumSamples != numSamples:
                msgbox = QMessageBox()
                msgbox.setWindowTitle("UQ/Opt GUI Warning")
                msgbox.setText(
                    "%s scheme with %d variable inputs requires %d samples! Do you want to proceed?"
                    % (
                        SamplingMethods.getPsuadeName(scheme),
                        len(selectedInputs),
                        newNumSamples,
                    ))
                msgbox.setIcon(QMessageBox.Question)
                msgbox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
                msgbox.setDefaultButton(QMessageBox.Yes)
                response = msgbox.exec_()
                if response == QMessageBox.Yes:
                    runData.setNumSamples(newNumSamples)
                else:
                    return
        elif scheme == SamplingMethods.MOAT or scheme == SamplingMethods.GMOAT:
            if type(newNumSamples) is tuple:
                msgbox = QMessageBox()
                msgbox.setWindowTitle("UQ/Opt GUI Warning")
                msgbox.setText(
                    "%s scheme with %d variable inputs cannot have %d samples! How do you want to proceed?"
                    % (
                        SamplingMethods.getFullName(scheme),
                        len(selectedInputs),
                        numSamples,
                    ))
                msgbox.setIcon(QMessageBox.Question)
                firstValButton = msgbox.addButton(
                    "Change to %d samples" % newNumSamples[0],
                    QMessageBox.AcceptRole)
                secondValButton = msgbox.addButton(
                    "Change to %d samples" % newNumSamples[1],
                    QMessageBox.AcceptRole)
                cancelButton = msgbox.addButton(QMessageBox.Cancel)

                msgbox.exec_()
                if msgbox.clickedButton() == firstValButton:
                    runData.setNumSamples(int(newNumSamples[0]))
                elif msgbox.clickedButton() == secondValButton:
                    runData.setNumSamples(int(newNumSamples[1]))
                else:
                    return

        # Visual indications of processing
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.generateStatusText.setText("Generating...")
        self.generateStatusText.repaint()

        # Generate samples for the variable inputs
        selectedRunData = ExperimentalDesign.generateSamples(
            runData, selectedInputs, self.model.getSelectedOutputs())
        if selectedRunData is None:
            QApplication.restoreOverrideCursor()
            self.generateStatusText.setText("")
            return
        selectedInputData = selectedRunData.getInputData()

        # Add fixed inputs back in
        ##        print runData.getNumSamples()
        fullInputData = [0] * runData.getNumSamples()
        for row in range(runData.getNumSamples()):
            rowData = []
            selectedIndex = 0
            for col in range(runData.getNumInputs()):
                if col in selectedInputs:
                    rowData.append(selectedInputData[row][selectedIndex])
                    selectedIndex = selectedIndex + 1
                else:
                    rowData.append(defaults[col])
            fullInputData[row] = rowData
        runData.setInputData(fullInputData)
        runData.setRunState([0] * runData.getNumSamples())
        self.runData = runData

        # Handle archive of METIS file
        if self.runData.getSampleMethod() == SamplingMethods.METIS:
            if self.currentArchiveData is not None:
                # Common.removeArchive(self.currentArchive)
                self.currentArchiveData.removeArchiveFolder()
                pass
            # Common.archiveFile('psuadeMetisInfo', self.runData.getID())
            self.runData.archiveFile("psuadeMetisInfo")
            self.currentArchiveData = self.runData

        # Restore cursor
        QApplication.restoreOverrideCursor()
        self.generateStatusText.setText("Done!")

        self.samplesGenerated = True
        self.previewButton.setEnabled(True)
        self.doneButton.setEnabled(True)
Esempio n. 4
0
    def loadSampleFile(self):
        if platform.system() == "Windows":
            allFiles = "*.*"
        else:
            allFiles = "*"
        sampleFile, _ = QFileDialog.getOpenFileName(
            self,
            "Load Sample file",
            "",
            "Psuade Files (*.dat *.psuade *.filtered);;Psuade Simple File (*.smp);;CSV (Comma delimited) (*.csv);;All files (%s)"
            % allFiles,
        )
        if not sampleFile:  # Cancelled
            return
        fromSimpleFile = False
        try:
            if sampleFile.endswith(".csv"):
                data = LocalExecutionModule.readSampleFromCsvFile(
                    sampleFile, False)
                inputNames = data.getInputNames()
                if len(inputNames[0]) == 0:
                    fromSimpleFile = True
            else:
                data = LocalExecutionModule.readSampleFromPsuadeFile(
                    sampleFile)
            inputData = data.getInputData()
            numSamples = data.getNumSamples()
            numInputs = data.getNumInputs()
            numLoadVariableInputs = data.getInputTypes().count(Model.VARIABLE)
        except:
            import traceback

            traceback.print_exc()
            try:
                (
                    inputData,
                    _,
                    numInputs,
                    _,
                ) = LocalExecutionModule.readDataFromSimpleFile(sampleFile)
                numSamples = inputData.shape[0]
                numLoadVariableInputs = numInputs
                fromSimpleFile = True
            except:
                QMessageBox.critical(
                    self,
                    "Incorrect format",
                    "File does not have the correct format! Please consult the users manual about the format.",
                )
                return

        # Check compatibility with model.
        # For now, we just check number of inputs ok.
        modelInputTypes = self.model.getInputTypes()
        numModelVariableInputs = modelInputTypes.count(Model.VARIABLE)
        compatible = True
        if fromSimpleFile and numLoadVariableInputs != numModelVariableInputs:
            prompt = (
                "This file does not have the same number of variable inputs (%d) as the setup model (%d)!"
                % (numLoadVariableInputs, numModelVariableInputs))
            compatible = False
        elif not fromSimpleFile:  # Check if input names match
            if numLoadVariableInputs < numModelVariableInputs:
                prompt = (
                    "This file does not have as many variable inputs (%d) as the setup model (%d)!"
                    % (numLoadVariableInputs, numModelVariableInputs))
                compatible = False
            else:
                loadInputNames = data.getInputNames()
                loadInputTypes = data.getInputTypes()
                loadVariableNames = set([
                    loadInputNames[modelIndex]
                    for modelIndex in range(len(loadInputNames))
                    if loadInputTypes[modelIndex] == Model.VARIABLE
                ])
                modelInputNames = self.model.getInputNames()
                modelVariableNames = set([
                    modelInputNames[modelIndex]
                    for modelIndex in range(len(modelInputNames))
                    if modelInputTypes[modelIndex] == Model.VARIABLE
                ])
                if not loadVariableNames <= modelVariableNames:
                    compatible = False
                    prompt = "This file does not have the same variable names as the setup model!"

        if not compatible:
            QMessageBox.warning(self, self.tr("UQ GUI"), self.tr(prompt),
                                QMessageBox.Ok, QMessageBox.Ok)
            return

        # UI indications of success
        self.sampleFileNameEdit.setText(sampleFile)
        self.fileLoaded = True
        self.previewButton.setEnabled(True)
        self.doneButton.setEnabled(True)

        # Create loadData object
        self.loadData = SampleData(self.model)
        self.loadData.setFromFile(False)
        if fromSimpleFile:
            self.loadData.setSampleMethod(SamplingMethods.MC)
        else:
            self.loadData.setSampleMethod(data.getSampleMethod())
        self.loadData.setNumSamples(numSamples)
        resultData = numpy.zeros([numSamples, self.model.getNumInputs()])
        modelDefaults = self.model.getInputDefaults()
        loadIndex = 0
        if fromSimpleFile:
            for modelIndex, modelInType in enumerate(modelInputTypes):
                if modelInType == Model.FIXED:
                    resultData[:, modelIndex] = [modelDefaults[modelIndex]
                                                 ] * numSamples
                else:
                    inDataCol = inputData[:, loadIndex]
                    resultData[:, modelIndex] = inDataCol
                    loadIndex += 1
        else:  # full file
            # Create mapping between model names and load names
            loadDefaults = self.loadData.getInputDefaults()
            for modelIndex, (modelInName, modelInType) in enumerate(
                    zip(modelInputNames, modelInputTypes)):
                if modelInName in loadInputNames:
                    loadIndex = loadInputNames.index(modelInName)
                if modelInType == Model.FIXED:
                    if modelInName in loadInputNames:
                        value = loadDefaults[loadIndex]
                    else:
                        value = modelDefaults[modelIndex]
                    resultData[:, modelIndex] = [value] * numSamples
                else:  # Variable
                    if modelInName not in loadInputNames:
                        resultData[:,
                                   modelIndex] = [modelDefaults[modelIndex]
                                                  ] * numSamples
                    elif loadInputTypes[loadIndex] == Model.FIXED:
                        resultData[:, modelIndex] = [loadDefaults[loadIndex]
                                                     ] * numSamples
                    else:
                        inDataCol = inputData[:, loadIndex]
                        resultData[:, modelIndex] = inDataCol

            self.loadData.setInputDistributions(data.getInputDistributions())

        dists = []
        for modelIndex in range(self.model.getNumInputs()):
            d = Distribution(Distribution.SAMPLE)
            d.setParameterValues(sampleFile, modelIndex + 1)
            dists.append(d)
            self.loadData.setInputDistributions(dists)

        self.loadData.setInputData(resultData)
        self.loadData.setRunState([False] * numSamples)
Esempio n. 5
0
 def updateInputVariables(self):
     '''
         Update the input variables table from the node contents
     '''
     table = self.inputVarTable
     vars = self.node.inVars
     table.clearContents()
     table.setRowCount(len(vars))
     row = 0
     for name in sorted(vars.keys(), key=lambda s: s.lower()):
         var = vars[name]
         if var.con == 1:
             bgColor = QColor(255, 255, 200)
         elif var.con ==2:
             bgColor = QColor(255, 220, 230)
         else:
             bgColor = QColor(255, 255, 255)
         gh.setTableItem(table, row, self.ivCols["Name"], name,
             bgColor=bgColor, editable=False)
         gh.setTableItem(table, row,
             self.ivCols["Value"],
             var.value,
             jsonEnc = True,
             bgColor = bgColor)
         gh.setTableItem(table, row,
             self.ivCols["Default"],
             var.default,
             jsonEnc = True,
             bgColor = bgColor)
         gh.setTableItem(table, row,
             self.ivCols["Min"],
             var.min,
             jsonEnc = True,
             bgColor = bgColor)
         gh.setTableItem(table, row,
             self.ivCols["Max"],
             var.max,
             jsonEnc = True,
             bgColor = bgColor)
         gh.setTableItem(table,
             row, self.ivCols["Tags"],
             var.tags,
             jsonEnc = True,
             bgColor = bgColor)
         gh.setTableItem(table, row,
             self.ivCols["Unit"],
             var.unit,
             bgColor = bgColor)
         gh.setTableItem(table, row,
             self.ivCols["Type"],
             pullDown= ["float", "int", "str"],
             text=var.typeStr(),
             bgColor = bgColor)
         gh.setTableItem(table, row,
             self.ivCols["Description"],
             var.desc,
             bgColor = bgColor)
         gh.setTableItem(table, row,
             self.ivCols["Distribution"],
             Distribution.getFullName(var.dist.type),
             pullDown=Distribution.fullNames,
             bgColor = bgColor)
         gh.setTableItem(table, row,
             self.ivCols["Param 1"],
             var.dist.firstParamValue,
             jsonEnc = True,
             bgColor = bgColor)
         gh.setTableItem(table, row,
             self.ivCols["Param 2"],
             var.dist.secondParamValue,
             jsonEnc = True,
             bgColor = bgColor)
         row += 1
     table.resizeColumnsToContents()
     self.inputVarTable.setSelectionMode(
         QAbstractItemView.ExtendedSelection)
     self.inputVarTable.setSelectionBehavior(
         QAbstractItemView.SelectRows)
Esempio n. 6
0
    def writeOUUdata(outfile, outputs, constraints, derivatives, data, xtable,
                     **kwargs):

        # Charles TODO: Handle y is now a list of inputs
        # Charles TODO: Handle derivatives

        # defaults
        rseed = None
        driver = data.getDriverName()
        if driver is None:
            driver = 'NONE'
        optdriver = data.getOptDriverName()
        if optdriver is None:
            optdriver = 'NONE'
        ensoptdriver = data.getEnsembleOptDriverName()
        if ensoptdriver is None:
            ensoptdriver = 'NONE'
        auxdriver = data.getAuxDriverName()
        if auxdriver is None:
            auxdriver = 'NONE'
        inputLB = None
        inputUB = None
        inputDefaults = None
        distributions = None
        init_input = None

        # process keyworded arguments
        for key in kwargs:
            k = key.lower()
            if k == 'randseed':
                rseed = kwargs[key]
            elif k == 'driver':
                driver = kwargs[key]
            elif k == 'optdriver':
                optdriver = kwargs[key]
            elif k == 'ensoptdriver':
                ensoptdriver = kwargs[key]
            elif k == 'auxdriver':
                auxdriver = kwargs[key]
            elif k == 'inputlowerbounds':
                inputLB = kwargs[key]
            elif k == 'inputupperbounds':
                inputUB = kwargs[key]
            elif k == 'inputpdf':
                distributions = kwargs[key]
            elif k == 'init_input':
                init_input = kwargs[key]

        inputTypes = data.getInputTypes()
        nInputs = data.getNumInputs()
        inputNames = data.getInputNames()
        variableInputIndices = []
        for e in xtable:
            if e['type'] != u'Fixed':
                variableInputIndices.append(inputNames.index(e['name']))
        nVariableInputs = len(variableInputIndices)
        nOutputs = len(outputs)
        nSamples = num_fmin = 1  # number of random restarts
        nConstraints = constraints.count(True)
        nDerivatives = derivatives.count(True)
        totalOutputs = nOutputs + nConstraints + nDerivatives

        f = open(outfile, 'w')
        if init_input:
            f.write('PSUADE_IO\n')
            f.write('%d %d %d\n' % (nVariableInputs, totalOutputs, nSamples))
            f.write("1 0\n")  # assume initial point has not been run
            for x in init_input:
                f.write(' % .16e\n' % x)
            for i in xrange(totalOutputs):
                f.write(' 9.9999999999999997e+34\n')
            f.write("PSUADE_IO\n")

        # TO DO: merge with RSAnalyzer.writeRSdata()
        f.write('PSUADE\n')

        # ... input ...
        numFixed = nInputs - nVariableInputs
        f.write('INPUT\n')
        if numFixed > 0:
            f.write('   num_fixed %d\n' % numFixed)
        f.write('   dimension = %d\n' % nVariableInputs)
        if inputLB is None:
            inputLB = data.getInputMins()
        if inputUB is None:
            inputUB = data.getInputMaxs()
        if inputDefaults is None:
            inputDefaults = data.getInputDefaults()
        indices = range(nInputs)
        variableIndex = 1
        fixedIndex = 1
        for i, name, inType, lb, ub, default in zip(indices, inputNames, \
                             inputTypes, inputLB, inputUB, inputDefaults):
            if i in variableInputIndices:  #inType == Model.VARIABLE:
                f.write('   variable %d %s  =  % .16e  % .16e\n' % \
                        (variableIndex, name, lb, ub))
                variableIndex = variableIndex + 1
            else:
                f.write('   fixed %d %s = % .16e\n' %
                        (fixedIndex, name, default))
                fixedIndex = fixedIndex + 1

        # inject discrete variables in psuade
        opttypes = []
        cnt = 0
        for e in xtable:
            cnt = cnt + 1
            t = e['type']
            if t == u'Opt: Primary Discrete (Z1d)':
                opttypes.append(cnt)

        nn = len(opttypes)
        for ii in range(nn):
            jj = opttypes[ii]
            f.write('   discrete %d\n' % (jj))

        if distributions is None:
            distributions = SampleData.getInputDistributions(data)
        for i, inType, dist in zip(indices, inputTypes, distributions):
            if i in variableInputIndices:  #inType == Model.VARIABLE:
                distType = dist.getDistributionType()
                distParams = dist.getParameterValues()
                if distType != Distribution.UNIFORM:
                    f.write('   PDF %d %c' % (i+1, \
                            Distribution.getPsuadeName(distType)))
                    if distType == Distribution.SAMPLE:
                        error = 'OUU: In function writeOUUdata(), '
                        error = error + 'SAMPLE distribution is not supported.'
                        Common.showError(error)
                        return None
                    else:
                        if distParams[0] is not None:
                            f.write(' % .16e' % distParams[0])
                        if distParams[1] is not None:
                            f.write(' % .16e' % distParams[1])
                    f.write('\n')
        f.write('END\n')

        # ... output ...
        outActive = nOutputs
        nConstrs = 0
        nDerivs = 0
        for ii in range(len(constraints)):
            if constraints[ii]:
                outActive = outActive + 1
                nConstrs = nConstrs + 1
        for ii in range(len(derivatives)):
            if derivatives[ii]:
                outActive = outActive + 1
                nDerivs = nDerivs + 1
        if (nOutputs != 1):
            error = 'OUU: In function writeOUUdata(), '
            error = error + 'multi-objective optimization not supported.'
            Common.showError(error)
            return None
        else:
            if ((nConstrs > 0) and (nDerivs > 0)):
                error = 'OUU: In function writeOUUdata(), '
                error = error + 'LBFGS does not support inequality constraints.'
                Common.showError(error)
                return None
            elif ((nDerivs > 0) and (nDerivs != nVariableInputs)):
                error = 'OUU: In function writeOUUdata(), '
                error = error + 'Number of derivatives not correct'
                Common.showError(error)
                return None

        f.write('OUTPUT\n')
        f.write('   dimension = %d\n' % (outActive))
        outputNames = SampleData.getOutputNames(data)
        for ii in range(nOutputs):
            ind = outputs[ii]
            f.write('   variable %d %s\n' % (ii + 1, outputNames[ind - 1]))
            print('   variable %d %s\n' % (ii + 1, outputNames[ind - 1]))
        outActive = nOutputs + 1
        for ii in range(len(constraints)):
            if constraints[ii]:
                f.write('   variable %d %s\n' % (outActive, outputNames[ii]))
                print('   variable %d %s\n' % (outActive, outputNames[ii]))
                outActive = outActive + 1
        for ii in range(len(derivatives)):
            if derivatives[ii]:
                f.write('   variable %d %s\n' % (outActive, outputNames[ii]))
                print('   variable %d %s\n' % (outActive, outputNames[ii]))
                outActive = outActive + 1
        f.write('END\n')

        # ... method ...
        f.write('METHOD\n')
        f.write('   sampling = MC\n')  # OUU uses this to create
        f.write('   num_samples = 1\n')  # initial guess
        if rseed is not None:
            f.write('random_seed = %d\n' % rseed)  # random seed
        f.write('END\n')

        # ... application ...
        f.write('APPLICATION\n')
        if platform.system() == 'Windows':
            import win32api
            if driver != 'NONE' and driver != 'PSUADE_LOCAL':
                driver = win32api.GetShortPathName(driver)
            if optdriver != 'NONE' and optdriver != 'PSUADE_LOCAL':
                optdriver = win32api.GetShortPathName(optdriver)
            if ensoptdriver != 'NONE' and ensoptdriver != 'PSUADE_LOCAL':
                ensoptdriver = win32api.GetShortPathName(ensoptdriver)
            if auxdriver != 'NONE' and auxdriver != 'PSUADE_LOCAL':
                auxdriver = win32api.GetShortPathName(auxdriver)
        f.write('   driver = %s\n' % driver)
        f.write('   opt_driver = %s\n' % optdriver)
        f.write('   ensemble_opt_driver = %s\n' % ensoptdriver)
        f.write('   aux_opt_driver = %s\n' % auxdriver)
        f.write('   launch_interval = 0\n')
        f.write('END\n')

        # ... analysis ...
        f.write('ANALYSIS\n')
        if (nDerivs > 0):
            f.write('   optimization method = ouu_lbfgs\n')
        else:
            f.write('   optimization method = ouu\n')
        f.write('   optimization num_local_minima = 1\n')
        f.write('   optimization max_feval = 1000000\n')
        f.write('   optimization fmin = 0.0\n')
        f.write('   optimization tolerance = 1.000000e-06\n')
        f.write('   optimization num_fmin = %d\n' % num_fmin)
        f.write('   optimization print_level = 3\n')
        #f.write('   analyzer output_id = %d\n' % y)
        f.write('   analyzer output_id = 1\n')
        f.write('   opt_expert\n')
        f.write('   printlevel 0\n')
        f.write('END\n')

        f.write('END\n')
        f.close()

        return outfile
Esempio n. 7
0
    def __init__(self, info, parent=None):
        super(AnalysisInfoDialog, self).__init__(parent)
        self.setWindowTitle('Analysis Additional Info')
        self.resize(400, 400)
        self.gridLayout = QGridLayout(self)
        self.table = QTableWidget()
        self.table.setRowCount(len(list(info.keys())))
        self.table.setColumnCount(1)

        boldFont = QFont()
        boldFont.setWeight(75)
        boldFont.setBold(True)

        totalHeight = 20
        totalWidth = 50
        row = 0
        for key in list(info.keys()):
            if key in ('xprior', 'xtable', 'ytable', 'obsTable'):
                continue
            #item = QTableWidgetItem(key)
            #self.table.setItem(row, 0, item)
            if isinstance(info[key], (list, tuple)):
                strings = []
                for strItem in info[key]:
                    if isinstance(strItem, dict):
                        ks = list(strItem.keys())
                        for k in ks:
                            if strItem[k] is None:
                                del strItem[k]
                    strings.append(str(strItem))

                item = QTableWidgetItem('\n'.join(strings))
            else:
                item = QTableWidgetItem(str(info[key]))
            self.table.setItem(row, 0, item)
            row += 1
        if row > 0:
            label = QLabel('Additional Info')
            label.setFont(boldFont)
            self.gridLayout.addWidget(label)

            self.gridLayout.addWidget(self.table)
            self.table.horizontalHeader().setHidden(True)
            self.table.setRowCount(row)
            self.table.setVerticalHeaderLabels([key for key in list(info.keys()) if key not in ('xprior', 'xtable', 'ytable', 'obsTable')])
            #self.table.verticalHeader().setHidden(True)
            self.table.setWordWrap(True)
            self.table.resizeColumnsToContents()
            self.table.resizeRowsToContents()

            self.show() # Needed for headers to be correctly sized
            width = 2 + self.table.verticalHeader().width() + self.table.columnWidth(0)
            if self.table.verticalScrollBar().isVisible():
                width += self.table.verticalScrollBar().width()
            self.table.setMinimumWidth(width)
            maxHeight = 3
            for i in range(row):
                maxHeight += self.table.rowHeight(i)
            self.table.setMinimumHeight(maxHeight)

            totalHeight += maxHeight + 20
            if width + 20 > totalWidth:
                totalWidth = width + 20


        # Show table
        for key in info:
            if key in ('xprior', 'xtable', 'ytable', 'obsTable'):
                #self.resize(800, 400)
                values = info[key]
                for d in values:
                    if d is not None and 'type' in d and d['type'] == 'Design':
                        keys = list(d.keys())
                        for k in keys:
                            if k not in ('name', 'type'):
                                del d[k]

                if key == 'ytable':
                    labelString = 'Outputs'
                elif key == 'obsTable':
                    labelString = 'Experiments'
                else:
                    labelString = 'Inputs'
                label = QLabel(labelString)
                label.setFont(boldFont)
                self.gridLayout.addWidget(label)
                table = QTableWidget()
                self.gridLayout.addWidget(table)
                table.setRowCount(len([1 for i in range(len(values)) if values[i] is not None]))

                # column headers
                if key == 'obsTable':
                    inputInfo = info['xtable']
                    designVars = []
                    for d in inputInfo:
                        if 'type' in d and d['type'] == 'Design':
                            designVars.append(d['name'])
                    columnHeaders = [name + ' Value' for name in designVars]
                    outputInfo = info['ytable']
                    outputVars = [d['name'] for d in outputInfo if d is not None]
                    for out in outputVars:
                        columnHeaders.append(out + ' Mean')
                        columnHeaders.append(out + ' Std Dev')
                    table.setColumnCount(len(columnHeaders))
                    table.setHorizontalHeaderLabels(columnHeaders)
                    table.setVerticalHeaderLabels(['Experiment ' + str(num) for num in range(1, len(values) + 1)])
                else:
                    columnSet = set()
                    if key == 'ytable':
                        valuesKeys = ['name', 'rsIndex', 'legendreOrder', 'marsBases', 'marsInteractions',
                                      'userRegressionFile']
                        columnHeaders = ['Output Name', 'RS Type', 'Legendre Order', 'MARS # Basis Functions',
                                         'MARS Deg. of Interaction', 'User Regression File']
                    else: #xprior, xtable
                        valuesKeys = ['name', 'type', 'value', 'pdf', 'param1', 'param2', 'min', 'max']
                        columnHeaders = ['Input Name', 'Type', 'Fixed Value', 'PDF', 'PDF Param 1', 'PDF Param 2', 'Min', 'Max']
                    for d in values:
                        if d is not None:
                            d2 = copy.deepcopy(d)
                            for key in d2:
                                if d2[key] is None:
                                    del d[key]
                            columnSet = columnSet.union(set(d.keys()))
                    table.setColumnCount(len(columnSet))
                    usedColumns = []
                    usedHeaders = []
                    columnIndices = {}
                    for i, (valuesKey, header) in enumerate(zip(valuesKeys, columnHeaders)):
                        if valuesKey in columnSet:
                            usedColumns.append(valuesKey)
                            usedHeaders.append(header)
                            columnIndices[valuesKey] = i
                    table.setHorizontalHeaderLabels(usedHeaders)
                    table.verticalHeader().setHidden(True)
                table.setWordWrap(True)

                r = 0
                for i in range(len(values)):
                    if key == 'obsTable':
                        for c, string in enumerate(values[r][1:]):
                            item = QTableWidgetItem(string)
                            table.setItem(r, c, item)
                        r += 1
                    elif values[r] is not None:
                        for c, colName in enumerate(usedColumns):
                            if colName in values[r]:
                                if colName == 'pdf':
                                    string = Distribution.getFullName(values[r][colName])
                                elif colName == 'rsIndex':
                                    string = ResponseSurfaces.getFullName(values[r][colName])
                                else:
                                    string = str(values[r][colName])
                                item = QTableWidgetItem(string)
                                table.setItem(r, c, item)
                        r += 1
                table.resizeColumnsToContents()

                QtCore.QCoreApplication.processEvents()
                width = 2
                if key == 'obsTable':
                    width += table.verticalHeader().width()
                for i in range(table.columnCount()):
                    width += table.columnWidth(i)
                if table.verticalScrollBar().isVisible():
                    width += table.verticalScrollBar().width()
                if width > 800:
                    width = 800
                table.setMinimumWidth(width)
                maxHeight = 3 + table.horizontalHeader().height()
                for i in range(table.rowCount()):
                    maxHeight += table.rowHeight(i)
                maxHeight = min([maxHeight, 400])
                table.setMinimumHeight(maxHeight)

                totalHeight += maxHeight + 20
                if width + 20 > totalWidth:
                    totalWidth = width + 20


        self.okButton = QPushButton(self)
        self.okButton.setText('OK')
        self.okButton.clicked.connect(self.close)
        self.gridLayout.addWidget(self.okButton)
        self.show()
        self.resize(totalWidth, totalHeight)
Esempio n. 8
0
    def __init__(self, info, parent=None):
        super(AnalysisInfoDialog, self).__init__(parent)
        self.setWindowTitle("Analysis Additional Info")
        self.resize(400, 400)
        self.gridLayout = QGridLayout(self)
        self.table = QTableWidget()
        self.table.setRowCount(len(list(info.keys())))
        self.table.setColumnCount(1)

        boldFont = QFont()
        boldFont.setWeight(75)
        boldFont.setBold(True)

        totalHeight = 20
        totalWidth = 50
        row = 0
        for key in list(info.keys()):
            if key in ("xprior", "xtable", "ytable", "obsTable"):
                continue
            # item = QTableWidgetItem(key)
            # self.table.setItem(row, 0, item)
            if isinstance(info[key], (list, tuple)):
                strings = []
                for strItem in info[key]:
                    if isinstance(strItem, dict):
                        ks = list(strItem.keys())
                        for k in ks:
                            if strItem[k] is None:
                                del strItem[k]
                    strings.append(str(strItem))

                item = QTableWidgetItem("\n".join(strings))
            else:
                item = QTableWidgetItem(str(info[key]))
            self.table.setItem(row, 0, item)
            row += 1
        if row > 0:
            label = QLabel("Additional Info")
            label.setFont(boldFont)
            self.gridLayout.addWidget(label)

            self.gridLayout.addWidget(self.table)
            self.table.horizontalHeader().setHidden(True)
            self.table.setRowCount(row)
            self.table.setVerticalHeaderLabels(
                [
                    key
                    for key in list(info.keys())
                    if key not in ("xprior", "xtable", "ytable", "obsTable")
                ]
            )
            # self.table.verticalHeader().setHidden(True)
            self.table.setWordWrap(True)
            self.table.resizeColumnsToContents()
            self.table.resizeRowsToContents()

            self.show()  # Needed for headers to be correctly sized
            width = 2 + self.table.verticalHeader().width() + self.table.columnWidth(0)
            if self.table.verticalScrollBar().isVisible():
                width += self.table.verticalScrollBar().width()
            self.table.setMinimumWidth(width)
            maxHeight = 3
            for i in range(row):
                maxHeight += self.table.rowHeight(i)
            self.table.setMinimumHeight(maxHeight)

            totalHeight += maxHeight + 20
            if width + 20 > totalWidth:
                totalWidth = width + 20

        # Show table
        for key in info:
            if key in ("xprior", "xtable", "ytable", "obsTable"):
                # self.resize(800, 400)
                values = info[key]
                for d in values:
                    if d is not None and "type" in d and d["type"] == "Design":
                        keys = list(d.keys())
                        for k in keys:
                            if k not in ("name", "type"):
                                del d[k]

                if key == "ytable":
                    labelString = "Outputs"
                elif key == "obsTable":
                    labelString = "Experiments"
                else:
                    labelString = "Inputs"
                label = QLabel(labelString)
                label.setFont(boldFont)
                self.gridLayout.addWidget(label)
                table = QTableWidget()
                self.gridLayout.addWidget(table)
                table.setRowCount(
                    len([1 for i in range(len(values)) if values[i] is not None])
                )

                # column headers
                if key == "obsTable":
                    inputInfo = info["xtable"]
                    designVars = []
                    for d in inputInfo:
                        if "type" in d and d["type"] == "Design":
                            designVars.append(d["name"])
                    columnHeaders = [name + " Value" for name in designVars]
                    outputInfo = info["ytable"]
                    outputVars = [d["name"] for d in outputInfo if d is not None]
                    for out in outputVars:
                        columnHeaders.append(out + " Mean")
                        columnHeaders.append(out + " Std Dev")
                    table.setColumnCount(len(columnHeaders))
                    table.setHorizontalHeaderLabels(columnHeaders)
                    table.setVerticalHeaderLabels(
                        ["Experiment " + str(num) for num in range(1, len(values) + 1)]
                    )
                else:
                    columnSet = set()
                    if key == "ytable":
                        valuesKeys = [
                            "name",
                            "rsIndex",
                            "legendreOrder",
                            "marsBases",
                            "marsInteractions",
                            "userRegressionFile",
                        ]
                        columnHeaders = [
                            "Output Name",
                            "RS Type",
                            "Legendre Order",
                            "MARS # Basis Functions",
                            "MARS Deg. of Interaction",
                            "User Regression File",
                        ]
                    else:  # xprior, xtable
                        valuesKeys = [
                            "name",
                            "type",
                            "value",
                            "pdf",
                            "param1",
                            "param2",
                            "min",
                            "max",
                        ]
                        columnHeaders = [
                            "Input Name",
                            "Type",
                            "Fixed Value",
                            "PDF",
                            "PDF Param 1",
                            "PDF Param 2",
                            "Min",
                            "Max",
                        ]
                    for d in values:
                        if d is not None:
                            d2 = copy.deepcopy(d)
                            for key in d2:
                                if d2[key] is None:
                                    del d[key]
                            columnSet = columnSet.union(set(d.keys()))
                    table.setColumnCount(len(columnSet))
                    usedColumns = []
                    usedHeaders = []
                    columnIndices = {}
                    for i, (valuesKey, header) in enumerate(
                        zip(valuesKeys, columnHeaders)
                    ):
                        if valuesKey in columnSet:
                            usedColumns.append(valuesKey)
                            usedHeaders.append(header)
                            columnIndices[valuesKey] = i
                    table.setHorizontalHeaderLabels(usedHeaders)
                    table.verticalHeader().setHidden(True)
                table.setWordWrap(True)

                r = 0
                for i in range(len(values)):
                    if key == "obsTable":
                        for c, string in enumerate(values[r][1:]):
                            item = QTableWidgetItem(string)
                            table.setItem(r, c, item)
                        r += 1
                    elif values[r] is not None:
                        for c, colName in enumerate(usedColumns):
                            if colName in values[r]:
                                if colName == "pdf":
                                    string = Distribution.getFullName(
                                        values[r][colName]
                                    )
                                elif colName == "rsIndex":
                                    string = ResponseSurfaces.getFullName(
                                        values[r][colName]
                                    )
                                else:
                                    string = str(values[r][colName])
                                item = QTableWidgetItem(string)
                                table.setItem(r, c, item)
                        r += 1
                table.resizeColumnsToContents()

                QtCore.QCoreApplication.processEvents()
                width = 2
                if key == "obsTable":
                    width += table.verticalHeader().width()
                for i in range(table.columnCount()):
                    width += table.columnWidth(i)
                if table.verticalScrollBar().isVisible():
                    width += table.verticalScrollBar().width()
                if width > 800:
                    width = 800
                table.setMinimumWidth(width)
                maxHeight = 3 + table.horizontalHeader().height()
                for i in range(table.rowCount()):
                    maxHeight += table.rowHeight(i)
                maxHeight = min([maxHeight, 400])
                table.setMinimumHeight(maxHeight)

                totalHeight += maxHeight + 20
                if width + 20 > totalWidth:
                    totalWidth = width + 20

        self.okButton = QPushButton(self)
        self.okButton.setText("OK")
        self.okButton.clicked.connect(self.close)
        self.gridLayout.addWidget(self.okButton)
        self.show()
        self.resize(totalWidth, totalHeight)