Search in sources :

Example 86 with PMMLPortObject

use of org.knime.core.node.port.pmml.PMMLPortObject in project knime-core by knime.

the class RulesToTableNodeModel method execute.

/**
 * {@inheritDoc}
 */
@Override
protected BufferedDataTable[] execute(final PortObject[] inData, final ExecutionContext exec) throws Exception {
    PMMLPortObject ruleSetPo = (PMMLPortObject) inData[0];
    PMMLRuleTranslator translator = new PMMLRuleTranslator();
    BufferedDataTable table = new RuleSetToTable(m_settings).execute(exec, ruleSetPo);
    ruleSetPo.initializeModelTranslator(translator);
    List<RuleSelectionMethod> selectionMethodList = translator.getSelectionMethodList();
    if (selectionMethodList.size() != 1 || (selectionMethodList.size() == 1 && !Objects.equals(selectionMethodList.get(0).getCriterion(), RuleSelectionMethod.Criterion.FIRST_HIT))) {
        setWarningMessage("Only a single 'firstHit' rule selection method is supported properly, all others cannot be represented properly. Rule selection methods: " + selectionMethodList);
    }
    return new BufferedDataTable[] { table };
}
Also used : PMMLPortObject(org.knime.core.node.port.pmml.PMMLPortObject) BufferedDataTable(org.knime.core.node.BufferedDataTable) RuleSelectionMethod(org.dmg.pmml.RuleSelectionMethodDocument.RuleSelectionMethod) PMMLRuleTranslator(org.knime.base.node.rules.engine.pmml.PMMLRuleTranslator)

Example 87 with PMMLPortObject

use of org.knime.core.node.port.pmml.PMMLPortObject in project knime-core by knime.

the class RuleEngine2PortsNodeModel method createPMMLPortObject.

/**
 * Creates the {@link PMMLPortObject} based on {@code doc}, {@code ruleSetModel} and {@code ruleSet}.
 *
 * @param doc A {@link PMMLDocument}.
 * @param ruleSetModel The {@link RuleSetModel}.
 * @param ruleSet The {@link RuleSet}.
 * @param parser The {@link PMMLRuleParser} to collect used columns.
 * @param outputSpec The expected output table specification.
 * @return The computed {@link PMMLPortObject} with PMML RuleSet.
 */
private PMMLPortObject createPMMLPortObject(final PMMLDocument doc, final RuleSetModel ruleSetModel, final RuleSet ruleSet, final PMMLRuleParser parser, final DataTableSpec outputSpec) {
    PMMLPortObject pmml = new PMMLPortObject(createPMMLPortObjectSpec(outputSpec, parser.getUsedColumns()));
    // 
    // if (inData[1] != null) {
    // PMMLPortObject po = (PMMLPortObject)inData[1];
    // TransformationDictionary dict = TransformationDictionary.Factory.newInstance();
    // dict.setDerivedFieldArray(po.getDerivedFields());
    // ret.addGlobalTransformations(dict);
    // }
    fillPMMLPortObject(doc, ruleSetModel, ruleSet, pmml);
    return pmml;
}
Also used : PMMLPortObject(org.knime.core.node.port.pmml.PMMLPortObject)

Example 88 with PMMLPortObject

use of org.knime.core.node.port.pmml.PMMLPortObject in project knime-core by knime.

the class RuleEngine2PortsNodeModel method computeRearrangerWithPMML.

/**
 * @param spec
 * @param rules
 * @param flowVars
 * @param ruleIdx
 * @param outcomeIdx
 * @param confidenceIdx
 * @param weightIdx
 * @param validationIdx
 * @param outputColumnName
 * @return
 * @throws InterruptedException
 * @throws InvalidSettingsException
 */
