Example usage for java.lang Float isInfinite

List of usage examples for java.lang Float isInfinite

Introduction

In this page you can find the example usage for java.lang Float isInfinite.

Prototype

public static boolean isInfinite(float v) 

Source Link

Document

Returns true if the specified number is infinitely large in magnitude, false otherwise.

Usage

From source file:com.bazaarvoice.jackson.rison.RisonGenerator.java

@Override
public void writeNumber(float f) throws IOException, JsonGenerationException {
    if (_cfgNumbersAsStrings ||
    // [JACKSON-139]
            (((Float.isNaN(f) || Float.isInfinite(f))
                    && isEnabled(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS)))) {
        writeString(Float.toString(f));
        return;/*from   ww  w  .  j a  v a2  s  .  c o  m*/
    }
    // What is the max length for floats?
    _verifyValueWrite("write number");
    _writeRaw(formatFloat(f));
}

From source file:com.golemgame.properties.fengGUI.FunctionTab.java

protected void buildGUI() {
    Container tabFrame = super.getTab();
    tabFrame.setLayoutManager(new BorderLayout());

    pane = new KnottedFunctionPane();

    //Add an internal frame with controls for choosing a function
    Container controlFrame = FengGUI.createContainer(tabFrame);
    controlFrame.setLayoutData(BorderLayoutData.NORTH);
    controlFrame.setLayoutManager(new BorderLayout());

    Container controlsNorth = FengGUI.createContainer(controlFrame);
    controlsNorth.setLayoutData(BorderLayoutData.NORTH);
    controlsNorth.setLayoutManager(new RowLayout(false));
    dropDown = FengGUI.<PropertyStore>createComboBox(controlsNorth);

    dropDown.setLayoutData(BorderLayoutData.NORTH);
    dropDown.getAppearance().setPadding(new Spacing(0, 5));

    Container nameContainer = FengGUI.createContainer(controlsNorth);
    nameContainer.setLayoutManager(new BorderLayout());
    Label nameLabel = FengGUI.createLabel(nameContainer,
            StringConstants.get("PROPERTIES.FUNCTIONS.NAME", "Function Name "));
    nameLabel.setLayoutData(BorderLayoutData.WEST);
    functionName = FengGUI.createTextEditor(nameContainer);
    functionName.setMinSize(300, 10);/*from w ww . jav  a  2  s .co  m*/
    functionName.setLayoutData(BorderLayoutData.CENTER);

    controlFrame.layout();

    dropDown.addSelectionChangedListener(new ISelectionChangedListener() {

        public void selectionChanged(SelectionChangedEvent selectionChangedEvent) {

            if (selectionChangedEvent.isSelected()) {
                IToggable<PropertyStore> selected = dropDown.getSelectedItem();

                if (selected == slopeItem) {
                    pane.setEnabled(false);
                    interpreter.setFunctionType(FunctionType.Differentiate);
                    functionName.setText(StringConstants.get("FUNCTIONS.SLOPE", "(Slope)"));
                } else if (selected == areaItem) {//disabled
                    pane.setEnabled(false);
                    interpreter.setFunctionType(FunctionType.AntiDifferentiate);
                    functionName.setText(StringConstants.get("FUNCTIONS.AREA", "(Area)"));
                } else if (selected != null && selected.getValue() != null) {
                    pane.setEnabled(true);
                    interpreter.setFunctionType(FunctionType.Function);
                    loadFrom(selected.getValue().deepCopy());
                    /*FunctionSettingsInterpreter settings = new FunctionSettingsInterpreter(new PropertyStore());
                    settings.setFunction(selected.getValue());
                    setFunction(settings);*/
                }
            }

        }

    });

    controlFrame.updateMinSize();

    controlFrame.pack();

    Container functionContainer = FengGUI.createContainer(tabFrame);
    functionContainer.setLayoutData(BorderLayoutData.CENTER);
    functionContainer.setLayoutManager(new BorderLayout());
    //  pane.setMinSize(20, 20);
    functionContainer.addWidget(pane);

    pane.setLayoutData(BorderLayoutData.CENTER);
    //  pane.getAppearance().setBorder(new Spacing(5,5));        

    horizontal = new ScalingRuler(true, pane);
    horizontal.setLayoutData(BorderLayoutData.SOUTH);
    functionContainer.addWidget(horizontal);

    Container eastContainer = FengGUI.createContainer(functionContainer);
    eastContainer.setLayoutManager(new BorderLayout());
    eastContainer.setLayoutData(BorderLayoutData.EAST);
    vertical = new ScalingRuler(false, pane);
    vertical.setLayoutData(BorderLayoutData.CENTER);
    eastContainer.addWidget(vertical);

    horizontal.getMinSize().setHeight(15);
    horizontal.setSizeToMinSize();
    vertical.getMinSize().setWidth(horizontal.getHeight());

    Spacer spacer = new Spacer(1, horizontal.getHeight());
    eastContainer.addWidget(spacer);
    spacer.setLayoutData(BorderLayoutData.SOUTH);

    Container south = FengGUI.createContainer(getTab());
    //Add controls at the bottom
    south.setLayoutData(BorderLayoutData.SOUTH);
    south.setLayoutManager(new RowLayout(false));
    periodContainer = FengGUI.createContainer(south);

    periodContainer.setLayoutManager(new RowLayout());

    FengGUI.createLabel(periodContainer, "Length(s):");
    time = FengGUI.createTextEditor(periodContainer);
    // FengGUI.createLabel(settingsContainer,"Power (w):");
    power = FengGUI.createTextEditor();//dont add power right now.

    periodicity = FengGUI.createCheckBox(periodContainer, "Periodic:");

    final Container saveContainer = FengGUI.createContainer(south);

    saveContainer.setLayoutManager(new BorderLayout());
    Container saveButtonContainer = FengGUI.createContainer(saveContainer);
    saveButtonContainer.setLayoutData(BorderLayoutData.EAST);
    saveButtonContainer.setLayoutManager(new RowLayout());

    Button saveButton = FengGUI.createButton(saveButtonContainer);

    saveButton.setText("Save Function");

    saveButton.addButtonPressedListener(new IButtonPressedListener() {

        @SuppressWarnings("unchecked")
        public void buttonPressed(ButtonPressedEvent e) {

            PropertyStore newFunction = new PropertyStore();
            set(newFunction);
            PropertyStore effectStore = StateManager.getMachineSpace().getFunctionRepository().getStore();
            //capture the current settings, then add them to the main machine repository (overwriting any existing setting of the same name).
            final PropertyState beforePropertyState = new SimplePropertyState(effectStore,
                    FunctionSettingsRepositoryInterpreter.FUNCTIONS);
            StateManager.getMachineSpace().getFunctionRepository().addFunction(newFunction);

            final PropertyState afterPropertyState = new SimplePropertyState(effectStore,
                    FunctionSettingsRepositoryInterpreter.FUNCTIONS);

            Action<?> action = new Action() {

                @Override
                public String getDescription() {
                    return "Save Function";
                }

                @Override
                public Type getType() {
                    return null;
                }

                @Override
                public boolean doAction() {
                    afterPropertyState.restore();
                    afterPropertyState.refresh();
                    return true;
                }

                @Override
                public boolean undoAction() {
                    beforePropertyState.restore();
                    beforePropertyState.refresh();
                    return true;
                }

            };
            action.setDependencySet(getPropertyStoreAdjuster().getDependencySet());

            UndoManager.getInstance().addAction(action);

            buildFunctions();

            dropDown.getLabel().setText(newFunction.getString(FunctionSettingsInterpreter.FUNCTION_NAME));

            loadFrom(newFunction.deepCopy());

        }

    });

    currentKnotContainer = FengGUI.createContainer(saveContainer);
    currentKnotContainer.setVisible(false);
    currentKnotContainer.setLayoutManager(new RowLayout(true));
    FengGUI.createLabel(currentKnotContainer, "Vertex Position: ").setExpandable(false);
    FengGUI.createLabel(currentKnotContainer, "X").setExpandable(false);
    currentX = FengGUI.createTextEditor(currentKnotContainer);
    FengGUI.createLabel(currentKnotContainer, "Y").setExpandable(false);
    currentY = FengGUI.createTextEditor(currentKnotContainer);

    currentY.addTextChangedListener(new ITextChangedListener() {

        public void textChanged(TextChangedEvent textChangedEvent) {
            try {
                float pos;
                float scaleY = (float) pane.getTransformFunction().getScaleY();
                if (scaleY != 0f && !Float.isInfinite(scaleY) && !Float.isNaN(scaleY)) {
                    pos = (Float.valueOf((currentY.getText()))
                            - (float) pane.getTransformFunction().getTranslateY())
                            * (float) pane.getTransformFunction().getScaleY();

                } else {
                    return;
                    //pos = (float) pane.getTransformFunction().getTranslateY();
                }

                Knot cur = pane.getCurrent();
                if (cur != null) {
                    if (cur.getTranslation().y != pos) {
                        cur.getTranslation().y = pos;
                        pane.updateKnots();
                    }
                }
            } catch (NumberFormatException e) {

            }
        }

    });

    currentX.addTextChangedListener(new ITextChangedListener() {

        public void textChanged(TextChangedEvent textChangedEvent) {
            try {
                float pos;
                float scaleX = (float) pane.getTransformFunction().getScaleX();
                if (scaleX != 0f && !Float.isInfinite(scaleX) && !Float.isNaN(scaleX)) {
                    pos = (Float.valueOf((currentX.getText()))
                            - (float) pane.getTransformFunction().getTranslateX())
                            * (float) pane.getTransformFunction().getScaleX();

                } else {
                    return;

                }
                Knot cur = pane.getCurrent();
                if (cur != null) {
                    if (cur.getTranslation().x != pos) {
                        cur.getTranslation().x = pos;
                        pane.updateKnots();
                    }
                }
            } catch (NumberFormatException e) {

            }
        }

    });

    pane.registerCurrentKnotListener(new CurrentKnotListener() {

        public void currentKnotChanged(Knot current) {
            if (current == null) {
                currentKnotContainer.setVisible(false);
            } else {
                currentKnotContainer.setVisible(true);
                float scaleX = (float) pane.getTransformFunction().getScaleX();
                if (scaleX != 0f && !Float.isInfinite(scaleX) && !Float.isNaN(scaleX))
                    scaleX = 1f / scaleX;
                else
                    scaleX = 0f;

                float scaleY = (float) pane.getTransformFunction().getScaleY();
                if (scaleY != 0f && !Float.isInfinite(scaleY) && !Float.isNaN(scaleY))
                    scaleY = 1f / scaleY;
                else
                    scaleY = 0f;

                currentX.setText(String.valueOf(
                        current.getTranslation().x * scaleX + pane.getTransformFunction().getTranslateX()));
                currentY.setText(String.valueOf(
                        current.getTranslation().y * scaleY + pane.getTransformFunction().getTranslateY()));

                saveContainer.layout();
            }

        }
    });
    functionContainer.pack();
    tabFrame.pack();
}

