Example usage for java.lang Math rint

List of usage examples for java.lang Math rint

Introduction

In this page you can find the example usage for java.lang Math rint.

Prototype

public static double rint(double a) 

Source Link

Document

Returns the double value that is closest in value to the argument and is equal to a mathematical integer.

Usage

From source file:org.audiveris.omr.sheet.grid.StaffProjector.java

/**
 * Compute thresholds that closely depend on actual line thickness in this staff.
 *//*from  w  ww .j a v a2  s .co m*/
private void computeLineThresholds() {
    final double linesCumul = computeCoreLinesThickness();
    final double lineThickness = linesCumul / staff.getLines().size();

    params.linesThreshold = (int) Math.rint(linesCumul);
    params.blankThreshold = (int) Math.rint(constants.blankThreshold.getValue() * lineThickness);
    params.chunkThreshold = (4 * scale.getMaxFore())
            + InterlineScale.toPixels(staff.getSpecificInterline(), constants.chunkThreshold);
    logger.debug("Staff#{} linesThreshold:{} chunkThreshold:{}", staff.getId(), params.linesThreshold,
            params.chunkThreshold);
}

From source file:com.bytelightning.opensource.pokerface.PokerFace.java

/**
 * Utility method that allows us to be very flexible in how many reactor processors are allocated to a reactor.
 * @param num   If not a finite number, returns 1.
 *             If <= 0, returns the actual number of Runtime.getRuntime().availableProcessors().
 *             If >= 1, returns the minimum of <code>num</code> or (Runtime.getRuntime().availableProcessors(). * 2)
 *             If > 0 && < 1, returns (num * Runtime.getRuntime().availableProcessors()).
 * @return   The translated number of IOProcessors for a reactor.
 */// ww w . j  a v  a2s . c  om
private static int ComputeReactorProcessors(double num) {
    if (!Double.isFinite(num))
        num = 1d;
    if (num <= 0)
        return Runtime.getRuntime().availableProcessors();
    if (num >= (1d - Double.MIN_VALUE))
        return Math.min((int) Math.rint(num), (Runtime.getRuntime().availableProcessors() * 2));
    return Math.max(1, (int) Math.rint(Runtime.getRuntime().availableProcessors() * num));
}

From source file:de.tor.tribes.types.FarmInformation.java

/**
 * Update this farm's correction factor by calculating the expected haul
 * (estimated storage status) and the actual haul (sum of haul and remaining
 * resources). This call will do nothing if no spy information is available or
 * if no haul information is available. The correction factor delta is limited
 * to +/- 10 percent to reduce the influence of A and B runs and for farms which
 * are relatively new.//from   w ww  . j  ava  2s. c  o m
 */
private void updateCorrectionFactor(FightReport pReport) {
    if (pReport.getHaul() != null && pReport.getSpyedResources() != null) {
        logger.debug("Updating correction factor");
        int haulSum = pReport.getHaul()[0] + pReport.getHaul()[1] + pReport.getHaul()[2];
        int storageSum = pReport.getSpyedResources()[0] + pReport.getSpyedResources()[1]
                + pReport.getSpyedResources()[2];
        int expected = getResourcesInStorage(pReport.getTimestamp());
        // resources were hauled
        logger.debug(" - Resources in farm: " + (haulSum + storageSum));

        float correctionBefore = getCorrectionFactor();
        logger.debug(" - Correction factor before: " + correctionBefore);
        // add resources expected at report's timestamp to expected haul
        expectedHaul += expected;
        // actual haul contains only resources we've obtained
        actualHaul += haulSum + storageSum;

        float correctionAfter = getCorrectionFactor();
        logger.debug(" - Correction factor after: " + correctionAfter);
        logger.debug(" - Correction factor delta: " + Math.abs(correctionAfter - correctionBefore));

        if (Math.abs(correctionAfter - correctionBefore) > .1) {
            logger.debug(" - Correction factor delta larger than 0.1");
            // limit correction influence by one report to +/- 10 percent
            actualHaul = (int) Math.rint(
                    (correctionBefore + ((correctionAfter < correctionBefore) ? -.1 : .1)) * expectedHaul);
            logger.debug(" - New correction factor: " + getCorrectionFactor());
        } else {
            logger.debug(" - No correction necessary. New correction factor: " + getCorrectionFactor());
        }
    } else {
        logger.debug("Skipping correction factor update due to missing spy/farm information");
    }
}