private Pair<ColumnRearranger, PortObject> computeRearrangerWithPMML(final DataTableSpec spec, final RowInput rules, final Map<String, FlowVariable> flowVars, final int ruleIdx, final int outcomeIdx, final int confidenceIdx, final int weightIdx, final int validationIdx, final String outputColumnName) throws InterruptedException, InvalidSettingsException {
    PortObject po;
    ColumnRearranger ret;
    PMMLDocument doc = PMMLDocument.Factory.newInstance();
    final PMML pmmlObj = doc.addNewPMML();
    RuleSetModel ruleSetModel = pmmlObj.addNewRuleSetModel();
    RuleSet ruleSet = ruleSetModel.addNewRuleSet();
    List<DataType> outcomeTypes = new ArrayList<>();
    PMMLRuleParser parser = new PMMLRuleParser(spec, flowVars);
    int lineNo = 0;
    DataRow ruleRow;
    while ((ruleRow = rules.poll()) != null) {
        ++lineNo;
        DataCell rule = ruleRow.getCell(ruleIdx);
        CheckUtils.checkSetting(!rule.isMissing(), "Missing rule in row: " + ruleRow.getKey());
        if (rule instanceof StringValue) {
            StringValue ruleText = (StringValue) rule;
            String r = ruleText.getStringValue().replaceAll("[\r\n]+", " ");
            if (RuleSupport.isComment(r)) {
                continue;
            }
            if (outcomeIdx >= 0) {
                r += " => " + m_settings.asStringFailForMissing(ruleRow.getCell(outcomeIdx));
            }
            ParseState state = new ParseState(r);
            try {
                PMMLPredicate condition = parser.parseBooleanExpression(state);
                SimpleRule simpleRule = ruleSet.addNewSimpleRule();
                setCondition(simpleRule, condition);
                state.skipWS();
                state.consumeText("=>");
                state.skipWS();
                Expression outcome = parser.parseOutcomeOperand(state, null);
                simpleRule.setScore(outcome.toString());
                if (confidenceIdx >= 0) {
                    DataCell confidenceCell = ruleRow.getCell(confidenceIdx);
                    if (!confidenceCell.isMissing()) {
                        if (confidenceCell instanceof DoubleValue) {
                            DoubleValue dv = (DoubleValue) confidenceCell;
                            double confidence = dv.getDoubleValue();
                            simpleRule.setConfidence(confidence);
                        }
                    }
                }
                if (weightIdx >= 0) {
                    DataCell weightCell = ruleRow.getCell(weightIdx);
                    boolean missing = true;
                    if (!weightCell.isMissing()) {
                        if (weightCell instanceof DoubleValue) {
                            DoubleValue dv = (DoubleValue) weightCell;
                            double weight = dv.getDoubleValue();
                            simpleRule.setWeight(weight);
                            missing = false;
                        }
                    }
                    if (missing && m_settings.isHasDefaultWeight()) {
                        simpleRule.setWeight(m_settings.getDefaultWeight());
                    }
                }
                CheckUtils.checkSetting(outcome.isConstant(), "Outcome is not constant in line " + lineNo + " (" + ruleRow.getKey() + ") for rule: " + rule);
                outcomeTypes.add(outcome.getOutputType());
            } catch (ParseException e) {
                ParseException error = Util.addContext(e, r, lineNo);
                throw new InvalidSettingsException("Wrong rule in line: " + ruleRow.getKey() + "\n" + error.getMessage(), error);
            }
        } else {
            CheckUtils.checkSetting(false, "Wrong type (" + rule.getType() + ") of rule: " + rule + "\nin row: " + ruleRow.getKey());
        }
    }
    ColumnRearranger dummy = new ColumnRearranger(spec);
    if (!m_settings.isReplaceColumn()) {
        dummy.append(new SingleCellFactory(new DataColumnSpecCreator(outputColumnName, RuleEngineNodeModel.computeOutputType(outcomeTypes, computeOutcomeType(rules.getDataTableSpec()), true, m_settings.isDisallowLongOutputForCompatibility())).createSpec()) {

            @Override
            public DataCell getCell(final DataRow row) {
                return null;
            }
        });
    }
    PMMLPortObject pmml = createPMMLPortObject(doc, ruleSetModel, ruleSet, parser, dummy.createSpec());
    po = pmml;
    m_copy = copy(pmml);
    String predictionConfidenceColumn = m_settings.getPredictionConfidenceColumn();
    if (predictionConfidenceColumn == null || predictionConfidenceColumn.isEmpty()) {
        predictionConfidenceColumn = RuleEngine2PortsSettings.DEFAULT_PREDICTION_CONFIDENCE_COLUMN;
    }
    ret = PMMLRuleSetPredictorNodeModel.createRearranger(pmml, spec, m_settings.isReplaceColumn(), outputColumnName, m_settings.isComputeConfidence(), DataTableSpec.getUniqueColumnName(dummy.createSpec(), predictionConfidenceColumn), validationIdx);
    return Pair.create(ret, po);
}
Also used : RuleSetModel(org.dmg.pmml.RuleSetModelDocument.RuleSetModel) DataColumnSpecCreator(org.knime.core.data.DataColumnSpecCreator) ArrayList(java.util.ArrayList) PMMLRuleParser(org.knime.base.node.rules.engine.pmml.PMMLRuleParser) ParseState(org.knime.base.node.rules.engine.BaseRuleParser.ParseState) DataRow(org.knime.core.data.DataRow) SimpleRule(org.dmg.pmml.SimpleRuleDocument.SimpleRule) ColumnRearranger(org.knime.core.data.container.ColumnRearranger) DataType(org.knime.core.data.DataType) StringValue(org.knime.core.data.StringValue) PortObject(org.knime.core.node.port.PortObject) PMMLPortObject(org.knime.core.node.port.pmml.PMMLPortObject) InactiveBranchPortObject(org.knime.core.node.port.inactive.InactiveBranchPortObject) SingleCellFactory(org.knime.core.data.container.SingleCellFactory) RuleSet(org.dmg.pmml.RuleSetDocument.RuleSet) PMMLPredicate(org.knime.base.node.mine.decisiontree2.PMMLPredicate) Expression(org.knime.base.node.rules.engine.Expression) DoubleValue(org.knime.core.data.DoubleValue) InvalidSettingsException(org.knime.core.node.InvalidSettingsException) PMMLPortObject(org.knime.core.node.port.pmml.PMMLPortObject) PMML(org.dmg.pmml.PMMLDocument.PMML) DataCell(org.knime.core.data.DataCell) PMMLDocument(org.dmg.pmml.PMMLDocument) ParseException(java.text.ParseException)