From source file:de.undercouch.bson4jackson.BsonGenerator.java

@Override
public void writeNumber(BigDecimal dec) throws IOException, JsonGenerationException {
    if (isEnabled(Feature.WRITE_BIGDECIMALS_AS_STRINGS)) {
        writeString(dec.toString());//from   ww w .  j  a va2  s . c  o  m
        return;
    }

    float f = dec.floatValue();
    if (!Float.isInfinite(f)) {
        writeNumber(f);
    } else {
        double d = dec.doubleValue();
        if (!Double.isInfinite(d)) {
            writeNumber(d);
        } else {
            writeString(dec.toString());
        }
    }
}

From source file:org.fhcrc.cpl.viewer.commandline.modules.SpreadsheetMergeCLM.java

/**
 * do the actual work//  ww  w  .j a va2 s. co  m
 */
public void execute() throws CommandLineModuleExecutionException {
    PrintWriter outPW = null;
    try {
        if (outFile != null)
            outPW = new PrintWriter(outFile);

        List<String> combinedColumns = new ArrayList<String>();
        combinedColumns.add(mergeColumnName);

        StringBuffer headerLine = new StringBuffer(mergeColumnName);
        TabLoader[] tabLoaders = new TabLoader[inFiles.length];
        List<TabLoader.ColumnDescriptor>[] columnsAllFiles = new List[inFiles.length];

        for (int i = 0; i < inFiles.length; i++) {
            File inFile = inFiles[i];
            System.err.println("Loading file " + inFile.getName());
            //forcing reading the first file line as a header line, since we're dependent on column names
            TabLoader loader = new TabLoader(new FileReader(inFile), true);
            List<TabLoader.ColumnDescriptor> columnsThisFile = new ArrayList<TabLoader.ColumnDescriptor>();
            if (i == 1 && file2ColumnName != null) {

                for (TabLoader.ColumnDescriptor column : loader.getColumns()) {
                    if (column.name.equals(file2ColumnName))
                        columnsThisFile.add(column);
                }
                headerLine.append("\t" + file2ColumnName);
            } else if (i == 1 && newColumnName != null) {
                headerLine.append("\t" + newColumnName);
                columnsThisFile.add(new TabLoader.ColumnDescriptor(newColumnName, String.class));
            } else {
                for (TabLoader.ColumnDescriptor column : loader.getColumns()) {
                    columnsThisFile.add(column);
                    if (!mergeColumnName.equals(column.name))
                        headerLine.append("\t" + column.name);
                }
            }
            List<String> columnNamesThisFile = new ArrayList<String>();
            for (TabLoader.ColumnDescriptor column : columnsThisFile)
                columnNamesThisFile.add(column.name);
            if (!columnNamesThisFile.contains(mergeColumnName))
                throw new CommandLineModuleExecutionException(
                        "File " + inFile.getAbsolutePath() + " does not contain column " + mergeColumnName);
            columnsAllFiles[i] = columnsThisFile;
            tabLoaders[i] = loader;
        }

        if (outFile != null) {
            outPW.println(headerLine.toString());
            outPW.flush();
        }

        Map<String, Map>[] rowMaps = new Map[inFiles.length];
        for (int i = 0; i < inFiles.length; i++) {
            rowMaps[i] = mapRowsByMergeCol((Map[]) new TabLoader(inFiles[i]).load());
            //Replace map with  presence annotations if that's what we're doing
            if (i == 1 && newColumnName != null) {
                Map<String, Map> annotRowMap = new HashMap<String, Map>();
                for (String key : rowMaps[i].keySet()) {
                    Map<String, String> keyMap = new HashMap<String, String>();
                    keyMap.put(newColumnName, presenceAnnotation);
                    annotRowMap.put(key, keyMap);
                }
                rowMaps[i] = annotRowMap;
            }
            ApplicationContext.infoMessage("Loaded " + rowMaps[i].size() + " rows from file " + (i + 1));
        }

        Set<String> keysInAllFiles = new HashSet<String>();

        for (String key : rowMaps[0].keySet()) {
            boolean notFoundSomewhere = false;
            for (int i = 1; i < rowMaps.length; i++) {
                if (!rowMaps[i].containsKey(key)) {
                    notFoundSomewhere = true;
                    break;
                }
            }
            if (!notFoundSomewhere)
                keysInAllFiles.add(key);
        }
        ApplicationContext.infoMessage("Rows in common: " + keysInAllFiles.size());

        Set<String> keysToWrite = new HashSet<String>();

        if (keepAllValuesAllFiles) {
            for (Map<String, Map> rowMap : rowMaps)
                keysToWrite.addAll(rowMap.keySet());
        } else if (keepAllFile1Values)
            keysToWrite = rowMaps[0].keySet();
        else {
            keysToWrite = keysInAllFiles;
        }

        for (String key : keysToWrite) {
            //if (key.equals("IPI00115660")) System.err.println("***!");
            Map[] mapsAllFiles = new Map[rowMaps.length];
            for (int j = 0; j < rowMaps.length; j++) {
                mapsAllFiles[j] = rowMaps[j].get(key);
                //if (key.equals("IPI00115660")) System.err.println("\t" + j + ", " + mapsAllFiles[j].get("geommean_defghi"));                    
                //if we don't find it, and we're supposed to split up keys by ";", do so
                if (mapsAllFiles[j] == null && j > 0 && multipleMergeColumnValuesFirstFile
                        && key.contains(";")) {
                    for (String partKey : key.split(";")) {
                        if (rowMaps[j].containsKey(partKey)) {
                            mapsAllFiles[j] = rowMaps[j].get(partKey);
                            ApplicationContext
                                    .infoMessage("Split up multi-key " + key + ", found match for " + partKey);
                            break;
                        }
                    }
                }
            }

            String line = createFileLine(key, columnsAllFiles, mapsAllFiles);
            if (outFile != null) {
                outPW.println(line);
                outPW.flush();
            }
        }

        if (outUnique2File != null) {
            PrintWriter unique2OutWriter = new PrintWriter(outUnique2File);
            StringBuffer headerLineBuf = new StringBuffer(mergeColumnName);
            for (TabLoader.ColumnDescriptor column : columnsAllFiles[1]) {
                if (!mergeColumnName.equals(column.name))
                    headerLineBuf.append("\t" + column.name);
            }
            unique2OutWriter.println(headerLineBuf);
            List<Float> plotColumnUnique2Values = new ArrayList<Float>();
            for (String key : rowMaps[1].keySet()) {
                if (keysInAllFiles.contains(key))
                    continue;
                List<TabLoader.ColumnDescriptor>[] colArray = new List[] { columnsAllFiles[1] };
                Map[] colMap = new Map[] { rowMaps[1].get(key) };

                String line = createFileLine(key, colArray, colMap);
                if (outUnique2File != null) {
                    unique2OutWriter.println(line);
                    unique2OutWriter.flush();
                }

                if (plotColumnName != null && colMap[0].get(plotColumnName) != null) {
                    try {
                        plotColumnUnique2Values.add(columnValueAsFloat(colMap[0].get(plotColumnNameFile2)));
                    } catch (ClassCastException e) {
                    }
                }

            }
            if (plotColumnName != null & !plotColumnUnique2Values.isEmpty()) {
                PanelWithHistogram pwh = new PanelWithHistogram(plotColumnUnique2Values, "Values unique to 2");
                pwh.displayInTab();
            }
            unique2OutWriter.close();
            ApplicationContext
                    .infoMessage("Wrote lines unique to file 2 in " + outUnique2File.getAbsolutePath());
        }

        //first two files only
        if (plotColumnName != null) {

            List<Float> values1 = new ArrayList<Float>();
            List<Float> values2 = new ArrayList<Float>();
            List<String> commonKeys = new ArrayList<String>();

            List<Float> trackValues1 = new ArrayList<Float>();
            List<Float> trackValues2 = new ArrayList<Float>();

            Map<String, Map> rowMaps1 = rowMaps[0];
            Map<String, Map> rowMaps2 = rowMaps[1];

            for (String key : rowMaps2.keySet()) {
                if (!rowMaps1.containsKey(key)) {
                    Object o2 = rowMaps2.get(key).get(plotColumnNameFile2);
                    if (valuesToTrack != null && valuesToTrack.contains(key)) {
                        System.err.println(key + "\tNA\t" + o2);
                    }
                }
            }
            for (String key : rowMaps1.keySet()) {
                //System.err.println("Key: " + key);
                Object o1 = rowMaps1.get(key).get(plotColumnName);

                if (rowMaps2.containsKey(key)) {
                    //System.err.println("\t" + o1 + rowMaps2.get(key).get(plotColumnName));
                    Object o2 = rowMaps2.get(key).get(plotColumnNameFile2);
                    if (o1 == null || o2 == null)
                        continue;
                    //if (key.equals("IPI00115660")) System.err.println("@@@" + o1 + ", " + o2);
                    try {
                        float value1 = columnValueAsFloat(o1);
                        float value2 = columnValueAsFloat(o2);
                        // System.err.println("Unplottable! " + value1 + ", " + value2);

                        float displayValue1 = value1;
                        float displayValue2 = value2;
                        if (plotLog) {
                            if (displayValue1 == 0)
                                displayValue1 += 0.000001;
                            if (displayValue2 == 0)
                                displayValue2 += 0.000001;
                            displayValue1 = (float) Math.log(displayValue1);
                            displayValue2 = (float) Math.log(displayValue2);
                        }
                        if (!Float.isInfinite(displayValue1) && !Float.isInfinite(displayValue2)
                                && !Float.isNaN(displayValue1) && !Float.isNaN(displayValue2)) {
                            //System.err.println("***" + displayValue1 + ", " + displayValue2);                                
                            values1.add(displayValue1);
                            values2.add(displayValue2);
                            commonKeys.add(key);

                            if (valuesToTrack != null && valuesToTrack.contains(key)) {
                                //         System.err.println(key + "\t" + displayValue1 + "\t" + displayValue2);

                                trackValues1.add(displayValue1);
                                trackValues2.add(displayValue2);
                            }
                        }
                    } catch (ClassCastException e) {
                        ApplicationContext.infoMessage(
                                "Crap!  Can't process value " + rowMaps1.get(key).get(plotColumnName) + " or "
                                        + rowMaps2.get(key).get(plotColumnName));
                    }

                } else {
                    if (valuesToTrack != null && valuesToTrack.contains(key)) {
                        //         System.err.println(key + "\t" + o1 + "\tNA");
                    }
                }
            }
            ApplicationContext.infoMessage("Rows in common and plottable: " + values1.size());
            ApplicationContext.infoMessage(
                    "Correlation coefficient: " + BasicStatistics.correlationCoefficient(values1, values2));
            PanelWithScatterPlot pwsp = new PanelWithScatterPlot(values1, values2, plotColumnName);
            pwsp.setAxisLabels("File 1", "File 2");
            pwsp.displayInTab();

            List<Float> differences = new ArrayList<Float>();
            for (int i = 0; i < values1.size(); i++)
                differences.add(values2.get(i) - values1.get(i));
            new PanelWithHistogram(differences, "Differences").displayInTab();

            if (valuesToTrack != null && trackValues1.size() > 0) {
                PanelWithScatterPlot pwsp2 = new PanelWithScatterPlot(trackValues1, trackValues2,
                        plotColumnName + "_track");
                pwsp2.setAxisLabels("File 1", "File 2");
                pwsp2.displayInTab();
            }

            if (compareOutFile != null) {
                PrintWriter compareOutWriter = new PrintWriter(compareOutFile);
                compareOutWriter
                        .println(mergeColumnName + "\t" + plotColumnName + "_1\t" + plotColumnName + "_2");
                for (int i = 0; i < values1.size(); i++) {
                    compareOutWriter.println(commonKeys.get(i) + "\t" + values1.get(i) + "\t" + values2.get(i));
                    compareOutWriter.flush();
                }
                compareOutWriter.close();
            }
        }

    } catch (Exception e) {
        throw new CommandLineModuleExecutionException(e);
    } finally {
        if (outPW != null)
            outPW.close();
    }
}

