Example usage for com.google.common.math DoubleMath mean

List of usage examples for com.google.common.math DoubleMath mean

Introduction

In this page you can find the example usage for com.google.common.math DoubleMath mean.

Prototype

@GwtIncompatible("com.google.common.math.DoubleUtils")
public static double mean(Iterator<? extends Number> values) 

Source Link

Document

Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of values .

Usage

From source file:task3.Task3.java

private static float getAvrgPrice(List<Book> books) {
    List<Float> list = new ArrayList<Float>();
    for (Book book : books) {
        list.add(book.getPrice());//w w  w .  java  2  s.  co  m
    }
    return new Float(DoubleMath.mean(list));
}

From source file:de.bund.bfr.knime.pmmlite.core.CombineUtils.java

public static List<TertiaryModel> combine(List<SecondaryModel> dataModels) throws UnitException {
    // 1. find secondary models and data for each primary model
    Map<String, PrimaryModel> primModelMap = new LinkedHashMap<>();
    Map<String, Map<String, Double>> paramMeanMap = new LinkedHashMap<>();
    ListMultimap<String, SecondaryModel> secModelMap = ArrayListMultimap.create();
    ListMultimap<String, TimeSeries> dataMap = ArrayListMultimap.create();

    for (SecondaryModel dataModel : dataModels) {
        PrimaryModel primModel = dataModel.getData().get(0);
        String id = primModel.getFormula().getId();

        if (!primModelMap.containsKey(id)) {
            primModelMap.put(id, primModel);

            ListMultimap<String, Double> paramValues = ArrayListMultimap.create();

            for (PrimaryModel primData : dataModel.getData()) {
                dataMap.put(id, primData.getData());

                for (Parameter param : primModel.getFormula().getParams()) {
                    ParameterValue value = primData.getParamValues().get(param.getName());

                    if (value != null && value.getValue() != null) {
                        paramValues.put(param.getName(), value.getValue());
                    }/*from   w ww  .  j  av  a  2s  . c o m*/
                }
            }

            Map<String, Double> paramMeans = new LinkedHashMap<>();

            for (Map.Entry<String, Collection<Double>> entry : paramValues.asMap().entrySet()) {
                paramMeans.put(entry.getKey(), DoubleMath.mean(Doubles.toArray(entry.getValue())));
            }

            paramMeanMap.put(id, paramMeans);
        }

        secModelMap.put(id, dataModel);
        paramMeanMap.get(id)
                .remove(dataModel.getAssignments().get(dataModel.getFormula().getDepVar().getName()));
    }

    // 2. if secondary does not exist for a parameter create constant model
    // 3. call combine for each primary models with its secondary models
    List<TertiaryModel> tertiaryModels = new ArrayList<>();

    for (Map.Entry<String, PrimaryModel> entry : primModelMap.entrySet()) {
        String id = entry.getKey();
        PrimaryModel primModel = entry.getValue();
        List<SecondaryModel> secModels = secModelMap.get(id);
        List<Model> allModels = new ArrayList<>();

        allModels.add(primModel);
        allModels.addAll(secModels);

        TertiaryModel tertModel = ModelsFactory.eINSTANCE.createTertiaryModel();

        tertModel.setId(Joiner.on("").join(PmmUtils.getIds(allModels)));
        tertModel.setName(Joiner.on("_").join(PmmUtils.getNames(secModels)));

        for (Map.Entry<String, VariableRange> range : primModel.getVariableRanges().entrySet()) {
            tertModel.getVariableRanges().put(range.getKey(), EcoreUtil.copy(range.getValue()));
        }

        for (Map.Entry<String, ParameterValue> value : primModel.getParamValues().entrySet()) {
            tertModel.getParamValues().put(value.getKey(), EcoreUtil.copy(value.getValue()));
        }

        for (SecondaryModel secModel : secModels) {
            String depVarAssignment = secModel.getAssignments()
                    .get(secModel.getFormula().getDepVar().getName());

            tertModel.getParamValues().remove(depVarAssignment);
        }

        List<SecondaryModelFormula> secFormulas = new ArrayList<>();
        Map<String, String> assignments = new LinkedHashMap<>();
        Map<String, Renamings> secondaryRenamings = new LinkedHashMap<>();

        for (SecondaryModel secModel : secModels) {
            SecondaryModelFormula secFormula = secModel.getFormula();
            String depVarAssignment = secModel.getAssignments().get(secFormula.getDepVar().getName());
            Renamings renamings = ModelsFactory.eINSTANCE.createRenamings();

            for (Map.Entry<String, String> assignment : secModel.getAssignments().entrySet()) {
                if (!assignment.getKey().equals(secFormula.getDepVar().getName())) {
                    renamings.getMap().put(assignment.getKey(), assignment.getValue());
                    tertModel.getAssignments().put(assignment.getValue(), assignment.getValue());
                }
            }

            secFormulas.add(secFormula);
            assignments.put(depVarAssignment, secFormula.getId());
            secondaryRenamings.put(depVarAssignment, renamings);

            for (Variable var : secFormula.getIndepVars()) {
                VariableRange range = secModel.getVariableRanges()
                        .get(secModel.getAssignments().get(var.getName()));

                addIndep(tertModel, renamings.getMap().get(var.getName()), EcoreUtil.copy(range));
            }

            for (Map.Entry<String, ParameterValue> value : secModel.getParamValues().entrySet()) {
                addParam(tertModel, value.getKey(), EcoreUtil.copy(value.getValue()));
            }
        }

        for (Parameter param : primModel.getFormula().getParams()) {
            if (!assignments.containsKey(param.getName())) {
                ParameterValue value = ModelsFactory.eINSTANCE.createParameterValue();

                value.setValue(paramMeanMap.get(primModel.getFormula().getId()).get(param.getName()));
                tertModel.getParamValues().put(param.getName(), value);
            }
        }

        for (ParameterValue value : tertModel.getParamValues().values()) {
            value.setError(null);
            value.setP(null);
            value.setT(null);
            value.getCorrelations().clear();
        }

        tertModel.setFormula(combine(primModel.getFormula(), secFormulas, assignments, secondaryRenamings));
        tertModel.getAssignments().putAll(primModel.getAssignments());
        tertModel.getData().addAll(dataMap.get(id));
        tertiaryModels.add(tertModel);
    }

    return tertiaryModels;
}