From source file:projects.wdlf47tuc.ProcessAllSwathcal.java

/**
 * Computes the luminosity function for the current boxed region and plots it in a JFrame.
 * Also prints out the coordinates of the selection box vertices and the luminosity function
 * quantities.//from w ww  .  ja  v a 2  s. c om
 * 
 * @param sources
 *    The {@link Source}s to compute the luminosity function for.
 */
private void computeAndPlotLuminosityFunction(List<Source> sources) {

    // Print out coordinates of selection box corners
    System.out.println("# Coordinates of selection box corners:");
    System.out.println("# (" + col1Filter + "-" + col2Filter + ")\t" + magFilter);
    for (double[] point : points) {
        System.out.println("# " + point[0] + "\t" + point[1]);
    }
    System.out.println("# Luminosity function:");
    System.out.println("# Mag.\tN\tsigN");

    double magBinWidth = 0.5;

    // Get the range of the data
    double mMin = Double.MAX_VALUE;
    double mMax = -Double.MAX_VALUE;
    for (Source source : sources) {
        double mag = source.getMag(magFilter) - mu;
        mMin = Math.min(mMin, mag);
        mMax = Math.max(mMax, mag);
    }

    // Quantize this to a whole number
    mMin = Math.floor(mMin);
    mMax = Math.ceil(mMax);

    int nBins = (int) Math.rint((mMax - mMin) / magBinWidth);

    // Array to accumulate all objects in each bin
    int[] n = new int[nBins];

    for (Source source : sources) {
        double mag = source.getMag(magFilter) - mu;
        // Bin number
        int bin = (int) Math.floor((mag - mMin) / magBinWidth);
        n[bin]++;
    }

    YIntervalSeries luminosityFunction = new YIntervalSeries("Luminosity Function");

    for (int i = 0; i < nBins; i++) {
        // Bin centre
        double x = mMin + i * magBinWidth + 0.5 * magBinWidth;
        double y = n[i];
        double yErr = n[i] > 0 ? Math.sqrt(y) : 0;
        luminosityFunction.add(x, y, y - yErr, y + yErr);
        System.out.println(x + "\t" + y + "\t" + yErr);
    }

    final YIntervalSeriesCollection data = new YIntervalSeriesCollection();
    data.addSeries(luminosityFunction);

    XYErrorRenderer renderer = new XYErrorRenderer();
    renderer.setSeriesLinesVisible(0, true);
    renderer.setSeriesShapesVisible(0, true);
    renderer.setSeriesShape(0, new Ellipse2D.Float(-1f, -1f, 2, 2));
    renderer.setSeriesPaint(0, ChartColor.BLACK);

    NumberAxis xAxis = new NumberAxis("Absolute Magnitude (" + magFilter.toString() + ")");
    xAxis.setAutoRange(true);
    xAxis.setAutoRangeIncludesZero(false);

    NumberAxis yAxis = new NumberAxis("N");
    yAxis.setAutoRange(true);
    yAxis.setAutoRangeIncludesZero(true);

    // Configure plot
    XYPlot xyplot = new XYPlot(data, xAxis, yAxis, renderer);
    xyplot.setBackgroundPaint(Color.lightGray);
    xyplot.setDomainGridlinePaint(Color.white);
    xyplot.setDomainGridlinesVisible(true);
    xyplot.setRangeGridlinePaint(Color.white);

    // Configure chart
    JFreeChart chart = new JFreeChart("Luminosity Function", xyplot);
    chart.setBackgroundPaint(Color.white);
    chart.setTitle("47 Tuc luminosity function");
    chart.removeLegend();

    final ChartPanel lfChartPanel = new ChartPanel(chart);

    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            JFrame tester = new JFrame();
            tester.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            tester.setLayout(new BorderLayout());
            tester.add(lfChartPanel, BorderLayout.CENTER);
            tester.pack();
            tester.setVisible(true);
        }
    });

}

From source file:at.ofai.music.util.WormFileParseException.java