From source file:net.pms.util.Rational.java

/**
 * Returns a {@link Rational} whose value is {@code (this * value)}.
 *
 * @param value the value to be multiplied by this {@link Rational}.
 * @return The multiplication result.//  ww  w . j  ava  2s. com
 */
@Nonnull
public Rational multiply(float value) {
    if (isNaN() || Float.isNaN(value)) {
        return NaN;
    }
    if (isInfinite() || Float.isInfinite(value)) {
        if (signum() == 0 || value == 0f) {
            return NaN; // Infinity by zero
        }
        if (value > 0) {
            return signum() > 0 ? POSITIVE_INFINITY : NEGATIVE_INFINITY;
        }
        return signum() < 0 ? POSITIVE_INFINITY : NEGATIVE_INFINITY;
    }
    if (value == 0f) {
        return ZERO;
    }

    return multiply(valueOf(value));
}

From source file:uk.ac.diamond.scisoft.analysis.dataset.FloatDataset.java

/**
 * @return true if dataset contains any Infs
 *//*from   w  ww.  jav  a2s .c  o m*/
@Override
public boolean containsInfs() {
    IndexIterator iter = getIterator(); // REAL_ONLY
    while (iter.hasNext()) { // REAL_ONLY
        if (Float.isInfinite(data[iter.index])) // CLASS_TYPE // REAL_ONLY
            return true; // REAL_ONLY
    } // REAL_ONLY
    return false;
}