From source file:de.bund.bfr.math.MathUtils.java

public static Double getR2(double sse, List<Double> targetValues) {
    if (targetValues.size() < 2) {
        return null;
    }/*from  w w w.  ja va 2s.c  o  m*/

    double targetMean = DoubleMath.mean(targetValues);
    double targetTotalSumOfSquares = targetValues.stream().mapToDouble(v -> Math.pow(v - targetMean, 2.0))
            .sum();
    double rSquared = 1 - sse / targetTotalSumOfSquares;

    return Math.max(rSquared, 0.0);
}

From source file:controller.FeatureController.java

public static double[] computeFeatures(float[] y, FilterCoefficients filterCoefficients) {
    double[] x = Util.floatToDouble(y);

    TDoubleArrayList features = new TDoubleArrayList();

    int wlen = 100, noutput = 100;

    float[][] stft = new float[noutput][wlen];

    filtfilt(x, filterCoefficients);/*from  w  ww  .ja  va 2  s  .  c  om*/

    features.add(FastMath.sqrt(StatUtils.variance(x)));
    Skewness skew = new Skewness();
    features.add(skew.evaluate(x));
    Kurtosis kurt = new Kurtosis();
    features.add(kurt.evaluate(x));

    x = Math2.zscore(x);

    double[] d = Math2.diff(Math2.diff(x));
    features.add(Doubles.max(Math2.abs(d)));

    List<float[]> wdec = Entropies.wavedecomposition(Util.doubleToFloat(x));

    features.add(wdec.stream().mapToDouble(e -> FastMath.log(DoubleMath.mean(Math2.abs(Util.floatToDouble(e)))))
            .toArray());

    features.add(Entropies.wpentropy(Util.doubleToFloat(x), 6, 1));
    features.add(wdec.stream().mapToDouble(e -> Entropies.wpentropy(e, 6, 1)).toArray());

    features.add(Signal.lineSpectralPairs(x, 10));
    features.add(Arrays.copyOf(
            Util.floatToDouble(tools.Signal.logAbsStft(Util.doubleToFloat(x), wlen, noutput, stft)), 10));

    double[] x_pos = new double[x.length];
    double[] x_neg = new double[x.length];
    for (int i = 0; i < x.length; i++) {
        x_pos[i] = (x[i] >= 0) ? x[i] : 0;
        x_neg[i] = (x[i] <= 0) ? x[i] : 0;
    }

    features.add(Arrays.copyOf(
            Util.floatToDouble(tools.Signal.logAbsStft(Util.doubleToFloat(x_pos), wlen, noutput, stft)), 10));

    features.add(Arrays.copyOf(
            Util.floatToDouble(tools.Signal.logAbsStft(Util.doubleToFloat(x_neg), wlen, noutput, stft)), 10));
    return features.toArray();
}