Example 89 with PMMLPortObject

use of org.knime.core.node.port.pmml.PMMLPortObject in project knime-core by knime.

the class PMMLRuleEditorNodeModel method createRearrangerAndPMMLModel.

private RearrangerAndPMMLModel createRearrangerAndPMMLModel(final DataTableSpec spec) throws ParseException, InvalidSettingsException {
    final PMMLDocument doc = PMMLDocument.Factory.newInstance();
    final PMML pmml = doc.addNewPMML();
    RuleSetModel ruleSetModel = pmml.addNewRuleSetModel();
    RuleSet ruleSet = ruleSetModel.addNewRuleSet();
    PMMLRuleParser parser = new PMMLRuleParser(spec, getAvailableInputFlowVariables());
    ColumnRearranger rearranger = createRearranger(spec, ruleSet, parser);
    PMMLPortObject ret = new PMMLPortObject(createPMMLPortObjectSpec(rearranger.createSpec(), parser.getUsedColumns()));
    // if (inData[1] != null) {
    // PMMLPortObject po = (PMMLPortObject)inData[1];
    // TransformationDictionary dict = TransformationDictionary.Factory.newInstance();
    // dict.setDerivedFieldArray(po.getDerivedFields());
    // ret.addGlobalTransformations(dict);
    // }
    PMMLRuleTranslator modelTranslator = new PMMLRuleTranslator();
    ruleSetModel.setFunctionName(MININGFUNCTION.CLASSIFICATION);
    ruleSet.setDefaultConfidence(defaultConfidenceValue());
    PMMLMiningSchemaTranslator.writeMiningSchema(ret.getSpec(), ruleSetModel);
    PMMLDataDictionaryTranslator ddTranslator = new PMMLDataDictionaryTranslator();
    ddTranslator.exportTo(doc, ret.getSpec());
    modelTranslator.initializeFrom(doc);
    ret.addModelTranslater(modelTranslator);
    ret.validate();
    return new RearrangerAndPMMLModel(rearranger, ret);
}
Also used : RuleSetModel(org.dmg.pmml.RuleSetModelDocument.RuleSetModel) RuleSet(org.dmg.pmml.RuleSetDocument.RuleSet) ColumnRearranger(org.knime.core.data.container.ColumnRearranger) PMMLPortObject(org.knime.core.node.port.pmml.PMMLPortObject) PMML(org.dmg.pmml.PMMLDocument.PMML) PMMLDocument(org.dmg.pmml.PMMLDocument) PMMLDataDictionaryTranslator(org.knime.core.node.port.pmml.PMMLDataDictionaryTranslator)