From source file:org.fhcrc.cpl.viewer.ms2.commandline.PostProcessPepXMLCLM.java

/**
 * TODO: fold this in with loadLightHeavyPeptides
 *
 * This is some really weird stuff, right here.  This method handles calculation of median log ratios, regardless
 * of whether you're doing it separately by file or all together, by number of cysteines or not.
 * It creates a map data structure that gets used down below, with a key for each file.  If we're doing global
 * centering, the value gets repeated for each key.  This is a bit silly, but it makes things simpler below.
 *
 * @return// ww  w  .  jav  a  2s.  c o m
 * @throws CommandLineModuleExecutionException
 */
protected void calcLogMedianRatiosAllFiles() throws CommandLineModuleExecutionException {
    ApplicationContext
            .infoMessage("Calculating median log ratio(s) for all files, " + "this may take a while...");

    if (medianCenterByNumCysteines) {
        fileNumCysteinesMedianLogRatioMap = new HashMap<File, Map<Integer, Float>>();
        Map<Integer, List<Float>> numCysLogRatiosMapAllFiles = new HashMap<Integer, List<Float>>();
        for (File featureFile : pepXmlFiles) {
            Map<Integer, List<Float>> numCysLogRatiosMapThisFile = new HashMap<Integer, List<Float>>();
            ApplicationContext.infoMessage("\tProcessing file " + featureFile.getAbsolutePath() + "...");
            try {
                Iterator<FeatureSet> featureSetIterator = new PepXMLFeatureFileHandler.PepXMLFeatureSetIterator(
                        featureFile);
                while (featureSetIterator.hasNext()) {
                    FeatureSet featureSet = featureSetIterator.next();
                    filterOnQualityScores(featureSet);

                    for (Feature feature : featureSet.getFeatures()) {
                        if (IsotopicLabelExtraInfoDef.hasRatio(feature)
                                && MS2ExtraInfoDef.getPeptideProphet(feature) >= minPeptideProphetForMedian) {
                            float ratio = (float) IsotopicLabelExtraInfoDef.getRatio(feature);
                            if (Float.isInfinite(ratio) || (ratio == 0) || Float.isNaN(ratio))
                                continue;

                            //don't consider to-be-stripped proteins in median ratio calculation
                            List<String> proteins = MS2ExtraInfoDef.getProteinList(feature);
                            boolean hasBadProtein = false;
                            if (proteins != null) {
                                for (String protein : proteins) {
                                    if ((proteinsToStripQuant != null && proteinsToStripQuant.contains(protein))
                                            || (proteinsToStrip != null && proteinsToStrip.contains(protein))) {
                                        hasBadProtein = true;
                                        break;
                                    }
                                }
                            }
                            if (hasBadProtein)
                                continue;

                            String peptide = MS2ExtraInfoDef.getFirstPeptide(feature);

                            if (peptide != null) {
                                if (peptidesToStrip != null && peptidesToStrip.contains(peptide))
                                    continue;
                                int numCysteines = 0;
                                for (int i = 0; i < peptide.length(); i++) {
                                    if (peptide.charAt(i) == 'C')
                                        numCysteines++;
                                }
                                if (numCysteines > 0) {
                                    List<Float> logRatiosList = numCysLogRatiosMapThisFile.get(numCysteines);
                                    if (logRatiosList == null) {
                                        logRatiosList = new ArrayList<Float>();
                                        numCysLogRatiosMapThisFile.put(numCysteines, logRatiosList);
                                    }
                                    logRatiosList.add((float) Math.log(ratio));
                                }
                            }
                        }
                    }
                }

                if (medianCenterAllRunsTogether) {
                    for (int numCys : numCysLogRatiosMapThisFile.keySet()) {
                        List<Float> logRatiosThisNumCys = numCysLogRatiosMapAllFiles.get(numCys);
                        if (logRatiosThisNumCys == null) {
                            logRatiosThisNumCys = new ArrayList<Float>();
                            numCysLogRatiosMapAllFiles.put(numCys, logRatiosThisNumCys);
                        }
                        logRatiosThisNumCys.addAll(numCysLogRatiosMapThisFile.get(numCys));
                    }
                } else {
                    HashMap<Integer, Float> numCysteinesMedianThisFile = new HashMap<Integer, Float>();
                    for (int numCys : numCysLogRatiosMapThisFile.keySet()) {
                        numCysteinesMedianThisFile.put(numCys,
                                (float) BasicStatistics.median(numCysLogRatiosMapThisFile.get(numCys)));
                    }
                    fileNumCysteinesMedianLogRatioMap.put(featureFile, numCysteinesMedianThisFile);
                }

            } catch (IOException e) {
                throw new CommandLineModuleExecutionException("Failed to load feature file " + featureFile);
            }
        }

        if (medianCenterAllRunsTogether) {
            Map<Integer, Float> numCysteinesMedianMap = new HashMap<Integer, Float>();
            for (int numCys = 0; numCys < 10; numCys++) {
                if (!numCysLogRatiosMapAllFiles.containsKey(numCys))
                    continue;
                numCysteinesMedianMap.put(numCys,
                        (float) BasicStatistics.median(numCysLogRatiosMapAllFiles.get(numCys)));
                if (showCharts) {
                    new PanelWithHistogram(numCysLogRatiosMapAllFiles.get(numCys), "LogRatiosCys" + numCys, 200)
                            .displayInTab();
                }
            }
            for (File file : pepXmlFiles) {
                fileNumCysteinesMedianLogRatioMap.put(file, numCysteinesMedianMap);
            }
            ApplicationContext.infoMessage("Median log ratios by num Cysteines:");
            for (int i = 0; i < 20; i++) {
                if (numCysteinesMedianMap.containsKey(i)) {
                    ApplicationContext.infoMessage(i + ": " + numCysteinesMedianMap.get(i) + " ("
                            + numCysLogRatiosMapAllFiles.get(i).size() + " events)");
                }
            }
        } else
            ApplicationContext
                    .infoMessage("Separate median log ratio (by #Cysteines) per file, not displaying.");
    } //end if (medianCenterByNumCysteines)
    else {
        List<Float> logRatiosForMedianCalc = new ArrayList<Float>();
        fileMedianLogRatioMap = new HashMap<File, Float>();
        int fileIndex = 1;
        for (File featureFile : pepXmlFiles) {
            List<Float> logRatiosForMedianCalcThisFile = new ArrayList<Float>();

            ApplicationContext.infoMessage("\tProcessing file " + featureFile.getAbsolutePath() + "...");
            try {
                Iterator<FeatureSet> featureSetIterator = new PepXMLFeatureFileHandler.PepXMLFeatureSetIterator(
                        featureFile);

                while (featureSetIterator.hasNext()) {
                    FeatureSet featureSet = featureSetIterator.next();
                    filterOnQualityScores(featureSet);
                    for (Feature feature : featureSet.getFeatures()) {
                        if (IsotopicLabelExtraInfoDef.hasRatio(feature)
                                && MS2ExtraInfoDef.getPeptideProphet(feature) >= minPeptideProphetForMedian) {
                            float ratio = (float) IsotopicLabelExtraInfoDef.getRatio(feature);

                            if (!Float.isInfinite(ratio) && !Float.isNaN(ratio) && ratio != 0) {
                                logRatiosForMedianCalcThisFile.add((float) Math.log(ratio));
                            }
                        }
                    }
                }
            } catch (IOException e) {
                throw new CommandLineModuleExecutionException("Failed to load feature file " + featureFile);
            }
            if (!medianCenterAllRunsTogether) {
                if (logRatiosForMedianCalcThisFile.size() < minRatiosForMedianCenter)
                    throw new CommandLineModuleExecutionException(
                            "Not enough ratios to calculate median for file " + featureFile.getAbsolutePath()
                                    + " (only " + logRatiosForMedianCalcThisFile.size() + " ratios, needed "
                                    + minRatiosForMedianCenter + ")");
                else {
                    float medianLogRatioThisFile = (float) BasicStatistics
                            .median(logRatiosForMedianCalcThisFile);
                    ApplicationContext.infoMessage("Median log ratio for file " + featureFile.getName() + ": "
                            + medianLogRatioThisFile);
                    fileMedianLogRatioMap.put(featureFile, medianLogRatioThisFile);
                    if (showCharts) {
                        PanelWithHistogram pwh = new PanelWithHistogram(logRatiosForMedianCalcThisFile,
                                "RAW Log Ratios " + fileIndex++, 200);
                        pwh.displayInTab();
                    }
                }
            } else
                logRatiosForMedianCalc.addAll(logRatiosForMedianCalcThisFile);
        }

        if (medianCenterAllRunsTogether) {
            if (logRatiosForMedianCalc.size() < minRatiosForMedianCenter)
                throw new CommandLineModuleExecutionException("Not enough ratios to calculate median (only "
                        + logRatiosForMedianCalc.size() + " ratios, needed " + minRatiosForMedianCenter + ")");
            //assign the same median to each file.  This keeps code same down below
            float medianLogRatioAcrossAll = (float) BasicStatistics.median(logRatiosForMedianCalc);
            ApplicationContext.infoMessage("Median log ratio across all runs: " + medianLogRatioAcrossAll);
            for (File featureFile : pepXmlFiles)
                fileMedianLogRatioMap.put(featureFile, medianLogRatioAcrossAll);
            if (showCharts) {
                PanelWithHistogram pwh = new PanelWithHistogram(logRatiosForMedianCalc, "RAW Log Ratios", 200);
                pwh.displayInTab();
            }
        }
    } //end not-by-cysteines behavior
    ApplicationContext.infoMessage("Done calculating median log ratio across all files.");
}