From source file:org.matsim.contrib.parking.parkingsearch.evaluation.ParkingSearchEvaluator.java

/**
 * @param distances2//from   w  w  w .  j  av a  2  s  . c o m
 * @param distanceFile
 */
private void writeStats(Map<Id<Link>, List<Double>> map, String distanceFile) {
    BufferedWriter bw = IOUtils.getBufferedWriter(distanceFile);

    try {
        bw.write("LinkId;Average;Min;Max;Arrivals");
        for (Entry<Id<Link>, List<Double>> e : map.entrySet()) {
            bw.newLine();
            bw.write(e.getKey() + ";" + DoubleMath.mean(e.getValue()) + ";" + Collections.min(e.getValue())
                    + ";" + Collections.max(e.getValue()) + ";" + e.getValue().size());

        }
        bw.flush();
        bw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:io.github.msdk.io.mztab.MzTabFileImportMethod.java

@SuppressWarnings({ "unchecked" })
private void addRows(@Nonnull FeatureTable featureTable, @Nonnull MZTabFile mzTabFile) {

    String formula, smiles, inchiKey, description, database, identifier;
    // String dbVersion, reliability, url;
    Double mzCalc = null, featureArea = null;
    Double mzExp;/*  www  .j  ava2s.c om*/
    Float rtAverageValue = null;
    Integer charge = null;

    // Loop through small molecules data
    Collection<SmallMolecule> smallMolecules = mzTabFile.getSmallMolecules();
    for (SmallMolecule smallMolecule : smallMolecules) {
        parsedRows++;
        FeatureTableColumn<Object> column;
        FeatureTableRow currentRow = MSDKObjectBuilder.getFeatureTableRow(featureTable, parsedRows);

        formula = smallMolecule.getChemicalFormula();
        smiles = smallMolecule.getSmiles().toString();
        inchiKey = smallMolecule.getInchiKey().toString();
        description = smallMolecule.getDescription();
        database = smallMolecule.getDatabase();
        // dbVersion = smallMolecule.getDatabaseVersion();
        identifier = smallMolecule.getIdentifier().toString();
        SplitList<Double> rt = smallMolecule.getRetentionTime();
        mzExp = smallMolecule.getExpMassToCharge();

        // if (smallMolecule.getReliability() != null)
        // reliability = smallMolecule.getReliability().toString();
        // if (smallMolecule.getURI() != null)
        // url = smallMolecule.getURI().toString();
        if (smallMolecule.getCalcMassToCharge() != null)
            mzCalc = smallMolecule.getCalcMassToCharge();
        if (smallMolecule.getCharge() != null)
            charge = smallMolecule.getCharge();

        // Calculate average RT if multiple values are available
        if (rt != null && !rt.isEmpty())
            rtAverageValue = (float) DoubleMath.mean(rt);

        // Chromatography Info
        ChromatographyInfo chromatographyInfo = MSDKObjectBuilder
                .getChromatographyInfo1D(SeparationType.UNKNOWN, rtAverageValue);

        // Ion Annotation
        IonAnnotation ionAnnotation = MSDKObjectBuilder.getSimpleIonAnnotation();
        ionAnnotation.setAnnotationId(database);
        ionAnnotation.setDescription(description);
        ionAnnotation.setExpectedMz(mzCalc);
        ionAnnotation.setAnnotationId(identifier);

        // Convert formula to IMolecularFormula using CDK
        if (!Strings.isNullOrEmpty(formula)) {
            IChemObjectBuilder builder = DefaultChemObjectBuilder.getInstance();
            IMolecularFormula cdkFormula = MolecularFormulaManipulator.getMolecularFormula(formula, builder);
            ionAnnotation.setFormula(cdkFormula);
        }

        // Convert SMILES to IAtomContainer using CDK
        if (!Strings.isNullOrEmpty(smiles)) {
            try {
                SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance());
                IAtomContainer chemicalStructure = sp.parseSmiles(smiles);
                ionAnnotation.setChemicalStructure(chemicalStructure);
            } catch (InvalidSmilesException e) {
                e.printStackTrace();
            }
        }

        // Add common data to columns
        // Common column: Id
        column = featureTable.getColumn(ColumnName.ID, null);
        currentRow.setData(column, parsedRows);

        // Common column: m/z
        column = featureTable.getColumn(ColumnName.MZ, null);
        currentRow.setData(column, mzExp);

        // Common column: Chromatography Info
        FeatureTableColumn<ChromatographyInfo> ciColumn = featureTable.getColumn("Chromatography Info", null,
                ChromatographyInfo.class);
        currentRow.setData(ciColumn, chromatographyInfo);

        // Common column: Ion Annotation
        column = featureTable.getColumn(ColumnName.IONANNOTATION, null);
        List<IonAnnotation> ionAnnotations = (List<IonAnnotation>) currentRow.getData(column);
        if (ionAnnotations == null)
            ionAnnotations = new ArrayList<IonAnnotation>();
        ionAnnotations.add(ionAnnotation);
        currentRow.setData(column, ionAnnotations);

        // Common column: Charge
        column = featureTable.getColumn(ColumnName.CHARGE, null);
        if (charge != null)
            currentRow.setData(column, charge);

        // Add data to sample specific columns
        SortedMap<Integer, Assay> assayMap = mzTabFile.getMetadata().getAssayMap();
        for (Entry<Integer, Assay> entry : assayMap.entrySet()) {
            Assay sampleAssay = assayMap.get(entry.getKey());
            int sampleKey = sampleAssay.getId();

            // Abundance - Area
            if (smallMolecule.getAbundanceColumnValue(sampleAssay) != null) {
                featureArea = Double.parseDouble(smallMolecule.getAbundanceColumnValue(sampleAssay).toString());
                column = (FeatureTableColumn<Object>) tableColumns
                        .get("[" + sampleKey + "]_" + ColumnName.AREA.getName());
                currentRow.setData(column, featureArea);
            }

            // Optional columns
            for (String columnName : columnNameArray) {
                if (smallMolecule.getOptionColumnValue(sampleAssay, columnName) != null) {

                    column = (FeatureTableColumn<Object>) tableColumns
                            .get("opt_assay[" + sampleKey + "]_" + columnName);
                    String classType = getDataTypeClass(columnName).getSimpleName();
                    String orgValue = smallMolecule.getOptionColumnValue(sampleAssay, columnName);
                    switch (classType) {
                    case "Float":
                        Float floatValue = Float.parseFloat(orgValue);
                        currentRow.setData(column, floatValue);
                        break;
                    case "Double":
                        Double doubleValue = Double.parseDouble(orgValue);
                        currentRow.setData(column, doubleValue);

                        break;
                    case "Integer":
                        Integer integerValue = Integer.parseInt(orgValue);
                        currentRow.setData(column, integerValue);
                        break;
                    case "ChromatographyInfo":
                        Float rtValue = Float.parseFloat(orgValue);
                        ChromatographyInfo ciValue = MSDKObjectBuilder
                                .getChromatographyInfo1D(SeparationType.UNKNOWN, rtValue);
                        currentRow.setData(column, ciValue);
                        break;
                    }

                }

            }

        }

        // Add row to feature table
        newFeatureTable.addRow(currentRow);

        // Check if cancel is requested
        if (canceled) {
            return;
        }

    }
}

From source file:net.sf.mzmine.modules.peaklistmethods.io.mztabimport.MzTabImportTask.java

private void importSmallMolecules(PeakList newPeakList, MZTabFile mzTabFile,
        Map<Integer, RawDataFile> rawDataFiles) {
    SortedMap<Integer, Assay> assayMap = mzTabFile.getMetadata().getAssayMap();
    Collection<SmallMolecule> smallMolecules = mzTabFile.getSmallMolecules();

    // Loop through SML data
    String formula, description, database, url = "";
    double mzExp = 0, abundance = 0, peak_mz = 0, peak_rt = 0, peak_height = 0, rtValue = 0;
    // int charge = 0;
    int rowCounter = 0;

    for (SmallMolecule smallMolecule : smallMolecules) {

        // Stop the process if cancel() was called
        if (isCanceled())
            return;

        rowCounter++;//from  w ww  .j ava  2s .c o m
        formula = smallMolecule.getChemicalFormula();
        // smile = smallMolecule.getSmiles();
        // inchiKey = smallMolecule.getInchiKey();
        description = smallMolecule.getDescription();
        // species = smallMolecule.getSpecies();
        database = smallMolecule.getDatabase();
        // dbVersion = smallMolecule.getDatabaseVersion();
        // reliability = smallMolecule.getReliability();

        if (smallMolecule.getURI() != null) {
            url = smallMolecule.getURI().toString();
        }

        String identifier = smallMolecule.getIdentifier().toString();
        SplitList<Double> rt = smallMolecule.getRetentionTime();
        // SplitList<Modification> modifications =
        // smallMolecule.getModifications();

        if (smallMolecule.getExpMassToCharge() != null) {
            mzExp = smallMolecule.getExpMassToCharge();
        }
        // if (smallMolecule.getCharge() != null) charge =
        // smallMolecule.getCharge();

        // Calculate average RT if multiple values are available
        if (rt != null && !rt.isEmpty()) {
            rtValue = DoubleMath.mean(rt);
        }

        if ((url != null) && (url.equals("null"))) {
            url = null;
        }
        if (identifier.equals("null")) {
            identifier = null;
        }
        if (description == null && identifier != null) {
            description = identifier;
        }

        // Add shared information to row
        SimplePeakListRow newRow = new SimplePeakListRow(rowCounter);
        newRow.setAverageMZ(mzExp);
        newRow.setAverageRT(rtValue);
        if (description != null) {
            SimplePeakIdentity newIdentity = new SimplePeakIdentity(description, formula, database, identifier,
                    url);
            newRow.addPeakIdentity(newIdentity, false);
        }

        // Add raw data file entries to row
        for (Entry<Integer, RawDataFile> rawDataEntry : rawDataFiles.entrySet()) {

            RawDataFile rawData = rawDataEntry.getValue();
            Assay dataFileAssay = assayMap.get(rawDataEntry.getKey());

            abundance = 0;
            peak_mz = 0;
            peak_rt = 0;
            peak_height = 0;

            if (smallMolecule.getAbundanceColumnValue(dataFileAssay) != null) {
                abundance = smallMolecule.getAbundanceColumnValue(dataFileAssay);
            }

            if (smallMolecule.getOptionColumnValue(dataFileAssay, "peak_mz") != null) {
                peak_mz = Double.parseDouble(smallMolecule.getOptionColumnValue(dataFileAssay, "peak_mz"));
            } else {
                peak_mz = mzExp;
            }

            if (smallMolecule.getOptionColumnValue(dataFileAssay, "peak_rt") != null) {
                peak_rt = Double.parseDouble(smallMolecule.getOptionColumnValue(dataFileAssay, "peak_rt"));
            } else {
                peak_rt = rtValue;
            }

            if (smallMolecule.getOptionColumnValue(dataFileAssay, "peak_height") != null) {
                peak_height = Double
                        .parseDouble(smallMolecule.getOptionColumnValue(dataFileAssay, "peak_height"));
            } else {
                peak_height = 0.0;
            }

            int scanNumbers[] = {};
            DataPoint finalDataPoint[] = new DataPoint[1];
            finalDataPoint[0] = new SimpleDataPoint(peak_mz, peak_height);
            int representativeScan = 0;
            int fragmentScan = 0;
            Range<Double> finalRTRange = Range.singleton(peak_rt);
            Range<Double> finalMZRange = Range.singleton(peak_mz);
            Range<Double> finalIntensityRange = Range.singleton(peak_height);
            FeatureStatus status = FeatureStatus.DETECTED;

            Feature peak = new SimpleFeature(rawData, peak_mz, peak_rt, peak_height, abundance, scanNumbers,
                    finalDataPoint, status, representativeScan, fragmentScan, finalRTRange, finalMZRange,
                    finalIntensityRange);

            if (abundance > 0) {
                newRow.addPeak(rawData, peak);
            }

        }

        // Add row to peak list
        newPeakList.addRow(newRow);

    }
}