Example 90 with PMMLPortObject

use of org.knime.core.node.port.pmml.PMMLPortObject in project knime-core by knime.

the class PMMLRuleSetPredictorNodeModel method execute.

/**
 * {@inheritDoc}
 */
@Override
protected BufferedDataTable[] execute(final PortObject[] inData, final ExecutionContext exec) throws Exception {
    PMMLPortObject obj = (PMMLPortObject) inData[MODEL_INDEX];
    BufferedDataTable data = (BufferedDataTable) inData[DATA_INDEX];
    ColumnRearranger rearranger = createColumnRearranger(obj, data.getSpec(), exec);
    BufferedDataTable table = exec.createColumnRearrangeTable(data, rearranger, exec);
    if (m_doReplaceColumn.getBooleanValue()) {
        DataTableSpec preSpec = table.getSpec();
        DataColumnSpec[] columns = new DataColumnSpec[preSpec.getNumColumns()];
        for (int i = columns.length; i-- > 0; ) {
            columns[i] = preSpec.getColumnSpec(i);
        }
        int columnIndex = data.getSpec().findColumnIndex(m_replaceColumn.getStringValue());
        if (m_addConfidence.getBooleanValue()) {
            ColumnRearranger mover = new ColumnRearranger(table.getSpec());
            // Move confidence to the end
            mover.move(columnIndex, table.getSpec().getNumColumns());
            // Move the result to its place
            mover.move(table.getSpec().getNumColumns() - 2, columnIndex);
            table = exec.createColumnRearrangeTable(table, mover, exec);
        } else {
            DataColumnSpecCreator creator = new DataColumnSpecCreator(columns[columnIndex]);
            creator.setName(m_replaceColumn.getStringValue());
            columns[columnIndex] = creator.createSpec();
            DataTableSpec newSpec = new DataTableSpec(columns);
            table = exec.createSpecReplacerTable(table, newSpec);
        }
    }
    return new BufferedDataTable[] { table };
}
Also used : DataTableSpec(org.knime.core.data.DataTableSpec) ColumnRearranger(org.knime.core.data.container.ColumnRearranger) DataColumnSpec(org.knime.core.data.DataColumnSpec) DataColumnSpecCreator(org.knime.core.data.DataColumnSpecCreator) PMMLPortObject(org.knime.core.node.port.pmml.PMMLPortObject) BufferedDataTable(org.knime.core.node.BufferedDataTable)

Aggregations

PMMLPortObject (org.knime.core.node.port.pmml.PMMLPortObject)90 BufferedDataTable (org.knime.core.node.BufferedDataTable)53 DataTableSpec (org.knime.core.data.DataTableSpec)50 PortObject (org.knime.core.node.port.PortObject)47 ColumnRearranger (org.knime.core.data.container.ColumnRearranger)35 PMMLPortObjectSpec (org.knime.core.node.port.pmml.PMMLPortObjectSpec)25 PMMLPortObjectSpecCreator (org.knime.core.node.port.pmml.PMMLPortObjectSpecCreator)21 InvalidSettingsException (org.knime.core.node.InvalidSettingsException)18 ExecutionContext (org.knime.core.node.ExecutionContext)13 DataColumnSpec (org.knime.core.data.DataColumnSpec)12 DataRow (org.knime.core.data.DataRow)12 DerivedFieldMapper (org.knime.core.node.port.pmml.preproc.DerivedFieldMapper)11 StreamableOperator (org.knime.core.node.streamable.StreamableOperator)11 Node (org.w3c.dom.Node)10 SettingsModelString (org.knime.core.node.defaultnodesettings.SettingsModelString)9 IOException (java.io.IOException)8 DataCell (org.knime.core.data.DataCell)8 PMMLDocument (org.dmg.pmml.PMMLDocument)7 PMMLGeneralRegressionTranslator (org.knime.base.node.mine.regression.pmmlgreg.PMMLGeneralRegressionTranslator)7 StreamableFunction (org.knime.core.node.streamable.StreamableFunction)7