Example usage for org.apache.commons.math.stat.descriptive DescriptiveStatistics getMean

List of usage examples for org.apache.commons.math.stat.descriptive DescriptiveStatistics getMean

Introduction

In this page you can find the example usage for org.apache.commons.math.stat.descriptive DescriptiveStatistics getMean.

Prototype

public double getMean() 

Source Link

Document

Returns the <a href="http://www.xycoon.com/arithmetic_mean.htm"> arithmetic mean </a> of the available values

Usage

From source file:cal.binBased.BinMSnSpectrum.java

public double[] getBin_spectrum(int shift) {
    ArrayList<Double> bin_spec_al = new ArrayList<Double>();
    double binSize = (fragment_tolerance * 2), upperLimit = max_value + 0.00001;
    for (double lowerLimit = min_value; lowerLimit < upperLimit; lowerLimit = lowerLimit + binSize) {
        double tmp_intensity_bin = 0;
        DescriptiveStatistics obj = new DescriptiveStatistics();
        for (Peak p : peakList) {
            double mz = p.getMz() + shift;
            if (mz >= lowerLimit && mz < lowerLimit + binSize) {
                obj.addValue(p.intensity);
            }//  w  w w. ja  v a  2s  . c om
        }
        if (obj.getN() > 0) {
            if (intensities_sum_or_mean_or_median == 0) {
                tmp_intensity_bin = obj.getSum();
            } else if (intensities_sum_or_mean_or_median == 1) {
                tmp_intensity_bin = obj.getMean();
            } else if (intensities_sum_or_mean_or_median == 2) {
                tmp_intensity_bin = obj.getPercentile(50);
            }
        }
        // put every bin_pectrum
        bin_spec_al.add(tmp_intensity_bin);
    }
    // convert an arraylist to double array
    // initiate size of array
    bin_size = bin_spec_al.size();
    double[] bin_spectrum = new double[bin_spec_al.size()];
    for (int i = 0; i < bin_spec_al.size(); i++) {
        bin_spectrum[i] = bin_spec_al.get(i);
    }
    return bin_spectrum;
}

From source file:cal.binBased.BinMSnSpectrum.java

private ArrayList<double[]> prepareBinSpectra() {
    // first prepare bin-spectrum to be filled with zero
    int size = (2 * correctionFactor) + 1;

    ArrayList<double[]> shiftedSpectra = new ArrayList<double[]>(size);
    for (int i = 0; i < size; i++) {
        double[] shiftedSpectrum = new double[bin_size];
        shiftedSpectra.add(shiftedSpectrum);
    }//from ww  w.j a  v a  2  s. c o  m
    // now fill each bin spectrum with correct mz values.
    double binSize = (fragment_tolerance * 2), upperLimit = max_value + 0.00001;
    int current_index = 0;
    for (double lowerLimit = min_value + correctionFactor; lowerLimit < upperLimit
            - correctionFactor; lowerLimit = lowerLimit + binSize) {
        double tmp_intensity_bin = 0;
        DescriptiveStatistics obj = new DescriptiveStatistics();
        for (Peak p : peakList) {
            double mz = p.getMz();
            if (mz >= lowerLimit && mz < lowerLimit + binSize) {
                obj.addValue(p.intensity);
            }
        }
        if (obj.getN() > 0) {
            if (intensities_sum_or_mean_or_median == 0) {
                tmp_intensity_bin = obj.getSum();
            } else if (intensities_sum_or_mean_or_median == 1) {
                tmp_intensity_bin = obj.getMean();
            } else if (intensities_sum_or_mean_or_median == 2) {
                tmp_intensity_bin = obj.getPercentile(50);
            }
        }
        // put every bin_pectrum            
        int filling_index = current_index;
        // check every bin spectrum            
        for (double[] shifted : shiftedSpectra) {
            shifted[filling_index] = tmp_intensity_bin;
            filling_index++;
        }
        current_index++;
    }
    return shiftedSpectra;
}

From source file:hdr_plugin.ImageCompare.java

