Search in sources :

Example 1 with DataContainer

use of org.knime.core.data.container.DataContainer in project knime-core by knime.

the class Statistics2Table method createNominalValueTable.

/**
 * Create nominal value table containing all possible values together with
 * their occurrences.
 * @param nominal value output table
 * @return data table with nominal values for each column
 */
public DataTable createNominalValueTable(final List<String> nominal) {
    DataTableSpec outSpec = createOutSpecNominal(m_spec, nominal);
    Iterator[] it = new Iterator[outSpec.getNumColumns() / 2];
    int idx = 0;
    for (int i = 0; i < m_nominalValues.length; i++) {
        if (m_nominalValues[i] != null) {
            it[idx++] = m_nominalValues[i].entrySet().iterator();
        }
    }
    DataContainer cont = new DataContainer(outSpec);
    int rowIndex = 0;
    do {
        boolean addEnd = true;
        DataCell[] cells = new DataCell[2 * it.length];
        for (int i = 0; i < it.length; i++) {
            if (it[i] != null && it[i].hasNext()) {
                Map.Entry<DataCell, Integer> e = (Map.Entry<DataCell, Integer>) it[i].next();
                cells[2 * i] = e.getKey();
                cells[2 * i + 1] = new IntCell(e.getValue());
                addEnd = false;
            } else {
                cells[2 * i] = DataType.getMissingCell();
                cells[2 * i + 1] = DataType.getMissingCell();
            }
        }
        if (addEnd) {
            break;
        }
        cont.addRowToTable(new DefaultRow(RowKey.createRowKey(rowIndex++), cells));
    } while (true);
    cont.close();
    return cont.getTable();
}
Also used : DataTableSpec(org.knime.core.data.DataTableSpec) IntCell(org.knime.core.data.def.IntCell) MutableInteger(org.knime.core.util.MutableInteger) DataContainer(org.knime.core.data.container.DataContainer) Entry(java.util.Map.Entry) Iterator(java.util.Iterator) RowIterator(org.knime.core.data.RowIterator) DataCell(org.knime.core.data.DataCell) DefaultRow(org.knime.core.data.def.DefaultRow) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 2 with DataContainer

use of org.knime.core.data.container.DataContainer in project knime-core by knime.

the class TreeEnsembleStatisticsNodeModel method execute.

@Override
protected PortObject[] execute(final PortObject[] inObjects, final ExecutionContext exec) throws Exception {
    TreeEnsembleModel treeEnsemble = ((TreeEnsembleModelPortObject) inObjects[0]).getEnsembleModel();
    EnsembleStatistic ensembleStats = new EnsembleStatistic(treeEnsemble);
    DataContainer containerEnsembleStats = exec.createDataContainer(createEnsembleStatsSpec());
    DataCell[] cells = new DataCell[7];
    cells[0] = new IntCell(treeEnsemble.getNrModels());
    cells[1] = new IntCell(ensembleStats.getMinLevel());
    cells[2] = new IntCell(ensembleStats.getMaxLevel());
    cells[3] = new DoubleCell(ensembleStats.getAvgLevel());
    cells[4] = new IntCell(ensembleStats.getMinNumNodes());
    cells[5] = new IntCell(ensembleStats.getMaxNumNodes());
    cells[6] = new DoubleCell(ensembleStats.getAvgNumNodes());
    containerEnsembleStats.addRowToTable(new DefaultRow(RowKey.createRowKey(0L), cells));
    containerEnsembleStats.close();
    DataContainer containerTreeStats = exec.createDataContainer(createTreeStatsSpec());
    for (int i = 0; i < treeEnsemble.getNrModels(); i++) {
        DataCell[] treeCells = new DataCell[2];
        TreeStatistic treeStat = ensembleStats.getTreeStatistic(i);
        treeCells[0] = new IntCell(treeStat.getNumLevels());
        treeCells[1] = new IntCell(treeStat.getNumNodes());
        containerTreeStats.addRowToTable(new DefaultRow(RowKey.createRowKey((long) i), treeCells));
    }
    containerTreeStats.close();
    return new PortObject[] { (PortObject) containerEnsembleStats.getTable(), (PortObject) containerTreeStats.getTable() };
}
Also used : TreeEnsembleModelPortObject(org.knime.base.node.mine.treeensemble2.model.TreeEnsembleModelPortObject) TreeStatistic(org.knime.base.node.mine.treeensemble2.statistics.TreeStatistic) TreeEnsembleModel(org.knime.base.node.mine.treeensemble2.model.TreeEnsembleModel) DataContainer(org.knime.core.data.container.DataContainer) DoubleCell(org.knime.core.data.def.DoubleCell) DataCell(org.knime.core.data.DataCell) EnsembleStatistic(org.knime.base.node.mine.treeensemble2.statistics.EnsembleStatistic) DefaultRow(org.knime.core.data.def.DefaultRow) TreeEnsembleModelPortObject(org.knime.base.node.mine.treeensemble2.model.TreeEnsembleModelPortObject) PortObject(org.knime.core.node.port.PortObject) IntCell(org.knime.core.data.def.IntCell)