From source file:org.esa.s2tbx.dataio.s2.ortho.Sentinel2OrthoProductReader.java

private boolean isValidAngle(float value) {
    return !Float.isNaN(value) && !Float.isInfinite(value);
}

From source file:com.xwtec.xwserver.util.json.util.JSONUtils.java

/**
 * Finds out if n represents a Float./*from  ww w . jav a  2 s  .  c  o m*/
 *
 * @return true if n is instanceOf Float or the literal value can be
 *         evaluated as a Float.
 */
private static boolean isFloat(Number n) {
    if (n instanceof Float) {
        return true;
    }
    try {
        float f = Float.parseFloat(String.valueOf(n));
        return !Float.isInfinite(f);
    } catch (NumberFormatException e) {
        return false;
    }
}

From source file:com.facebook.presto.operator.scalar.MathFunctions.java

@Description("round to given number of decimal places")
@ScalarFunction("round")
@SqlType(StandardTypes.REAL)/*from   w  ww . ja v a2 s  .c  o m*/
public static long roundFloat(@SqlType(StandardTypes.REAL) long num,
        @SqlType(StandardTypes.INTEGER) long decimals) {
    float numInFloat = intBitsToFloat((int) num);
    if (Float.isNaN(numInFloat) || Float.isInfinite(numInFloat)) {
        return num;
    }

    double factor = Math.pow(10, decimals);
    if (numInFloat < 0) {
        return floatToRawIntBits((float) -(Math.round(-numInFloat * factor) / factor));
    }

    return floatToRawIntBits((float) (Math.round(numInFloat * factor) / factor));
}