private void button1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button1ActionPerformed
    ImagePlus imp = WindowManager.getImage(chcStack.getSelectedItem());
    for (int i = 0; i < imp.getNSlices() - 1; i++) {
        DescriptiveStatistics des = new DescriptiveStatistics();
        Object pixels = imp.getImageStack().getPixels(i + 1);
        Object pixels2 = imp.getImageStack().getPixels(i + 2);
        for (int j = 0; j < imp.getWidth() * imp.getHeight(); j++) {
            try {
                // get pixel value at position j and the current channel
                int m = ImageJTools.getPixelValue(pixels, j, imp.getType(), 0);
                int n = ImageJTools.getPixelValue(pixels2, j, imp.getType(), 0);
                des.addValue((double) n / m);
            } catch (TypeNotSupportedException ex) {
                Logger.getLogger(ImageCompare.class.getName()).log(Level.SEVERE, null, ex);
            }/*w w w.j a  va 2  s . co  m*/
        }
        System.out.println(des.getMean());
    }
}

From source file:info.raack.appliancedetection.evaluation.model.EvaluationGroup.java

private void calculateEvaluationMetrics(
        Map<ApplianceEnergyConsumptionDetectionAlgorithm, List<Evaluation>> evaluationInfo) {
    for (ApplianceEnergyConsumptionDetectionAlgorithm algorithm : evaluationInfo.keySet()) {
        // do wattage stats
        DescriptiveStatistics stats = new DescriptiveStatistics();

        List<Evaluation> evaluationList = evaluationInfo.get(algorithm);
        if (evaluationList.size() == 0) {
            throw new IllegalArgumentException(
                    "No evaluations for " + algorithm + " in simulation group " + simulationGroup);
        }/*  w w  w .j  av  a  2  s .c o  m*/
        for (Evaluation evaluation : evaluationList) {
            // calculation produces watts
            stats.addValue((double) (evaluation.getOverallEnergyError())
                    * (3600.0 / (double) (evaluation.getSimulation().getDurationInSeconds())));
        }

        errorMetrics.put(algorithm,
                new Double[] { stats.getMean(), stats.getPercentile(50), stats.getStandardDeviation() });

        //
        stats = new DescriptiveStatistics();

        evaluationList = evaluationInfo.get(algorithm);
        if (evaluationList.size() == 0) {
            throw new IllegalArgumentException(
                    "No evaluations for " + algorithm + " in simulation group " + simulationGroup);
        }
        for (Evaluation evaluation : evaluationList) {
            // calculation produces watts
            stats.addValue((double) (evaluation.getOverallAccuracy()));
        }

        accuracyErrorMetrics.put(algorithm,
                new Double[] { stats.getMean(), stats.getPercentile(50), stats.getStandardDeviation() });

        //
        stats = new DescriptiveStatistics();

        evaluationList = evaluationInfo.get(algorithm);
        if (evaluationList.size() == 0) {
            throw new IllegalArgumentException(
                    "No evaluations for " + algorithm + " in simulation group " + simulationGroup);
        }
        for (Evaluation evaluation : evaluationList) {
            // calculation produces watts
            stats.addValue((double) (evaluation.getStateTransitionAccuracy()));
        }

        stateTransitionAccuracyErrorMetrics.put(algorithm,
                new Double[] { stats.getMean(), stats.getPercentile(50), stats.getStandardDeviation() });

        //
        stats = new DescriptiveStatistics();

        evaluationList = evaluationInfo.get(algorithm);
        if (evaluationList.size() == 0) {
            throw new IllegalArgumentException(
                    "No evaluations for " + algorithm + " in simulation group " + simulationGroup);
        }
        for (Evaluation evaluation : evaluationList) {
            // calculation produces watts
            stats.addValue((double) (evaluation.getStateTransitionRecall()));
        }

        stateTransitionRecallErrorMetrics.put(algorithm,
                new Double[] { stats.getMean(), stats.getPercentile(50), stats.getStandardDeviation() });

        //
        stats = new DescriptiveStatistics();

        evaluationList = evaluationInfo.get(algorithm);
        if (evaluationList.size() == 0) {
            throw new IllegalArgumentException(
                    "No evaluations for " + algorithm + " in simulation group " + simulationGroup);
        }
        for (Evaluation evaluation : evaluationList) {
            // calculation produces watts
            stats.addValue((double) (evaluation.getStateTransitionPrecision()));
        }

        stateTransitionPrecisionErrorMetrics.put(algorithm,
                new Double[] { stats.getMean(), stats.getPercentile(50), stats.getStandardDeviation() });
    }
}