Example 3 with DataContainer

use of org.knime.core.data.container.DataContainer in project knime-core by knime.

the class ColorExtractNodeModel method extractColorTable.

/**
 * @param nom
 * @return
 * @throws InvalidSettingsException
 */
private DataTable extractColorTable(final ColorModelNominal nom) throws InvalidSettingsException {
    DataType superType = null;
    for (DataCell c : nom) {
        if (superType == null) {
            superType = c.getType();
        } else {
            superType = DataType.getCommonSuperType(superType, c.getType());
        }
    }
    if (superType == null) {
        throw new InvalidSettingsException("No nominal values in model");
    }
    DataTableSpec spec = createSpec(superType);
    DataContainer cnt = new DataContainer(spec);
    int counter = 0;
    for (DataCell c : nom) {
        Color clr = nom.getColorAttr(c).getColor();
        DataRow row = new DefaultRow(RowKey.createRowKey(counter++), c, new IntCell(clr.getRed()), new IntCell(clr.getGreen()), new IntCell(clr.getBlue()), new IntCell(clr.getAlpha()), new IntCell(clr.getRGB()));
        cnt.addRowToTable(row);
    }
    cnt.close();
    return cnt.getTable();
}
Also used : DataTableSpec(org.knime.core.data.DataTableSpec) DataContainer(org.knime.core.data.container.DataContainer) InvalidSettingsException(org.knime.core.node.InvalidSettingsException) Color(java.awt.Color) DataType(org.knime.core.data.DataType) DataCell(org.knime.core.data.DataCell) DefaultRow(org.knime.core.data.def.DefaultRow) DataRow(org.knime.core.data.DataRow) IntCell(org.knime.core.data.def.IntCell)

Example 4 with DataContainer

use of org.knime.core.data.container.DataContainer in project knime-core by knime.

the class LiftChartNodeModel method execute.

/**
 * {@inheritDoc}
 */