public static EventList readMatchFile(String fileName) throws Exception {
    EventList list = new EventList();
    boolean startNote = timingCorrection;
    int eventFlags, numerator, denominator;
    String element;//from w  ww. j a v  a  2 s . c o m
    BufferedReader inputFile = new BufferedReader(new FileReader(fileName));
    double versionNumber = 1.0;
    double onset, offset, eOffset, beat, duration;
    int velocity, pitch, octave;
    int lineCount = 1;
    Matcher s = new Matcher(inputFile.readLine());
    while (s.hasData()) {
        eventFlags = 0;
        beat = UNKNOWN;
        duration = UNKNOWN;
        // System.out.println("Processing line " + lineCount);
        if (s.matchString("info(")) { // meta-data
            if (s.matchString("timeSignature,")) {
                numerator = s.getInt();
                // ss1 << "beatsPerBar=" << numerator << ends;
                s.skip('/');
                denominator = s.getInt();
                // ss2 << "beatUnits=" << denominator;
            } else if (s.matchString("beatSubdivision,")) {
                // strcpy(buf, "beatSubdivisions=");
                // int i = strlen(buf);
                // f.getline(buf+i, SZ-i, ']');
                // strcat(buf, "]");
                // parameters->add(buf);
                s.skip(']');
            } else if (s.matchString("matchFileVersion,")) {
                versionNumber = s.getDouble();
            } else if (s.matchString("midiClockUnits,")) {
                clockUnits = s.getInt();
            } else if (s.matchString("midiClockRate,")) {
                clockRate = s.getInt();
            }
            s.set("%"); // don't expect the second half of the Prolog term
        } else if (s.matchString("snote(")) {
            s.skip(','); // identifier
            s.skip(']'); // note name
            s.skip(','); // ',' after note name
            s.skip(','); // octave
            s.skip(','); // onset time (in beats, integer part, bar:beat)
            boolean isBt = s.matchString("0");
            s.skip(','); // onset time (in beats, fractional part)
            s.skip(','); // duration (in beats, fraction)
            try {
                beat = s.getDouble();
            } catch (NumberFormatException e) {
                System.err.println("Bad beat number on line " + lineCount);
                beat = UNKNOWN;
            }
            if ((beat == Math.rint(beat)) != isBt)
                System.err.println("Inconsistent beats on line " + lineCount);
            s.skip(','); // onset time (in beats, decimal) 
            try {
                duration = s.getDouble() - beat;
            } catch (NumberFormatException e) {
                System.err.println("Bad duration on line " + lineCount);
                duration = UNKNOWN;
            }
            s.skip(','); // offset time (in beats, decimal)
            s.skip('['); // additional info (e.g. melody/arpeggio/grace)
            do {
                element = s.getString();
                eventFlags |= flags.getFlag(element);
            } while (s.matchString(","));
            s.skip('-');
        } else if (s.matchString("trill(")) {
            eventFlags |= flags.getFlag("trill");
            s.skip('-');
        } else if (s.matchString("ornament(")) {
            eventFlags |= flags.getFlag("ornament");
            s.skip('-');
        } else if (s.matchString("trailing_played_note-") || s.matchString("hammer_bounce-")
                || s.matchString("no_score_note-") || s.matchString("insertion-")) {
            eventFlags |= flags.getFlag("unscored");
        } else if (!s.matchString("%")) { // Prolog comment
            throw new MatchFileParseException("error 4; line " + lineCount);
        }
        // READ 2nd term of Prolog expression
        if (s.matchString("note(")) {
            s.skip('['); // skip identifier
            String note = s.getString();
            switch (Character.toUpperCase(note.charAt(0))) {
            case 'A':
                pitch = 9;
                break;
            case 'B':
                pitch = 11;
                break;
            case 'C':
                pitch = 0;
                break;
            case 'D':
                pitch = 2;
                break;
            case 'E':
                pitch = 4;
                break;
            case 'F':
                pitch = 5;
                break;
            case 'G':
                pitch = 7;
                break;
            default:
                throw new MatchFileParseException("Bad note on line " + lineCount);
            }
            s.skip(',');
            String mod = s.getString();
            for (int i = 0; i < mod.length(); i++) {
                switch (mod.charAt(i)) {
                case '#':
                    pitch++;
                    break;
                case 'b':
                    pitch--;
                    break;
                case 'n':
                    break;
                default:
                    throw new MatchFileParseException("error 5 " + lineCount);
                }
            }
            s.skip(',');
            octave = s.getInt();
            pitch += 12 * octave;
            s.skip(',');
            onset = s.getInt();
            s.skip(',');
            offset = s.getInt();
            if (versionNumber > 1.0) {
                s.skip(',');
                eOffset = s.getInt();
            } else
                eOffset = offset;
            s.skip(',');
            velocity = s.getInt();
            onset /= clockUnits * 1000000.0 / clockRate;
            offset /= clockUnits * 1000000.0 / clockRate;
            eOffset /= clockUnits * 1000000.0 / clockRate;
            if (timingCorrection) {
                if (startNote) {
                    timingDisplacement = onset - timingDisplacement;
                    startNote = false;
                }
                onset -= timingDisplacement;
                offset -= timingDisplacement;
                eOffset -= timingDisplacement;
            }
            int m = flags.getFlag("s");
            if ((((eventFlags & m) != 0) && !noMelody) || (((eventFlags & m) == 0) && !onlyMelody)) {
                Event e = new Event(onset, offset, eOffset, pitch, velocity, beat, duration, eventFlags);
                list.add(e);
            }
        } else if (!s.matchString("no_played_note.") && !s.matchString("trailing_score_note.")
                && !s.matchString("deletion.") && !s.matchString("%"))
            throw new MatchFileParseException("error 6; line " + lineCount);
        s.set(inputFile.readLine());
        lineCount++;
    }
    return list;
}