From source file:guineu.modules.dataanalysis.kstest.KSTestTask.java

public void run() {
    try {//  ww w .j a v  a  2s  .  c  o  m
        final Rengine rEngine;
        try {
            rEngine = RUtilities.getREngine();
        } catch (Throwable t) {

            throw new IllegalStateException(
                    "Kolmogorov-Smirnov test requires R but it couldn't be loaded (" + t.getMessage() + ')');
        }
        synchronized (RUtilities.R_SEMAPHORE) {

            DescriptiveStatistics stats = new DescriptiveStatistics();
            // assing the values to the matrix
            for (int row = 0; row < dataset.getNumberRows(); row++) {
                rEngine.eval("x <- vector(mode=\"numeric\",length=" + dataset.getNumberCols() + ")");
                stats.clear();
                PeakListRow peakListRow = dataset.getRow(row);
                for (int c = 0; c < dataset.getNumberCols(); c++) {
                    int r = c + 1;
                    double value = (Double) peakListRow.getPeak(dataset.getAllColumnNames().get(c));
                    rEngine.eval("x[" + r + "] <- " + value);
                    stats.addValue(value);
                }

                rEngine.eval("y <- rnorm(" + dataset.getNumberCols() + ", mean= " + stats.getMean() + ", sd = "
                        + stats.getStandardDeviation() + ")");

                rEngine.eval("result <- ks.test(x,y)");
                long e = rEngine.rniParse("result$p.value", 1);
                long r = rEngine.rniEval(e, 0);
                REXP x = new REXP(rEngine, r);
                double pValue = x.asDouble();
                dataset.getRow(row).setVar("setPValue", pValue);
                if (peakListRow.getID() == 68) {
                    rEngine.eval("write.csv(x, \"x.csv\"");
                }
            }

        }
        rEngine.end();
        setStatus(TaskStatus.FINISHED);
    } catch (Exception ex) {
        Logger.getLogger(KSTestTask.class.getName()).log(Level.SEVERE, null, ex);
        setStatus(TaskStatus.ERROR);
    }
}

From source file:com.joliciel.jochre.graphics.SourceImageImpl.java