@Override
protected BufferedDataTable[] execute(final BufferedDataTable[] inData, final ExecutionContext exec) throws Exception {
    ConvenienceMethods.checkTableSize(inData[0]);
    int predColIndex = inData[0].getDataTableSpec().findColumnIndex(m_responseColumn.getStringValue());
    List<String> inclList = new LinkedList<String>();
    inclList.add(m_probabilityColumn.getStringValue());
    boolean[] order = new boolean[] { false };
    SortedTable st = new SortedTable(inData[0], inclList, order, exec);
    long totalResponses = 0;
    double partWidth = Double.parseDouble(m_intervalWidth.getStringValue());
    int nrParts = (int) Math.ceil(100.0 / partWidth);
    List<Integer> positiveResponses = new LinkedList<Integer>();
    int rowIndex = 0;
    for (DataRow row : st) {
        if (row.getCell(predColIndex).isMissing()) {
            setWarningMessage("There are missing values." + " Please check your data.");
            continue;
        }
        String response = ((StringValue) row.getCell(predColIndex)).getStringValue().trim();
        if (response.equalsIgnoreCase(m_responseLabel.getStringValue())) {
            totalResponses++;
            positiveResponses.add(rowIndex);
        }
        rowIndex++;
    }
    int[] counter = new int[nrParts];
    int partWidthAbsolute = (int) Math.ceil(rowIndex / (double) nrParts);
    double avgResponse = (double) positiveResponses.size() / rowIndex;
    for (int rIndex : positiveResponses) {
        int index = rIndex / partWidthAbsolute;
        counter[index]++;
    }
    DataColumnSpec[] colSpec = new DataColumnSpec[3];
    colSpec[0] = new DataColumnSpecCreator("Lift", DoubleCell.TYPE).createSpec();
    colSpec[1] = new DataColumnSpecCreator("Baseline", DoubleCell.TYPE).createSpec();
    colSpec[2] = new DataColumnSpecCreator("Cumulative Lift", DoubleCell.TYPE).createSpec();
    DataTableSpec tableSpec = new DataTableSpec(colSpec);
    DataContainer cont = exec.createDataContainer(tableSpec);
    colSpec = new DataColumnSpec[2];
    colSpec[0] = new DataColumnSpecCreator("Actual", DoubleCell.TYPE).createSpec();
    colSpec[1] = new DataColumnSpecCreator("Baseline", DoubleCell.TYPE).createSpec();
    tableSpec = new DataTableSpec(colSpec);
    DataContainer responseCont = exec.createDataContainer(tableSpec);
    long cumulativeCounter = 0;
    responseCont.addRowToTable(new DefaultRow(new RowKey("0"), 0.0, 0.0));
    for (int i = 0; i < counter.length; i++) {
        cumulativeCounter += counter[i];
        double responseRate = (double) counter[i] / partWidthAbsolute;
        double lift = responseRate / avgResponse;
        double cumResponseRate = (double) cumulativeCounter / totalResponses;
        long number = partWidthAbsolute * (i + 1);
        // well.. rounding problems
        if (number > rowIndex) {
            number = rowIndex;
        }
        double cumulativeLift = // (double)cumulativeCounter / (partWidthAbsolute * (i + 1));
        (double) cumulativeCounter / number;
        cumulativeLift /= avgResponse;
        // cumulativeLift = lifts / (i+1);
        double rowKey = ((i + 1) * partWidth);
        if (rowKey > 100) {
            rowKey = 100;
        }
        cont.addRowToTable(new DefaultRow(new RowKey("" + rowKey), lift, 1.0, cumulativeLift));
        double cumBaseline = (i + 1) * partWidth;
        if (cumBaseline > 100) {
            cumBaseline = 100;
        }
        responseCont.addRowToTable(new DefaultRow(new RowKey("" + rowKey), cumResponseRate * 100, cumBaseline));
    }
    cont.close();
    responseCont.close();
    m_dataArray[0] = new DefaultDataArray(cont.getTable(), 1, (int) cont.size());
    m_dataArray[1] = new DefaultDataArray(responseCont.getTable(), 1, (int) responseCont.size());
    return new BufferedDataTable[] { st.getBufferedDataTable() };
}
Also used : DataTableSpec(org.knime.core.data.DataTableSpec) DataColumnSpecCreator(org.knime.core.data.DataColumnSpecCreator) RowKey(org.knime.core.data.RowKey) DefaultDataArray(org.knime.base.node.util.DefaultDataArray) SettingsModelString(org.knime.core.node.defaultnodesettings.SettingsModelString) DataRow(org.knime.core.data.DataRow) LinkedList(java.util.LinkedList) DataContainer(org.knime.core.data.container.DataContainer) DataColumnSpec(org.knime.core.data.DataColumnSpec) SortedTable(org.knime.base.data.sort.SortedTable) BufferedDataTable(org.knime.core.node.BufferedDataTable) DefaultRow(org.knime.core.data.def.DefaultRow)

Example 5 with DataContainer

use of org.knime.core.data.container.DataContainer in project knime-core by knime.

the class AbstractParallelNodeModel method execute.

/**
 * {@inheritDoc}
 */