From source file:de.walware.statet.r.core.rsource.ast.RAst.java

public static Integer toJavaInt(RAstNode node) {
    while (node != null) {
        switch (node.getNodeType()) {
        case NUM_CONST:
            switch (node.getOperator(0)) {
            case NUM_NUM: {
                final Double num = parseNum(node.getText());
                if (num != null && num.doubleValue() == Math.rint(num.doubleValue())) {
                    return num.intValue();
                }/*from   www  .j a v  a  2s  .co m*/
                break;
            }
            case NUM_INT:
                return parseInt(node.getText());
            case TRUE:
                return 1;
            case FALSE:
                return 0;
            default:
                break;
            }
            return null;
        case F_CALL_ARG:
            node = ((FCall.Arg) node).getValueChild();
            continue;
        default:
            return null;
        }
    }
    return null;
}

From source file:org.gumtree.vis.plot1d.LogarithmizableAxis.java

protected List newRefreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) {
    // TODO Auto-generated method stub
    List ticks = new java.util.ArrayList();
    Range range = getRange();// ww  w. ja  v  a  2  s . co m

    //get lower bound value:
    double lowerBoundVal = range.getLowerBound();
    //if small log values and lower bound value too small
    // then set to a small value (don't allow <= 0):
    if (this.smallLogFlag && lowerBoundVal < SMALL_LOG_VALUE) {
        lowerBoundVal = SMALL_LOG_VALUE;
    }

    //get upper bound value
    double upperBoundVal = range.getUpperBound();

    //get log10 version of lower bound and round to integer:
    int iBegCount = (int) Math.rint(switchedLog10(lowerBoundVal));
    //get log10 version of upper bound and round to integer:
    int iEndCount = (int) Math.rint(switchedLog10(upperBoundVal));

    //        if (iBegCount == iEndCount && iBegCount >= 0
    if (iBegCount == iEndCount && Math.pow(10, iBegCount) > lowerBoundVal) {
        //only 1 power of 10 value, it's > 0 and its resulting
        // tick value will be larger than lower bound of data
        --iBegCount; //decrement to generate more ticks
    }

    int numberOfGrids = 0;
    int numberOfTicks = 0;
    NumberTick lastTick = null;

    double currentTickValue;
    String tickLabel;
    boolean zeroTickFlag = false;
    for (int i = iBegCount; i <= iEndCount; i++) {
        //for each power of 10 value; create ten ticks
        for (int j = 0; j < 10; ++j) {
            //for each tick to be displayed
            if (this.smallLogFlag) {
                //small log values in use; create numeric value for tick
                currentTickValue = Math.pow(10, i) + (Math.pow(10, i) * j);
                if (this.expTickLabelsFlag || (i < 0 && currentTickValue > 0.0 && currentTickValue < 1.0)) {
                    //showing "1e#"-style ticks or negative exponent
                    // generating tick value between 0 & 1; show fewer
                    if (j == 0 || (i > -4 && (j < 2 || j == 4)) || currentTickValue >= upperBoundVal) {
                        //first tick of series, or not too small a value and
                        // one of first 3 ticks, or last tick to be displayed
                        // set exact number of fractional digits to be shown
                        // (no effect if showing "1e#"-style ticks):
                        this.numberFormatterObj.setMaximumFractionDigits(-i);
                        //create tick label (force use of fmt obj):
                        tickLabel = makeTickLabel(currentTickValue, true);
                    } else { //no tick label to be shown
                        //                            tickLabel = "";
                        if (numberOfTicks == 0) {
                            tickLabel = makeTickLabel(currentTickValue, true);
                        } else
                            tickLabel = "";
                    }
                } else { //tick value not between 0 & 1
                         //show tick label if it's the first or last in
                         // the set, or if it's 1-5; beyond that show
                         // fewer as the values get larger:
                    tickLabel = (j < 1 || (i < 1 && j < 5) || (j < 4 - i) || currentTickValue >= upperBoundVal
                            || numberOfTicks == 0) ? makeTickLabel(currentTickValue) : "";
                }
            } else { //not small log values in use; allow for values <= 0
                if (zeroTickFlag) { //if did zero tick last iter then
                    --j; //decrement to do 1.0 tick now
                } //calculate power-of-ten value for tick:
                currentTickValue = (i >= 0) ? Math.pow(10, i) + (Math.pow(10, i) * j)
                        : -(Math.pow(10, -i) - (Math.pow(10, -i - 1) * j));
                if (!zeroTickFlag) { // did not do zero tick last iteration
                    if (Math.abs(currentTickValue - 1.0) < 0.0001 && lowerBoundVal <= 0.0
                            && upperBoundVal >= 0.0) {
                        //tick value is 1.0 and 0.0 is within data range
                        currentTickValue = 0.0; //set tick value to zero
                        zeroTickFlag = true; //indicate zero tick
                    }
                } else { //did zero tick last iteration
                    zeroTickFlag = false; //clear flag
                } //create tick label string:
                //show tick label if "1e#"-style and it's one
                // of the first two, if it's the first or last
                // in the set, or if it's 1-5; beyond that
                // show fewer as the values get larger:
                tickLabel = ((this.expTickLabelsFlag && j < 2) || j < 1 || (i < 1 && j < 5) || (j < 4 - i)
                        || currentTickValue >= upperBoundVal || numberOfTicks == 0)
                                ? makeTickLabel(currentTickValue)
                                : "";
            }

            if (currentTickValue > upperBoundVal) {
                if (lastTick != null) {
                    String lastTickText = lastTick.getText();
                    if (lastTickText == null || lastTickText.trim().length() == 0) {
                        ticks.remove(lastTick);
                        ticks.add(new NumberTick(lastTick.getValue(),
                                createTickLabel(lastTick.getValue(), i - 1), lastTick.getTextAnchor(),
                                lastTick.getRotationAnchor(), lastTick.getAngle()));
                    }
                }
                if (numberOfTicks < 4) {
                    return getAllTicksHorizontal(g2, dataArea, edge);
                }
                return ticks; // if past highest data value then exit
                              // method
            }

            if (currentTickValue >= lowerBoundVal - SMALL_LOG_VALUE) {
                //tick value not below lowest data value
                TextAnchor anchor = null;
                TextAnchor rotationAnchor = null;
                double angle = 0.0;
                if (isVerticalTickLabels()) {
                    anchor = TextAnchor.CENTER_RIGHT;
                    rotationAnchor = TextAnchor.CENTER_RIGHT;
                    if (edge == RectangleEdge.TOP) {
                        angle = Math.PI / 2.0;
                    } else {
                        angle = -Math.PI / 2.0;
                    }
                } else {
                    if (edge == RectangleEdge.TOP) {
                        anchor = TextAnchor.BOTTOM_CENTER;
                        rotationAnchor = TextAnchor.BOTTOM_CENTER;
                    } else {
                        anchor = TextAnchor.TOP_CENTER;
                        rotationAnchor = TextAnchor.TOP_CENTER;
                    }
                }

                lastTick = new NumberTick(new Double(currentTickValue), tickLabel, anchor, rotationAnchor,
                        angle);
                ticks.add(lastTick);
                if (tickLabel != null && tickLabel.trim().length() > 0)
                    numberOfTicks++;
                numberOfGrids++;
            }
        }
    }
    if (numberOfTicks < 4) {
        return getAllTicksHorizontal(g2, dataArea, edge);
    }
    return ticks;
}