public SourceImageImpl(GraphicsServiceInternal graphicsService, String name, BufferedImage image) {
    super(image);
    this.name = name;
    this.setOriginalImage(image);
    this.setGraphicsService(graphicsService);

    this.setWidth(this.getPixelGrabber().getWidth());
    this.setHeight(this.getPixelGrabber().getHeight());

    // to normalise the image, we need to figure out where black and white are
    // we want to leave out anomalies (ink blots!)
    int[] pixelSpread = new int[256];

    // To save on memory
    for (int y = 0; y < this.getHeight(); y++)
        for (int x = 0; x < this.getWidth(); x++) {
            int pixel = this.getPixelGrabber().getPixelBrightness(x, y);
            pixelSpread[pixel]++;// w w w  .j  a v  a  2s .c  om
        }

    if (LOG.isTraceEnabled()) {
        for (int i = 0; i < 256; i++)
            LOG.trace("Brightness " + i + ": " + pixelSpread[i]);
    }

    DescriptiveStatistics countStats = new DescriptiveStatistics();
    for (int i = 0; i < 256; i++) {
        countStats.addValue(pixelSpread[i]);
    }

    int startWhite = -1;
    int endWhite = -1;
    for (int i = 255; i >= 0; i--) {
        if (startWhite < 0 && pixelSpread[i] > countStats.getMean())
            startWhite = i;
        if (startWhite >= 0 && endWhite < 0 && pixelSpread[i] < countStats.getMean()) {
            endWhite = i;
            break;
        }
    }

    LOG.debug("Start white: " + startWhite);
    LOG.debug("End white: " + endWhite);

    DescriptiveStatistics blackCountStats = new DescriptiveStatistics();
    DescriptiveStatistics blackSpread = new DescriptiveStatistics();
    for (int i = 0; i <= endWhite; i++) {
        blackCountStats.addValue(pixelSpread[i]);
        for (int j = 0; j < pixelSpread[i]; j++) {
            blackSpread.addValue(i);
        }
    }

    LOG.debug("mean counts: " + countStats.getMean());
    LOG.debug("mean black counts: " + blackCountStats.getMean());
    LOG.debug("std dev black counts: " + blackCountStats.getStandardDeviation());

    int startBlack = -1;
    for (int i = 0; i < 256; i++) {
        if (pixelSpread[i] > blackCountStats.getMean()) {
            startBlack = i;
            break;
        }
    }
    LOG.debug("Start black: " + startBlack);

    this.setBlackLimit(startBlack);
    this.setWhiteLimit(startWhite);

    this.greyscaleMultiplier = (255.0 / (double) (whiteLimit - blackLimit));

    // use mean + 2 sigma to find the black threshold
    // we make the threshold high (darker) to put more pixels in the letter when analysing
    double blackthresholdCount = blackCountStats.getMean() + (2.0 * blackCountStats.getStandardDeviation());
    LOG.debug("blackthresholdCount: " + blackthresholdCount);

    int blackThresholdValue = endWhite;
    for (int i = endWhite; i >= startBlack; i--) {
        if (pixelSpread[i] < blackthresholdCount) {
            blackThresholdValue = i;
            break;
        }
    }
    LOG.debug("Black threshold value (old): " + blackThresholdValue);
    blackThreshold = (int) Math.round((blackThresholdValue - blackLimit) * greyscaleMultiplier);
    LOG.debug("Black threshold (old): " + blackThreshold);

    blackThresholdValue = (int) Math.round(blackSpread.getPercentile(60.0));
    LOG.debug("Black threshold value (new): " + blackThresholdValue);
    LOG.debug("Black spread 25 percentile: " + (int) Math.round(blackSpread.getPercentile(25.0)));
    LOG.debug("Black spread 50 percentile: " + (int) Math.round(blackSpread.getPercentile(50.0)));
    LOG.debug("Black spread 75 percentile: " + (int) Math.round(blackSpread.getPercentile(75.0)));

    blackThreshold = (int) Math.round((blackThresholdValue - blackLimit) * greyscaleMultiplier);
    LOG.debug("Black threshold (new): " + blackThreshold);

    // use mean + 1 sigma to find the separation threshold
    // we keep threshold low (1 sigma) to encourage letter breaks
    double separationthresholdCount = blackCountStats.getMean()
            + (1.0 * blackCountStats.getStandardDeviation());
    LOG.debug("Separation threshold value: " + separationthresholdCount);

    int separationThresholdValue = endWhite;
    for (int i = endWhite; i >= startBlack; i--) {
        if (pixelSpread[i] < separationthresholdCount) {
            separationThresholdValue = i;
            break;
        }
    }
    LOG.debug("Separation threshold value (old): " + separationThresholdValue);

    separationThresholdValue = (int) Math.round(blackSpread.getPercentile(75.0));
    LOG.debug("Separation threshold value (new): " + separationThresholdValue);
    LOG.debug("Black spread 25 percentile: " + (int) Math.round(blackSpread.getPercentile(25.0)));
    LOG.debug("Black spread 50 percentile: " + (int) Math.round(blackSpread.getPercentile(50.0)));
    LOG.debug("Black spread 75 percentile: " + (int) Math.round(blackSpread.getPercentile(75.0)));

    separationThreshold = (int) Math.round((separationThresholdValue - blackLimit) * greyscaleMultiplier);
    LOG.debug("Separation threshold: " + separationThreshold);

    if (drawPixelSpread)
        this.drawChart(pixelSpread, countStats, blackCountStats, blackSpread, startWhite, endWhite, startBlack,
                blackThresholdValue);
}