@Override
protected final BufferedDataTable[] execute(final BufferedDataTable[] data, final ExecutionContext exec) throws Exception {
    final DataTableSpec[] outSpecs = prepareExecute(data);
    final List<Future<BufferedDataContainer[]>> futures = new ArrayList<>();
    final BufferedDataTable[] additionalTables = new BufferedDataTable[Math.max(0, data.length - 1)];
    System.arraycopy(data, 1, additionalTables, 0, additionalTables.length);
    // do some consistency checks to bail out as early as possible
    if (outSpecs == null) {
        throw new NullPointerException("Implementation Error: The " + "array of generated output table specs can't be null.");
    }
    if (outSpecs.length != getNrOutPorts()) {
        throw new IllegalStateException("Implementation Error: Number of" + " provided DataTableSpecs doesn't match number of output" + " ports");
    }
    for (DataTableSpec outSpec : outSpecs) {
        if (outSpec == null) {
            throw new IllegalStateException("Implementation Error: The" + " generated output DataTableSpec is null.");
        }
    }
    final double max = data[0].size();
    final Callable<Void> submitter = new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            final RowIterator it = data[0].iterator();
            BufferedDataContainer container = null;
            int count = 0, chunks = 0;
            while (true) {
                if ((count++ % m_chunkSize == 0) || !it.hasNext()) {
                    exec.checkCanceled();
                    if (container != null) {
                        container.close();
                        final BufferedDataContainer temp = container;
                        chunks++;
                        final int temp2 = chunks;
                        futures.add(m_workers.submit(new Callable<BufferedDataContainer[]>() {

                            @Override
                            public BufferedDataContainer[] call() throws Exception {
                                ExecutionMonitor subProg = exec.createSilentSubProgress((m_chunkSize > max) ? 1 : m_chunkSize / max);
                                exec.setMessage("Processing chunk " + temp2);
                                BufferedDataContainer[] result = new BufferedDataContainer[outSpecs.length];
                                for (int i = 0; i < outSpecs.length; i++) {
                                    result[i] = exec.createDataContainer(outSpecs[i], true, 0);
                                }
                                executeByChunk(temp.getTable(), additionalTables, result, subProg);
                                for (DataContainer c : result) {
                                    c.close();
                                }
                                exec.setProgress(temp2 * m_chunkSize / max);
                                return result;
                            }
                        }));
                    }
                    if (!it.hasNext()) {
                        break;
                    }
                    container = exec.createDataContainer(data[0].getDataTableSpec());
                }
                container.addRowToTable(it.next());
            }
            return null;
        }
    };
    try {
        m_workers.runInvisible(submitter);
    } catch (IllegalThreadStateException ex) {
        // this node has not been started by a thread from a thread pool.
        // This is odd, but may happen
        submitter.call();
    }
    final BufferedDataTable[][] tempTables = new BufferedDataTable[outSpecs.length][futures.size()];
    int k = 0;
    for (Future<BufferedDataContainer[]> results : futures) {
        try {
            exec.checkCanceled();
        } catch (CanceledExecutionException ex) {
            for (Future<BufferedDataContainer[]> cancel : futures) {
                cancel.cancel(true);
            }
            throw ex;
        }
        final BufferedDataContainer[] temp = results.get();
        if ((temp == null) || (temp.length != getNrOutPorts())) {
            throw new IllegalStateException("Invalid result. Execution " + " failed, reason: data is null or number " + "of outputs wrong.");
        }
        for (int i = 0; i < temp.length; i++) {
            tempTables[i][k] = temp[i].getTable();
        }
        k++;
    }
    final BufferedDataTable[] resultTables = new BufferedDataTable[outSpecs.length];
    for (int i = 0; i < resultTables.length; i++) {
        resultTables[i] = exec.createConcatenateTable(exec, tempTables[i]);
    }
    return resultTables;
}
Also used : DataTableSpec(org.knime.core.data.DataTableSpec) BufferedDataContainer(org.knime.core.node.BufferedDataContainer) ArrayList(java.util.ArrayList) Callable(java.util.concurrent.Callable) BufferedDataContainer(org.knime.core.node.BufferedDataContainer) DataContainer(org.knime.core.data.container.DataContainer) CanceledExecutionException(org.knime.core.node.CanceledExecutionException) RowIterator(org.knime.core.data.RowIterator) BufferedDataTable(org.knime.core.node.BufferedDataTable) Future(java.util.concurrent.Future) ExecutionMonitor(org.knime.core.node.ExecutionMonitor)

Aggregations

DataContainer (org.knime.core.data.container.DataContainer)38 DataTableSpec (org.knime.core.data.DataTableSpec)25 DefaultRow (org.knime.core.data.def.DefaultRow)23 DataRow (org.knime.core.data.DataRow)19 DataCell (org.knime.core.data.DataCell)17 BufferedDataTable (org.knime.core.node.BufferedDataTable)17 RowKey (org.knime.core.data.RowKey)12 ArrayList (java.util.ArrayList)9 DoubleCell (org.knime.core.data.def.DoubleCell)9 IntCell (org.knime.core.data.def.IntCell)8 LinkedHashMap (java.util.LinkedHashMap)7 DataColumnSpecCreator (org.knime.core.data.DataColumnSpecCreator)7 PortObject (org.knime.core.node.port.PortObject)7 HashSet (java.util.HashSet)6 DataColumnSpec (org.knime.core.data.DataColumnSpec)6 RowIterator (org.knime.core.data.RowIterator)6 StringCell (org.knime.core.data.def.StringCell)6 Map (java.util.Map)5 Set (java.util.Set)5 SortedTable (org.knime.base.data.sort.SortedTable)5