From source file:org.gumtree.vis.plot1d.KLogarithmicAxis.java

protected List getAllTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) {
    List ticks = new java.util.ArrayList();

    //get lower bound value:
    double lowerBoundVal = getRange().getLowerBound();
    //if small log values and lower bound value too small
    // then set to a small value (don't allow <= 0):
    if (this.smallLogFlag && lowerBoundVal < SMALL_LOG_VALUE) {
        lowerBoundVal = SMALL_LOG_VALUE;
    }//from  w ww.  j a v a  2  s . c o  m
    //get upper bound value
    double upperBoundVal = getRange().getUpperBound();

    //get log10 version of lower bound and round to integer:
    int iBegCount = (int) Math.rint(switchedLog10(lowerBoundVal));
    //get log10 version of upper bound and round to integer:
    int iEndCount = (int) Math.rint(switchedLog10(upperBoundVal));

    if (iBegCount == iEndCount && iBegCount > 0 && Math.pow(10, iBegCount) > lowerBoundVal) {
        //only 1 power of 10 value, it's > 0 and its resulting
        // tick value will be larger than lower bound of data
        --iBegCount; //decrement to generate more ticks
    }

    int numberOfGrids = 0;
    int numberOfTicks = 0;
    NumberTick lastTick = null;
    double tickVal;
    String tickLabel;
    //        tickVal = lowerBoundVal;
    //        
    //        tickLabel = Long.toString((long) Math.rint(tickVal));
    //        ticks.add(new NumberTick(new Double(tickVal), tickLabel,
    //              TextAnchor.CENTER_RIGHT, TextAnchor.CENTER_RIGHT, 0.0));
    boolean zeroTickFlag = false;
    for (int i = iBegCount; i <= iEndCount; i++) {
        //for each tick with a label to be displayed
        int jEndCount = 10;
        if (i == iEndCount) {
            //                jEndCount = 1;
        }

        for (int j = 0; j < jEndCount; j++) {
            //for each tick to be displayed
            if (this.smallLogFlag) {
                //small log values in use
                tickVal = Math.pow(10, i) + (Math.pow(10, i) * j);
                //first tick of group; create label text
                if (this.log10TickLabelsFlag) {
                    //if flag then
                    tickLabel = "10^" + i; //create "log10"-type label
                } else { //not "log10"-type label
                    if (this.expTickLabelsFlag) {
                        //if flag then
                        tickLabel = "1e" + i; //create "1e#"-type label
                    } else { //not "1e#"-type label
                        if (i >= 0) { // if positive exponent then
                                      // make integer
                            NumberFormat format = getNumberFormatOverride();
                            if (format != null) {
                                tickLabel = format.format(tickVal);
                            } else {
                                tickLabel = Long.toString((long) Math.rint(tickVal));
                            }
                        } else {
                            //negative exponent; create fractional value
                            //set exact number of fractional digits to
                            // be shown:
                            this.numberFormatterObj.setMaximumFractionDigits(-i);
                            //create tick label:
                            tickLabel = this.numberFormatterObj.format(tickVal);
                        }
                    }
                }
            } else { //not small log values in use; allow for values <= 0
                if (zeroTickFlag) { //if did zero tick last iter then
                    --j;
                } //decrement to do 1.0 tick now
                tickVal = (i >= 0) ? Math.pow(10, i) + (Math.pow(10, i) * j)
                        : -(Math.pow(10, -i) - (Math.pow(10, -i - 1) * j));
                if (!zeroTickFlag) { // did not do zero tick last
                                     // iteration
                    if (i > iBegCount && i < iEndCount && Math.abs(tickVal - 1.0) < 0.0001) {
                        // not first or last tick on graph and value
                        // is 1.0
                        tickVal = 0.0; //change value to 0.0
                        zeroTickFlag = true; //indicate zero tick
                        tickLabel = "0"; //create label for tick
                    } else {
                        //first or last tick on graph or value is 1.0
                        //create label for tick:
                        tickLabel = createTickLabel(tickVal, i);
                    }
                } else { // not first tick of group
                    tickLabel = createTickLabel(tickVal, i);
                }
            }

            if (tickVal > upperBoundVal) {
                if (lastTick != null) {
                    String lastTickText = lastTick.getText();
                    if (lastTickText == null || lastTickText.trim().length() == 0) {
                        ticks.remove(lastTick);
                        ticks.add(new NumberTick(lastTick.getValue(),
                                createTickLabel(lastTick.getValue(), i - 1), lastTick.getTextAnchor(),
                                lastTick.getRotationAnchor(), lastTick.getAngle()));
                    }
                }
                if (ticks.size() < 2) {
                    double definition = Math.abs(lowerBoundVal - upperBoundVal);
                    int numberOfDigits = 0;
                    if (definition >= 1)
                        numberOfDigits = 0;
                    else {
                        numberOfDigits = (int) Math.ceil((-Math.log10(definition)));
                    }
                    tickVal = lowerBoundVal;
                    if (definition > 1)
                        tickLabel = Long.toString((long) Math.rint(tickVal));
                    else
                        tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
                    ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.CENTER_RIGHT,
                            TextAnchor.CENTER_RIGHT, 0.0));
                    tickVal = upperBoundVal;
                    if (definition > 1)
                        tickLabel = Long.toString((long) Math.rint(tickVal));
                    else
                        tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
                    ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.CENTER_RIGHT,
                            TextAnchor.CENTER_RIGHT, 0.0));
                }
                return ticks; //if past highest data value then exit method
            }

            if (tickVal >= lowerBoundVal - SMALL_LOG_VALUE) {
                //tick value not below lowest data value
                TextAnchor anchor = null;
                TextAnchor rotationAnchor = null;
                double angle = 0.0;
                if (isVerticalTickLabels()) {
                    if (edge == RectangleEdge.LEFT) {
                        anchor = TextAnchor.BOTTOM_CENTER;
                        rotationAnchor = TextAnchor.BOTTOM_CENTER;
                        angle = -Math.PI / 2.0;
                    } else {
                        anchor = TextAnchor.BOTTOM_CENTER;
                        rotationAnchor = TextAnchor.BOTTOM_CENTER;
                        angle = Math.PI / 2.0;
                    }
                } else {
                    if (edge == RectangleEdge.LEFT) {
                        anchor = TextAnchor.CENTER_RIGHT;
                        rotationAnchor = TextAnchor.CENTER_RIGHT;
                    } else {
                        anchor = TextAnchor.CENTER_LEFT;
                        rotationAnchor = TextAnchor.CENTER_LEFT;
                    }
                }
                //create tick object and add to list:
                lastTick = new NumberTick(new Double(tickVal), tickLabel, anchor, rotationAnchor, angle);
                ticks.add(lastTick);
                if (tickLabel != null && tickLabel.trim().length() > 0)
                    numberOfTicks++;
                numberOfGrids++;
            }
        }
    }
    if (ticks.size() < 2) {
        double definition = Math.abs(lowerBoundVal - upperBoundVal);
        int numberOfDigits = 0;
        if (definition >= 1)
            numberOfDigits = 0;
        else {
            numberOfDigits = (int) Math.ceil((-Math.log10(definition)));
        }
        tickVal = lowerBoundVal;
        if (definition > 1)
            tickLabel = Long.toString((long) Math.rint(tickVal));
        else
            tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
        ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.CENTER_RIGHT,
                TextAnchor.CENTER_RIGHT, 0.0));
        tickVal = upperBoundVal;
        if (definition > 1)
            tickLabel = Long.toString((long) Math.rint(tickVal));
        else
            tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
        ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.CENTER_RIGHT,
                TextAnchor.CENTER_RIGHT, 0.0));
    }
    return ticks;
}