From source file:edu.usc.goffish.gopher.sample.N_Hop_Stat_Collector.java

@Override
public void compute(List<SubGraphMessage> subGraphMessages) {

    /**/*ww  w . j av a  2 s  . c  o  m*/
     * We do this in following steps.
     * Calculate stats for each subgraph.
     * Calculate aggregate stats for partition.
     * In this case a single sub-graph will do the aggregation
     * Aggregate partition level stats and combine at the smallest partition.
     */

    if (superStep == 0) {
        SubGraphMessage msg = subGraphMessages.get(0);
        String data = new String(msg.getData());

        String[] dataSplit = data.split("#");
        N = Integer.parseInt(dataSplit[0]);
        String[] vps = dataSplit[1].split(",");
        for (String vp : vps) {
            vantagePoints.add(vp.trim());
        }

        try {

            Iterable<? extends ISubgraphInstance> subgraphInstances = subgraph.getInstances(Long.MIN_VALUE,
                    Long.MAX_VALUE, PropertySet.EmptyPropertySet, subgraph.getEdgeProperties(), false);

            //                        sliceManager.readInstances(subgraph,
            //                        Long.MIN_VALUE, Long.MAX_VALUE,
            //                        PropertySet.EmptyPropertySet, subgraph.getEdgeProperties());

            for (ISubgraphInstance instance : subgraphInstances) {

                Map<String, DescriptiveStatistics> statsMap = new HashMap<String, DescriptiveStatistics>();

                for (TemplateEdge edge : subgraph.edges()) {

                    ISubgraphObjectProperties edgeProps = instance.getPropertiesForEdge(edge.getId());

                    Integer isExist = (Integer) edgeProps.getValue(IS_EXIST_PROP);
                    if (isExist == 1) {
                        String[] vantageIps = ((String) edgeProps.getValue(VANTAGE_IP_PROP)).split(",");
                        String[] latencies = ((String) edgeProps.getValue(LATENCY_PROP)).split(",");
                        String[] hops = ((String) edgeProps.getValue(HOP_PROP)).split(",");

                        Integer[] vantangeIdx = vantageIpIndex(vantageIps);
                        if (vantangeIdx == null) {
                            continue;
                        }

                        for (int i : vantangeIdx) {

                            String vantage = vantageIps[i];
                            String latency = latencies[i];
                            String hop = hops[i];

                            double latency_num = Double.parseDouble(latency);
                            int hop_num = Integer.parseInt(hop);

                            if (latency_num >= 0 && hop_num == N) {
                                if (statsMap.containsKey(vantage)) {

                                    statsMap.get(vantage).addValue(latency_num);

                                } else {

                                    DescriptiveStatistics statistics = new DescriptiveStatistics();
                                    statistics.addValue(latency_num);
                                    statsMap.put(vantage, statistics);

                                }
                            }
                            ;

                        }

                    }

                }

                int c = 0;
                StringBuffer msgBuffer = new StringBuffer();

                for (String v : statsMap.keySet()) {
                    c++;
                    DescriptiveStatistics statistics = statsMap.get(v);
                    String m = createMessageString(v, instance.getTimestampStart(), instance.getTimestampEnd(),
                            statistics.getStandardDeviation(), statistics.getMean(), statistics.getN());

                    if (c == statsMap.keySet().size()) {
                        msgBuffer.append(m);
                    } else {

                        msgBuffer.append(m).append("|");
                    }

                }

                SubGraphMessage subMsg = new SubGraphMessage(msgBuffer.toString().getBytes());

                sentMessage(partition.getId(), subMsg);

            }

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    } else if (superStep == 1) {
        //Ok here every sub-graph will receive message from its own partition.
        //Each message is belongs to a given some time span.
        Map<String, List<String[]>> vantageGroup = new HashMap<String, List<String[]>>();

        for (SubGraphMessage subGraphMessage : subGraphMessages) {

            String msgData = new String(subGraphMessage.getData());
            String[] dataParts = msgData.split("|");

            for (String data : dataParts) {
                String[] vantageParts = data.split(",");
                //Group by vantage point and startTime
                if (vantageGroup.containsKey(vantageParts[0] + "|" + vantageParts[1])) {
                    vantageGroup.get(vantageParts[0] + "|" + vantageParts[1]).add(vantageParts);
                } else {
                    ArrayList<String[]> arrayList = new ArrayList<String[]>();
                    arrayList.add(vantageParts);
                    vantageGroup.put(vantageParts[0] + "|" + vantageParts[1], arrayList);
                }

            }

        }

        for (String key : vantageGroup.keySet()) {

            if (!acquireLock(key)) {
                continue;
            }

            List<String[]> data = vantageGroup.get(key);

            double totalN = 0;
            double totalAvgVal = 0;

            double totalVar = 0;
            for (String[] d : data) {

                //average
                double mean = Double.parseDouble(d[4]);
                long sN = Long.parseLong(d[5]);
                totalN += sN;
                totalAvgVal += mean * sN;

                double sd = Double.parseDouble(d[3]);
                totalVar += ((double) sd * sd) / ((double) sN);

            }

            double avg = totalAvgVal / totalN;
            double newSD = Math.sqrt(totalVar);

            //create message
            //sent to all the partitions except me.
            String msg = key + "," + newSD + "," + avg + "," + totalN;

            for (int pid : partitions) {
                sentMessage(pid, new SubGraphMessage(msg.getBytes()));
            }

        }

    } else if (superStep >= 2) {

        if (partition.getId() == Collections.min(partitions)) {

            Map<String, List<String[]>> group = new HashMap<String, List<String[]>>();

            for (SubGraphMessage msg : subGraphMessages) {

                String data = new String(msg.getData());

                String[] dataParts = data.split(",");

                if (group.containsKey(dataParts[0])) {
                    group.get(dataParts[0]).add(dataParts);
                } else {
                    List<String[]> list = new ArrayList<String[]>();
                    list.add(dataParts);
                    group.put(dataParts[0], list);
                }

            }

            if (!acquireLock("" + partition.getId())) {
                voteToHalt();
                return;
            }

            PrintWriter writer;
            try {

                writer = new PrintWriter(new FileWriter("TimeSeriesStats.csv"));
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
            for (String key : group.keySet()) {

                List<String[]> data = group.get(key);

                double totalN = 0;
                double totalAvgVal = 0;

                double totalVar = 0;
                for (String[] d : data) {

                    //average

                    //key + "," + newSD + "," + avg + "," + totalN;
                    double mean = Double.parseDouble(d[2]);
                    long sN = Long.parseLong(d[3]);
                    totalN += sN;
                    totalAvgVal += mean * sN;

                    double sd = Double.parseDouble(d[1]);
                    totalVar += ((double) sd * sd) / ((double) sN);

                }

                double avg = totalAvgVal / totalN;
                double newSD = Math.sqrt(totalVar);

                String vantage = key.split("|")[0];
                String timeStamp = key.split("|")[1];

                log(writer, vantage, timeStamp, avg, newSD);

            }
            writer.flush();
            voteToHalt();

        }
    }

}

From source file:de.mpicbg.knime.hcs.base.nodes.preproc.ParameterMutualInformation.java

@Override
protected BufferedDataTable[] execute(BufferedDataTable[] inData, ExecutionContext exec) throws Exception {

    BufferedDataTable input = inData[0];

    // Get the parameter and make sure there all double value columns
    List<Attribute> parameters = getParameterList(input);

    // Initialize
    int Np = parameters.size();
    int iterations = Np * 2;
    double[][] mutmatrix = new double[Np][Np];
    double[][] sigmatrix = new double[Np][Np];
    ;//ww  w.  j  a v  a  2s .c o m
    double[][] biamatrix = new double[Np][Np];
    ;

    MutualInformation mutualinfo = new MutualInformation();
    mutualinfo.set_base(logbase.getDoubleValue());
    mutualinfo.set_method(method.getStringValue());
    mutualinfo.set_axeslinking(linkaxes.getBooleanValue());
    if (binning.getIntValue() > 0)
        mutualinfo.set_binning(binning.getIntValue());

    // Load data.
    Double[][] table = new Double[Np][input.getRowCount()];
    int j = 0;
    for (DataRow row : input) {
        int i = 0;
        for (Attribute param : parameters) {
            table[i][j] = param.getDoubleAttribute(row);
            i++;
        }
        j++;
        exec.checkCanceled();
    }
    BufTableUtils.updateProgress(exec, Np, iterations);

    // Calculate mutual information
    for (int a = 0; a < Np; a++) {
        mutualinfo.set_xvector(table[a]);

        for (int b = a; b < Np; b++) {
            mutualinfo.set_yvector(table[b]);

            // Calculate the mutual info.
            Double[] res = mutualinfo.calculate();

            // Put it into the output matrix
            mutmatrix[a][b] = res[0];
            mutmatrix[b][a] = res[0];
            sigmatrix[a][b] = res[1];
            sigmatrix[b][a] = res[1];
            biamatrix[a][b] = res[2];
            biamatrix[b][a] = res[2];
        }
        BufTableUtils.updateProgress(exec, Np + a, iterations);
        exec.checkCanceled();
    }

    // Create Tables
    BufferedDataContainer matrixContainer = exec.createDataContainer(new DataTableSpec(getMatrixSpec()));
    BufferedDataContainer listContainer = exec.createDataContainer(new DataTableSpec(getListSpec()));
    double thresh = threshold.getDoubleValue();
    int numListCol = listContainer.getTableSpec().getNumColumns();

    for (int a = 0; a < Np; a++) {

        // Initialize
        DataCell[] matrixCells = new DataCell[Np];
        DataCell[] listCells = new DataCell[numListCol];
        String similars = "";
        DescriptiveStatistics mutstats = new DescriptiveStatistics();
        DescriptiveStatistics sigstats = new DescriptiveStatistics();
        ;
        DescriptiveStatistics biastats = new DescriptiveStatistics();
        ;

        // Create matrix rows and collect values for statistics.
        for (int b = 0; b < Np; b++) {
            matrixCells[b] = new DoubleCell(mutmatrix[a][b]);
            if (a != b) {
                mutstats.addValue(mutmatrix[a][b]);
                sigstats.addValue(sigmatrix[a][b]);
                biastats.addValue(biamatrix[a][b]);
                if (mutmatrix[a][b] > thresh) {
                    similars += parameters.get(b).getName() + ",";
                }
            }
        }

        // Create matrix row
        DataRow matrixRow = new DefaultRow(parameters.get(a).getName(), matrixCells);
        matrixContainer.addRowToTable(matrixRow);

        // Create list row
        listCells[0] = new StringCell(parameters.get(a).getName());
        listCells[1] = new DoubleCell(mutstats.getMin());
        listCells[2] = new DoubleCell(mutstats.getMean());
        listCells[3] = new DoubleCell(mutstats.getMax());
        listCells[4] = new DoubleCell(sigstats.getGeometricMean());
        listCells[5] = new DoubleCell(biastats.getMean());
        listCells[6] = new StringCell(similars);
        DataRow listRow = new DefaultRow("row" + a, listCells);
        listContainer.addRowToTable(listRow);

        exec.checkCanceled();
    }

    matrixContainer.close();
    listContainer.close();
    return new BufferedDataTable[] { listContainer.getTable(), matrixContainer.getTable() };
}

From source file:com.joliciel.jochre.graphics.SourceImageImpl.java

private void drawChart(int[] pixelSpread, DescriptiveStatistics countStats,
        DescriptiveStatistics blackCountStats, DescriptiveStatistics blackSpread, int startWhite, int endWhite,
        int startBlack, int blackThresholdValue) {
    XYSeries xySeries = new XYSeries("Brightness data");
    double maxSpread = 0;
    for (int i = 0; i < 256; i++) {
        xySeries.add(i, pixelSpread[i]);
        if (pixelSpread[i] > maxSpread)
            maxSpread = pixelSpread[i];/*w  w w .j a v a 2s . c  o m*/
    }

    XYSeries keyValues = new XYSeries("Key values");

    XYSeries counts = new XYSeries("Counts");

    counts.add(10.0, countStats.getMean());
    counts.add(100.0, blackCountStats.getMean());
    counts.add(125.0, blackCountStats.getMean() + (1.0 * blackCountStats.getStandardDeviation()));
    counts.add(150.0, blackCountStats.getMean() + (2.0 * blackCountStats.getStandardDeviation()));
    counts.add(175.0, blackCountStats.getMean() + (3.0 * blackCountStats.getStandardDeviation()));
    counts.add(75.0, blackCountStats.getMean() - (1.0 * blackCountStats.getStandardDeviation()));
    counts.add(50.0, blackCountStats.getMean() - (2.0 * blackCountStats.getStandardDeviation()));
    counts.add(25.0, blackCountStats.getMean() - (3.0 * blackCountStats.getStandardDeviation()));
    keyValues.add(startWhite, maxSpread / 4.0);
    keyValues.add(endWhite, maxSpread / 4.0);
    keyValues.add(startBlack, maxSpread / 4.0);
    keyValues.add(blackThresholdValue, maxSpread / 2.0);

    XYSeriesCollection dataset = new XYSeriesCollection(xySeries);
    dataset.addSeries(keyValues);
    dataset.addSeries(counts);
    final ValueAxis xAxis = new NumberAxis("Brightness");
    final ValueAxis yAxis = new NumberAxis("Count");
    yAxis.setUpperBound(maxSpread);
    xAxis.setUpperBound(255.0);

    //final XYItemRenderer  renderer = new XYBarRenderer();
    final XYBarRenderer renderer = new XYBarRenderer();
    renderer.setShadowVisible(false);
    final XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
    plot.setOrientation(PlotOrientation.VERTICAL);
    String title = "BrightnessChart";
    final JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    chart.setBackgroundPaint(Color.white);
    File file = new File("data/" + title + ".png");
    try {
        ChartUtilities.saveChartAsPNG(file, chart, 600, 600);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:com.userweave.module.methoden.iconunderstandability.service.ComputeIconTestStatisticsImpl.java

/**
 * return regression, if regression can be computed
 * @return//from   w w  w .j  a  v  a2 s . c  om
 */
private OverallStatistics computeOverallStatistics() {

    SimpleRegression regression = new SimpleRegression();

    DescriptiveStatistics overallStatistics = DescriptiveStatistics.newInstance();

    Map<Integer, DescriptiveStatistics> iconCount2Statistics = new HashMap<Integer, DescriptiveStatistics>();

    List<Object[]> executionTimesIconCount = testResultDao.findAllValidExecutionTimesAndIconCount();

    if (!executionTimesIconCount.isEmpty()) {

        // check, if there is variation in x (only one x value for all observation yield NaN!)
        boolean canComputeRegression = false;

        int iconCountForFirstResult = ((Long) executionTimesIconCount.get(0)[1]).intValue();

        for (Object[] executionTimeIconCount : executionTimesIconCount) {

            int iconCount = ((Long) executionTimeIconCount[1]).intValue();
            if (iconCount != iconCountForFirstResult) {
                canComputeRegression = true;
            }

            double executionTime = (Long) executionTimeIconCount[0];

            if (isValid(executionTime)) {
                regression.addData(iconCount, executionTime);
                overallStatistics.addValue(executionTime);
                getStatisticsForIconCount(iconCount2Statistics, iconCount).addValue(executionTime);
            }
        }

        if (canComputeRegression) {
            return new OverallStatistics(regression, overallStatistics.getMean(), iconCount2Statistics);
        } else {
            return new OverallStatistics(null, overallStatistics.getMean(), iconCount2Statistics);
        }
    } else {
        return null;
    }
}