From source file:savant.view.tracks.BAMTrackRenderer.java

private void renderSNPMode(Graphics2D g2, GraphPaneAdapter gp, Resolution r) throws RenderingException {

    Genome genome = GenomeController.getInstance().getGenome();
    if (!genome.isSequenceSet()) {
        throw new RenderingException("No reference sequence loaded\nSwitch to standard display mode",
                RenderingException.WARNING_PRIORITY);
    }// ww  w. j a v  a  2 s  . c o  m

    AxisRange axisRange = (AxisRange) instructions.get(DrawingInstruction.AXIS_RANGE);
    ColourScheme cs = (ColourScheme) instructions.get(DrawingInstruction.COLOUR_SCHEME);

    List<Pileup> pileups = new ArrayList<Pileup>();

    // make the pileups
    int length = axisRange.getXMax() - axisRange.getXMin() + 1;
    assert Math.abs(axisRange.getXMin()) <= Integer.MAX_VALUE;
    int startPosition = (int) axisRange.getXMin();
    for (int j = 0; j < length; j++) {
        pileups.add(new Pileup(startPosition + j));
    }

    // Go through the samrecords and edit the pileups
    for (Record record : data) {
        SAMRecord samRecord = ((BAMIntervalRecord) record).getSAMRecord();
        updatePileupsFromSAMRecord(pileups, samRecord, startPosition);
    }

    double maxHeight = 0;
    for (Pileup p : pileups) {
        int current = p.getTotalCoverage(null);
        if (current > maxHeight) {
            maxHeight = current;
        }
    }

    gp.setXRange(axisRange.getXRange());
    gp.setYRange(new Range(0, (int) Math.rint((double) maxHeight / 0.9)));

    double unitHeight = (Math.rint(gp.transformYPos(0) * 0.9)) / maxHeight;
    double unitWidth = gp.getUnitWidth();

    ColourAccumulator accumulator = new ColourAccumulator(cs);
    List<Rectangle2D> insertions = new ArrayList<Rectangle2D>();

    for (Pileup p : pileups) {
        int totalCoverage = p.getTotalCoverage(null);
        if (totalCoverage > 0) {
            double bottom = gp.transformYPos(0);
            double x = gp.transformXPos(p.getPosition());

            VariantType genomeNuc = VariantType.fromChar((char) refSeq[p.getPosition() - startPosition]);
            VariantType snpNuc = genomeNuc;

            // Only record a shape if we have at least some mismatches.
            if (totalCoverage > p.getCoverage(genomeNuc, null)) {
                // Reduce height for insertions, since they don't contribute to the height.
                double h = unitHeight * (totalCoverage - p.getCoverage(VariantType.INSERTION, null));
                recordToShapeMap.put(new PileupRecord(p, false),
                        new Rectangle2D.Double(x, bottom - h, unitWidth, h));
            }

            while ((genome.isSequenceSet() && (snpNuc = p.getLargestVariantType(genomeNuc)) != null)
                    || ((snpNuc = p.getLargestVariantType(VariantType.OTHER)) != null)) {
                double h = unitHeight * p.getCoverage(snpNuc, null);
                Rectangle2D rect = new Rectangle2D.Double(x, bottom - h, unitWidth, h);
                accumulator.addShape(getSubPileColour(snpNuc, genomeNuc), rect);
                if (snpNuc == VariantType.INSERTION) {
                    insertions.add(rect);
                } else {
                    bottom -= h;
                }
                p.clearVariantType(snpNuc);
            }
        }
    }

    accumulator.fill(g2);
    for (Rectangle2D ins : insertions) {
        drawInsertion(g2, ins.getX(), ins.getY(), ins.getWidth(), ins.getHeight());
    }
}

From source file:desmoj.extensions.visualization2d.engine.modelGrafic.StatisticGrafic.java

/**
 * convert double to String. //from   w ww  .  j  ava 2s .  c o  m
 * Used by animation type StatisticGrafic.ANIMATION_LastValue.
 * @param a
 * @return
 */
private String formatieren(double a, boolean isIntValue) {
    String format = "";
    if (isIntValue) {
        a = Math.rint(a);
        if (Math.abs(a) < 10000.0)
            format = "#0";
        else
            format = "0.E0";
    } else {
        if (Math.abs(a) < 0.001)
            format = "0.00E0";
        else if (Math.abs(a) < 10000.0)
            format = "#0.000";
        else
            format = "0.00E0";
    }
    DecimalFormat df = new DecimalFormat(format);
    return df.format(a);
}