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.apache.velocity.tools.generic.MathTool.java

/**
 * Rounds a number to the nearest whole Integer
 *
 * @param num the number to round//w  w w  .j av  a  2 s . c  o  m
 * @return the number rounded to the nearest whole Integer
 *         or <code>null</code> if it's invalid
 * @see java.lang.Math#rint(double)
 */
public Integer round(Object num) {
    Number n = toNumber(num);
    if (n == null) {
        return null;
    }
    return new Integer((int) Math.rint(n.doubleValue()));
}

From source file:org.renjin.primitives.MathGroup.java

@Builtin
@Deferrable/* w w  w. ja v  a2  s .c o  m*/
@DataParallel(value = PreserveAttributeStyle.ALL, passNA = true)
public static double round(double x, int digits) {
    // adapted from the nmath library, fround.c

    double sign;
    int dig;

    if (Double.isNaN(x) || Double.isNaN(digits)) {
        return x + digits;
    }
    if (!DoubleVector.isFinite(x)) {
        return x;
    }

    if (digits == Double.POSITIVE_INFINITY) {
        return x;
    } else if (digits == Double.NEGATIVE_INFINITY) {
        return 0.0;
    }

    if (digits > MAX_DIGITS) {
        digits = MAX_DIGITS;
    }
    dig = (int) Math.floor(digits + 0.5);

    if (x < 0.) {
        sign = -1.;
        x = -x;
    } else {
        sign = 1.;
    }
    if (dig == 0) {
        return sign * Math.rint(x);
    } else if (dig > 0) {
        // round to a specific number of decimal places
        return sign * new BigDecimal(x).setScale(digits, RoundingMode.HALF_EVEN).doubleValue();
    } else {
        // round to the nearest power of 10
        double pow10 = Math.pow(10., -dig);
        return sign * Math.rint(x / pow10) * pow10;
    }
}

From source file:de.tor.tribes.ui.panels.MinimapPanel.java

/**
 * Creates new form MinimapPanel/*from w ww.  ja v a2s . co m*/
 */
MinimapPanel() {
    initComponents();
    setSize(300, 300);
    mMinimapListeners = new LinkedList<>();
    mToolChangeListeners = new LinkedList<>();
    setCursor(ImageManager.getCursor(iCurrentCursor));
    mScreenshotPanel = new ScreenshotPanel();
    minimapButtons.put(ID_MINIMAP, new Rectangle(2, 2, 26, 26));
    minimapButtons.put(ID_ALLY_CHART, new Rectangle(30, 2, 26, 26));
    minimapButtons.put(ID_TRIBE_CHART, new Rectangle(60, 2, 26, 26));
    try {
        minimapIcons.put(ID_MINIMAP, ImageIO.read(new File("./graphics/icons/minimap.png")));
        minimapIcons.put(ID_ALLY_CHART, ImageIO.read(new File("./graphics/icons/ally_chart.png")));
        minimapIcons.put(ID_TRIBE_CHART, ImageIO.read(new File("./graphics/icons/tribe_chart.png")));
    } catch (Exception ignored) {
    }
    jPanel1.add(mScreenshotPanel);
    rVisiblePart = new Rectangle(ServerSettings.getSingleton().getMapDimension());
    zoomed = false;
    MarkerManager.getSingleton().addManagerListener(this);
    TagManager.getSingleton().addManagerListener(this);
    MinimapRepaintThread.getSingleton().setVisiblePart(rVisiblePart);
    if (!GlobalOptions.isMinimal()) {
        MinimapRepaintThread.getSingleton().start();
    }
    addMouseListener(new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (!showControls && e.getButton() != MouseEvent.BUTTON1) {
                //show controls
                Point p = e.getPoint();
                p.translate(-5, -5);
                showControls(p);
                return;
            }
            if (!showControls && iCurrentView == ID_MINIMAP) {
                Point p = mousePosToMapPosition(e.getX(), e.getY());
                DSWorkbenchMainFrame.getSingleton().centerPosition(p.getX(), p.getY());
                MapPanel.getSingleton().getMapRenderer().initiateRedraw(MapRenderer.ALL_LAYERS);
                if (MinimapZoomFrame.getSingleton().isVisible()) {
                    MinimapZoomFrame.getSingleton().toFront();
                }
            } else {
                if (minimapButtons.get(ID_MINIMAP).contains(e.getPoint())) {
                    iCurrentView = ID_MINIMAP;
                    mBuffer = null;
                    showControls = false;
                    MinimapRepaintThread.getSingleton().update();
                } else if (minimapButtons.get(ID_ALLY_CHART).contains(e.getPoint())) {
                    iCurrentView = ID_ALLY_CHART;
                    lastHash = 0;
                    showControls = false;
                    updateComplete();
                } else if (minimapButtons.get(ID_TRIBE_CHART).contains(e.getPoint())) {
                    iCurrentView = ID_TRIBE_CHART;
                    lastHash = 0;
                    showControls = false;
                    updateComplete();
                }
            }
        }

        @Override
        public void mousePressed(MouseEvent e) {
            if (iCurrentView != ID_MINIMAP) {
                return;
            }
            if (iCurrentCursor == ImageManager.CURSOR_SHOT || iCurrentCursor == ImageManager.CURSOR_ZOOM) {
                iXDown = e.getX();
                iYDown = e.getY();
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (iCurrentView != ID_MINIMAP) {
                return;
            }
            if (rDrag == null) {
                return;
            }
            if (iCurrentCursor == ImageManager.CURSOR_SHOT) {
                try {
                    BufferedImage i = MinimapRepaintThread.getSingleton().getImage();
                    double widthFactor = ((double) ServerSettings.getSingleton().getMapDimension().width)
                            / getWidth();
                    double heightFactor = ((double) ServerSettings.getSingleton().getMapDimension().height)
                            / getHeight();

                    int x = (int) Math.rint(widthFactor * rDrag.getX());
                    int y = (int) Math.rint(heightFactor * rDrag.getY());
                    int w = (int) Math.rint(widthFactor * (rDrag.getWidth() - rDrag.getX()));
                    int h = (int) Math.rint(heightFactor * (rDrag.getHeight() - rDrag.getY()));
                    BufferedImage sub = i.getSubimage(x, y, w, h);
                    mScreenshotPanel.setBuffer(sub);
                    jPanel1.setSize(mScreenshotPanel.getSize());
                    jPanel1.setPreferredSize(mScreenshotPanel.getSize());
                    jPanel1.setMinimumSize(mScreenshotPanel.getSize());
                    jPanel1.setMaximumSize(mScreenshotPanel.getSize());
                    jScreenshotPreview.pack();
                    jScreenshotControl.pack();
                    jScreenshotPreview.setVisible(true);
                    jScreenshotControl.setVisible(true);
                } catch (Exception ie) {
                    logger.error("Failed to initialize mapshot", ie);
                }
            } else if (iCurrentCursor == ImageManager.CURSOR_ZOOM) {
                if (!zoomed) {
                    Rectangle mapDim = ServerSettings.getSingleton().getMapDimension();
                    double widthFactor = ((double) mapDim.width) / getWidth();
                    double heightFactor = ((double) mapDim.height) / getHeight();

                    int x = (int) Math.rint(widthFactor * rDrag.getX() + mapDim.getMinX());
                    int y = (int) Math.rint(heightFactor * rDrag.getY() + mapDim.getMinY());
                    int w = (int) Math.rint(widthFactor * (rDrag.getWidth() - rDrag.getX()));

                    if (w >= 10) {
                        rVisiblePart = new Rectangle(x, y, w, w);
                        MinimapRepaintThread.getSingleton().setVisiblePart(rVisiblePart);
                        redraw();
                        zoomed = true;
                    }
                } else {
                    rVisiblePart = new Rectangle(ServerSettings.getSingleton().getMapDimension());
                    MinimapRepaintThread.getSingleton().setVisiblePart(rVisiblePart);
                    redraw();
                    zoomed = false;
                }
                MinimapZoomFrame.getSingleton().setVisible(false);
            }
            iXDown = 0;
            iYDown = 0;
            rDrag = null;
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            if (iCurrentView != ID_MINIMAP) {
                return;
            }
            switch (iCurrentCursor) {
            case ImageManager.CURSOR_ZOOM: {
                MinimapZoomFrame.getSingleton().setVisible(true);
            }
            }
        }

        @Override
        public void mouseExited(MouseEvent e) {
            if (MinimapZoomFrame.getSingleton().isVisible()) {
                MinimapZoomFrame.getSingleton().setVisible(false);
            }
            iXDown = 0;
            iYDown = 0;
            rDrag = null;
        }
    });

    addMouseMotionListener(new MouseMotionListener() {

        @Override
        public void mouseDragged(MouseEvent e) {
            if (iCurrentView != ID_MINIMAP) {
                return;
            }
            switch (iCurrentCursor) {
            case ImageManager.CURSOR_MOVE: {
                Point p = mousePosToMapPosition(e.getX(), e.getY());
                DSWorkbenchMainFrame.getSingleton().centerPosition(p.x, p.y);
                rDrag = null;
                break;
            }
            case ImageManager.CURSOR_SHOT: {
                rDrag = new Rectangle2D.Double(iXDown, iYDown, e.getX(), e.getY());
                break;
            }
            case ImageManager.CURSOR_ZOOM: {
                rDrag = new Rectangle2D.Double(iXDown, iYDown, e.getX(), e.getY());
                break;
            }
            }
        }

        @Override
        public void mouseMoved(MouseEvent e) {
            if (iCurrentView == ID_MINIMAP) {
                switch (iCurrentCursor) {
                case ImageManager.CURSOR_ZOOM: {
                    if (!MinimapZoomFrame.getSingleton().isVisible()) {
                        MinimapZoomFrame.getSingleton().setVisible(true);
                    }
                    int mapWidth = (int) ServerSettings.getSingleton().getMapDimension().getWidth();
                    int mapHeight = (int) ServerSettings.getSingleton().getMapDimension().getHeight();

                    int x = (int) Math.rint((double) mapWidth / (double) getWidth() * (double) e.getX());
                    int y = (int) Math.rint((double) mapHeight / (double) getHeight() * (double) e.getY());
                    MinimapZoomFrame.getSingleton().updatePosition(x, y);
                    break;
                }
                default: {
                    if (MinimapZoomFrame.getSingleton().isVisible()) {
                        MinimapZoomFrame.getSingleton().setVisible(false);
                    }
                }
                }
            }
            Point location = minimapButtons.get(ID_MINIMAP).getLocation();
            location.translate(-2, -2);
            if (!new Rectangle(location.x, location.y, 88, 30).contains(e.getPoint())) {
                //hide controls
                showControls = false;
                repaint();
            }
        }
    });

    addMouseWheelListener(new MouseWheelListener() {

        @Override
        public void mouseWheelMoved(MouseWheelEvent e) {

            if (iCurrentView != ID_MINIMAP) {
                return;
            }
            iCurrentCursor += e.getWheelRotation();
            if (iCurrentCursor == ImageManager.CURSOR_DEFAULT + e.getWheelRotation()) {
                if (e.getWheelRotation() < 0) {
                    iCurrentCursor = ImageManager.CURSOR_SHOT;
                } else {
                    iCurrentCursor = ImageManager.CURSOR_MOVE;
                }
            } else if (iCurrentCursor < ImageManager.CURSOR_MOVE) {
                iCurrentCursor = ImageManager.CURSOR_DEFAULT;
            } else if (iCurrentCursor > ImageManager.CURSOR_SHOT) {
                iCurrentCursor = ImageManager.CURSOR_DEFAULT;
            }
            if (iCurrentCursor != ImageManager.CURSOR_ZOOM) {
                if (MinimapZoomFrame.getSingleton().isVisible()) {
                    MinimapZoomFrame.getSingleton().setVisible(false);
                }
            } else {
                MinimapZoomFrame.getSingleton().setVisible(true);
            }
            setCurrentCursor(iCurrentCursor);
        }
    });

}

From source file:it.cnr.istc.utils.gui.ReverseGradientXYBarPainter.java

/**
 * Splits a bar into subregions (elsewhere, these subregions will have
 * different gradients applied to them).
 *
 * @param bar the bar shape.//from ww w.  ja  v a2 s. c  om
 * @param a the first division.
 * @param b the second division.
 * @param c the third division.
 *
 * @return An array containing four subregions.
 */
private Rectangle2D[] splitHorizontalBar(RectangularShape bar, double a, double b, double c) {
    Rectangle2D[] result = new Rectangle2D[4];
    double y0 = bar.getMinY();
    double y1 = Math.rint(y0 + (bar.getHeight() * a));
    double y2 = Math.rint(y0 + (bar.getHeight() * b));
    double y3 = Math.rint(y0 + (bar.getHeight() * c));
    result[0] = new Rectangle2D.Double(bar.getMinX(), bar.getMinY(), bar.getWidth(), y1 - y0);
    result[1] = new Rectangle2D.Double(bar.getMinX(), y1, bar.getWidth(), y2 - y1);
    result[2] = new Rectangle2D.Double(bar.getMinX(), y2, bar.getWidth(), y3 - y2);
    result[3] = new Rectangle2D.Double(bar.getMinX(), y3, bar.getWidth(), bar.getMaxY() - y3);
    return result;
}

From source file:edu.kit.dama.ui.simon.panel.SimonMainPanel.java

/**
 * Build the overview tab including the list of all categories and der
 * overall status./*from  ww  w.j  a  v a2 s  .  c om*/
 *
 * @param pCategories A list of all categories.
 *
 * @return The tab component.
 */
private Component buildOverviewTab(String[] pCategories) {
    AbsoluteLayout abLay = new AbsoluteLayout();
    UIUtils7.GridLayoutBuilder layoutBuilder = new UIUtils7.GridLayoutBuilder(4, pCategories.length + 1);

    updateButton = new Button("Update Status");
    updateButton.addClickListener(this);
    Embedded logo = new Embedded(null, new ThemeResource("img/simon.png"));
    abLay.addComponent(logo, "top:30px;left:30px;");

    Label simonSaysLabel = new Label("", ContentMode.HTML);
    simonSaysLabel.setHeight("150px");
    setSimonSaysContent(simonSaysLabel, "Everything is fine.");
    abLay.addComponent(simonSaysLabel, "top:30px;left:250px;");

    int row = 0;
    for (String category : pCategories) {
        HorizontalLayout rowLayout = new HorizontalLayout();
        Label name = new Label(category);
        name.setWidth("200px");
        name.setHeight("24px");
        List<AbstractProbe> probes = probesByCategory.get(category);
        Collections.sort(probes, new Comparator<AbstractProbe>() {
            @Override
            public int compare(AbstractProbe o1, AbstractProbe o2) {
                return o1.getCurrentStatus().compareTo(o2.getCurrentStatus());
            }
        });

        int failed = 0;
        int unknown = 0;
        int unavailable = 0;
        int charactersPerProbe = 100;
        if (probes.size() > 0) {
            charactersPerProbe = (int) Math.rint((700.0 / probes.size()) / 8.0);
        }

        for (AbstractProbe probe : probes) {
            Label probeLabel = new Label(StringUtils.abbreviate(probe.getName(), charactersPerProbe));
            probeLabel.setHeight("24px");
            switch (probe.getCurrentStatus()) {
            case UNKNOWN:
                probeLabel.setDescription(probe.getName() + ": UNKNOWN");
                probeLabel.addStyleName("probe-unknown");
                unknown++;
                break;
            case UPDATING:
                probeLabel.setDescription(probe.getName() + ": UPDATING");
                probeLabel.addStyleName("probe-updating");
                break;
            case UNAVAILABLE:
                probeLabel.setDescription(probe.getName() + ": UNAVAILABLE");
                probeLabel.addStyleName("probe-unavailable");
                unavailable++;
                break;
            case FAILED:
                probeLabel.setDescription(probe.getName() + ": FAILED");
                probeLabel.addStyleName("probe-failed");
                failed++;
                break;
            default:
                probeLabel.setDescription(probe.getName() + ": SUCCESS");
                probeLabel.addStyleName("probe-success");
            }

            probeLabel.addStyleName("probe");
            rowLayout.addComponent(probeLabel);
        }

        if (failed != 0) {
            setSimonSaysContent(simonSaysLabel, "There are errors!");
        } else {
            if (unknown != 0) {
                setSimonSaysContent(simonSaysLabel, "There are unknown states. Please select 'Update Status'.");
            } else {
                if (unavailable != 0) {
                    setSimonSaysContent(simonSaysLabel,
                            "Some probes are unavailable. Please check their configuration.");
                }
            }
        }

        rowLayout.setWidth("700px");
        layoutBuilder.addComponent(name, Alignment.TOP_LEFT, 0, row, 1, 1).addComponent(rowLayout,
                Alignment.TOP_LEFT, 1, row, 3, 1);
        row++;
    }

    layoutBuilder.addComponent(updateButton, Alignment.BOTTOM_RIGHT, 3, row, 1, 1);

    GridLayout tabLayout = layoutBuilder.getLayout();
    tabLayout.setSpacing(true);
    tabLayout.setMargin(true);
    Panel p = new Panel();
    p.setContent(tabLayout);
    p.setWidth("1024px");
    p.setHeight("400px");
    abLay.addComponent(p, "top:160px;left:30px;");
    abLay.setSizeFull();
    return abLay;
}

From source file:io.cortical.retina.core.ExpressionsTest.java

/**
 * {@link Expressions#getFingerprintsForExpressions(io.cortical.retina.model.Model, double)}
 * @throws JsonProcessingException      should never be thrown
 * @throws ApiException     should never be thrown
 *//*w  w w. ja  v a 2  s . c  om*/
@Test
public void testGetFingerprintsForExpressions() throws ApiException, JsonProcessingException {
    int count = 2;
    double sparsity = 0.02;
    List<Term> terms = Arrays.asList(TERM_1, TERM_2);
    String termJson = Model.toJson(terms);

    when(expressionsApi.resolveBulkExpression(eq(termJson), eq(NOT_NULL_RETINA), eq(0.02)))
            .thenReturn(createFingerprints(count, sparsity));
    List<Fingerprint> fingerprints = expressions.getFingerprintsForExpressions(terms, sparsity);
    assertEquals(
            "[124, 133, 146, 181, 192, 230, 249, 279, 442, 447, 514, 597, 612, "
                    + "659, 785, 858, 861, 895, 1150, 1247, 1262, 1315, 1321, 1485, "
                    + "1496, 1518, 1522, 1535, 1580, 1685, 1701, 1882, 1896, 2054, "
                    + "2068, 2097, 2108, 2115, 2231, 2235, 2290, 2404, 2405, 2432, "
                    + "2466, 2474, 2489, 2502, 2520, 2534, 2599, 2623, 2799, 2800, "
                    + "2821, 2838, 2906, 2937, 2963, 3033, 3092, 3210, 3213, 3261, "
                    + "3286, 3401, 3436, 3596, 3987, 4106, 4123, 4160, 4229, 4263, "
                    + "4352, 4492, 4517, 4539, 4546, 4568, 4596, 4623, 4651, 4666, "
                    + "4752, 4763, 4777, 4778, 4871, 4965, 5006, 5058, 5090, 5163, "
                    + "5166, 5186, 5383, 5444, 5513, 5542, 5566, 5627, 5635, 5649, "
                    + "5864, 5902, 5904, 5922, 5982, 6005, 6042, 6047, 6078, 6124, "
                    + "6133, 6161, 6200, 6252, 6268, 6290, 6301, 6333, 6353, 6429, "
                    + "6467, 6484, 6496, 6513, 6586, 6635, 6843, 6862, 6897, 6933, "
                    + "6938, 6955, 7066, 7090, 7121, 7126, 7148, 7151, 7205, 7236, "
                    + "7253, 7302, 7393, 7492, 7501, 7516, 7526, 7541, 7592, 7596, "
                    + "7678, 7684, 7729, 7744, 7869, 7873, 7886, 7927, 7972, 7998, "
                    + "8148, 8274, 8332, 8335, 8505, 8514, 8544, 8732, 8756, 8758, "
                    + "8845, 8894, 8981, 8983, 8993, 8994, 9115, 9172, 9355, 9365, "
                    + "9396, 9503, 9559, 9624, 9642, 9676, 9737, 9762, 9791, 9811, "
                    + "9877, 10061, 10078, 10096, 10264, 10288, 10313, 10338, 10344, "
                    + "10368, 10405, 10430, 10495, 10527, 10545, 10587, 10629, 10732, "
                    + "10766, 10782, 10800, 10822, 10830, 10904, 10986, 11193, 11235, "
                    + "11276, 11286, 11311, 11371, 11402, 11421, 11423, 11466, 11502, "
                    + "11570, 11595, 11688, 11798, 11885, 11896, 11920, 11953, 12091, "
                    + "12208, 12218, 12286, 12308, 12329, 12342, 12413, 12419, 12472, "
                    + "12486, 12530, 12608, 12623, 12633, 12699, 12704, 12792, 12827, "
                    + "12920, 12954, 13023, 13040, 13042, 13079, 13084, 13108, 13140, "
                    + "13195, 13201, 13256, 13264, 13391, 13398, 13442, 13463, 13487, "
                    + "13532, 13554, 13584, 13659, 13662, 13683, 13884, 13931, 14014, "
                    + "14018, 14136, 14183, 14194, 14283, 14310, 14515, 14559, 14603, "
                    + "14647, 14666, 14706, 14722, 14732, 14800, 14804, 14819, 14820, "
                    + "14886, 14953, 15062, 15081, 15247, 15380, 15403, 15434, 15471, "
                    + "15562, 15580, 15765, 15769, 15835, 15851, 15878, 15889, 15958, "
                    + "15991, 16016, 16032, 16137, 16143, 16318, 16354, 16366]",
            Arrays.toString(fingerprints.get(0).getPositions()));
    assertEquals(Math.rint(16384. * 0.02), fingerprints.get(0).getPositions().length, 0.001);
    assertEquals(Math.rint(16384. * 0.02), fingerprints.get(1).getPositions().length, 0.001);
    verify(expressionsApi, times(1)).resolveBulkExpression(eq(termJson), eq(NOT_NULL_RETINA), eq(0.02));
}

From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java

@Override
public X509Certificate generateCertificate(PublicKey key, X500Principal subjectDn, X500Principal signer,
        PrivateKey signingKey, Date notAfter) {
    if (signingKey == null) {
        LOG.error("No signing key is provided");
        return null;
    }/*  w w  w . j  av a2s . c om*/
    if (signer == null) {
        LOG.error("No signiner principal is specified");
        return null;
    }
    if (subjectDn == null) {
        LOG.error("No subject principal is specified");
        return null;
    }
    if (key == null) {
        LOG.error("No requesting key is specified");
        return null;
    }

    EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_CERTIFICATE, signer.toString(),
            subjectDn.toString()).info();
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.nanoTime()).shiftLeft(4)
            .add(BigInteger.valueOf((long) Math.rint(Math.random() * 1000))));
    certGen.setIssuerDN(signer);
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    try {
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(key));
    } catch (InvalidKeyException e) {
        LOG.error("Error adding subject key identifier extension.", e);
    }
    Calendar cal = Calendar.getInstance();
    certGen.setNotBefore(cal.getTime());
    certGen.setNotAfter(notAfter);
    certGen.setSubjectDN(subjectDn);
    certGen.setPublicKey(key);
    certGen.setSignatureAlgorithm(KEY_SIGNING_ALGORITHM);
    try {
        X509Certificate cert = certGen.generate(signingKey, PROVIDER);
        cert.checkValidity();
        return cert;
    } catch (Exception e) {
        LOG.fatal(e, e);
        return null;
    }
}

From source file:projects.wdlf47tuc.ProcessAllSwathcal.java

/**
 * Main entry point./*from w ww.  j a  v a2  s  .  co  m*/
 * 
 * @param args
 * 
 * @throws IOException 
 * 
 */
public ProcessAllSwathcal() {

    // Path to AllSwathcal.dat file
    File allSwathcal = new File(
            "/home/nrowell/Astronomy/Data/47_Tuc/Kalirai_2012/UVIS/www.stsci.edu/~jkalirai/47Tuc/AllSwathcal.dat");

    // Read file contents into the List
    try (BufferedReader in = new BufferedReader(new FileReader(allSwathcal))) {
        String sourceStr;
        while ((sourceStr = in.readLine()) != null) {
            Source source = Source.parseSource(sourceStr);
            if (source != null) {
                allSources.add(source);
            }
        }
    } catch (IOException e) {
    }

    logger.info("Parsed " + allSources.size() + " Sources from AllSwathcal.dat");

    // Initialise chart
    cmdPanel = new ChartPanel(updateDataAndPlotCmd(allSources));
    cmdPanel.addChartMouseListener(new ChartMouseListener() {
        @Override
        public void chartMouseClicked(ChartMouseEvent e) {
            // Capture mouse click location, transform to graph coordinates and add
            // a point to the polygonal selection box.
            Point2D p = cmdPanel.translateScreenToJava2D(e.getTrigger().getPoint());
            Rectangle2D plotArea = cmdPanel.getScreenDataArea();
            XYPlot plot = (XYPlot) cmdPanel.getChart().getPlot();
            double chartX = plot.getDomainAxis().java2DToValue(p.getX(), plotArea, plot.getDomainAxisEdge());
            double chartY = plot.getRangeAxis().java2DToValue(p.getY(), plotArea, plot.getRangeAxisEdge());
            points.add(new double[] { chartX, chartY });
            cmdPanel.setChart(plotCmd());
        }

        @Override
        public void chartMouseMoved(ChartMouseEvent arg0) {
        }
    });

    // Create colour combo boxes
    final JComboBox<Filter> magComboBox = new JComboBox<Filter>(filters);
    final JComboBox<Filter> col1ComboBox = new JComboBox<Filter>(filters);
    final JComboBox<Filter> col2ComboBox = new JComboBox<Filter>(filters);

    // Set initial values
    magComboBox.setSelectedItem(magFilter);
    col1ComboBox.setSelectedItem(col1Filter);
    col2ComboBox.setSelectedItem(col2Filter);

    // Create an action listener for these
    ActionListener al = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            if (evt.getSource() == magComboBox) {
                magFilter = (Filter) magComboBox.getSelectedItem();
            }
            if (evt.getSource() == col1ComboBox) {
                col1Filter = (Filter) col1ComboBox.getSelectedItem();
            }
            if (evt.getSource() == col2ComboBox) {
                col2Filter = (Filter) col2ComboBox.getSelectedItem();
            }
            // Changed colour(s), so reset selection box coordinates
            points.clear();
            cmdPanel.setChart(updateDataAndPlotCmd(allSources));
        }
    };
    magComboBox.addActionListener(al);
    col1ComboBox.addActionListener(al);
    col2ComboBox.addActionListener(al);
    // Add a bit of padding to space things out
    magComboBox.setBorder(new EmptyBorder(5, 5, 5, 5));
    col1ComboBox.setBorder(new EmptyBorder(5, 5, 5, 5));
    col2ComboBox.setBorder(new EmptyBorder(5, 5, 5, 5));

    // Set up statistic sliders
    final JSlider magErrMaxSlider = GuiUtil.buildSlider(magErrorRangeMin, magErrorRangeMax, 3, "%3.3f");
    final JSlider chi2MaxSlider = GuiUtil.buildSlider(chi2RangeMin, chi2RangeMax, 3, "%3.3f");
    final JSlider sharpMinSlider = GuiUtil.buildSlider(sharpRangeMin, sharpRangeMax, 3, "%3.3f");
    final JSlider sharpMaxSlider = GuiUtil.buildSlider(sharpRangeMin, sharpRangeMax, 3, "%3.3f");

    // Set intial values
    magErrMaxSlider.setValue(
            (int) Math.rint(100.0 * (magErrMax - magErrorRangeMin) / (magErrorRangeMax - magErrorRangeMin)));
    chi2MaxSlider.setValue((int) Math.rint(100.0 * (chi2Max - chi2RangeMin) / (chi2RangeMax - chi2RangeMin)));
    sharpMinSlider
            .setValue((int) Math.rint(100.0 * (sharpMin - sharpRangeMin) / (sharpRangeMax - sharpRangeMin)));
    sharpMaxSlider
            .setValue((int) Math.rint(100.0 * (sharpMax - sharpRangeMin) / (sharpRangeMax - sharpRangeMin)));

    // Set labels & initial values
    final JLabel magErrMaxLabel = new JLabel(getMagErrMaxLabel());
    final JLabel chi2MaxLabel = new JLabel(getChi2MaxLabel());
    final JLabel sharpMinLabel = new JLabel(getSharpMinLabel());
    final JLabel sharpMaxLabel = new JLabel(getSharpMaxLabel());

    // Create a change listener fot these
    ChangeListener cl = new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            JSlider source = (JSlider) e.getSource();

            if (source == magErrMaxSlider) {
                // Compute max mag error from slider position
                double newMagErrMax = magErrorRangeMin
                        + (magErrorRangeMax - magErrorRangeMin) * (source.getValue() / 100.0);
                magErrMax = newMagErrMax;
                magErrMaxLabel.setText(getMagErrMaxLabel());
            }
            if (source == chi2MaxSlider) {
                // Compute Chi2 max from slider position
                double newChi2Max = chi2RangeMin + (chi2RangeMax - chi2RangeMin) * (source.getValue() / 100.0);
                chi2Max = newChi2Max;
                chi2MaxLabel.setText(getChi2MaxLabel());
            }
            if (source == sharpMinSlider) {
                // Compute sharp min from slider position
                double newSharpMin = sharpRangeMin
                        + (sharpRangeMax - sharpRangeMin) * (source.getValue() / 100.0);
                sharpMin = newSharpMin;
                sharpMinLabel.setText(getSharpMinLabel());
            }
            if (source == sharpMaxSlider) {
                // Compute sharp max from slider position
                double newSharpMax = sharpRangeMin
                        + (sharpRangeMax - sharpRangeMin) * (source.getValue() / 100.0);
                sharpMax = newSharpMax;
                sharpMaxLabel.setText(getSharpMaxLabel());
            }
            cmdPanel.setChart(updateDataAndPlotCmd(allSources));
        }
    };
    magErrMaxSlider.addChangeListener(cl);
    chi2MaxSlider.addChangeListener(cl);
    sharpMinSlider.addChangeListener(cl);
    sharpMaxSlider.addChangeListener(cl);
    // Add a bit of padding to space things out
    magErrMaxSlider.setBorder(new EmptyBorder(5, 5, 5, 5));
    chi2MaxSlider.setBorder(new EmptyBorder(5, 5, 5, 5));
    sharpMinSlider.setBorder(new EmptyBorder(5, 5, 5, 5));
    sharpMaxSlider.setBorder(new EmptyBorder(5, 5, 5, 5));

    // Text field to store distance modulus
    final JTextField distanceModulusField = new JTextField(Double.toString(mu));
    distanceModulusField.setBorder(new EmptyBorder(5, 5, 5, 5));

    Border compound = BorderFactory.createCompoundBorder(new LineBorder(this.getBackground(), 5),
            BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));

    final JButton lfButton = new JButton("Luminosity function for selection");
    lfButton.setBorder(compound);
    lfButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            // Read distance modulus field
            try {
                double mu_new = Double.parseDouble(distanceModulusField.getText());
                mu = mu_new;
            } catch (NullPointerException | NumberFormatException ex) {
                JOptionPane.showMessageDialog(lfButton,
                        "Error parsing the distance modulus: " + ex.getMessage(), "Distance Modulus Error",
                        JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (boxedSources.isEmpty()) {
                JOptionPane.showMessageDialog(lfButton, "No sources are currently selected!", "Selection Error",
                        JOptionPane.ERROR_MESSAGE);
            } else {
                computeAndPlotLuminosityFunction(boxedSources);
            }
        }
    });
    final JButton clearSelectionButton = new JButton("Clear selection");
    clearSelectionButton.setBorder(compound);
    clearSelectionButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            points.clear();
            cmdPanel.setChart(plotCmd());
        }
    });

    JPanel controls = new JPanel(new GridLayout(9, 2));
    controls.setBorder(new EmptyBorder(10, 10, 10, 10));
    controls.add(new JLabel("Magnitude = "));
    controls.add(magComboBox);
    controls.add(new JLabel("Colour 1 = "));
    controls.add(col1ComboBox);
    controls.add(new JLabel("Colour 2 = "));
    controls.add(col2ComboBox);
    controls.add(magErrMaxLabel);
    controls.add(magErrMaxSlider);
    controls.add(chi2MaxLabel);
    controls.add(chi2MaxSlider);
    controls.add(sharpMinLabel);
    controls.add(sharpMinSlider);
    controls.add(sharpMaxLabel);
    controls.add(sharpMaxSlider);
    controls.add(new JLabel("Adopted distance modulus = "));
    controls.add(distanceModulusField);
    controls.add(lfButton);
    controls.add(clearSelectionButton);

    this.setLayout(new BorderLayout());
    this.add(cmdPanel, BorderLayout.CENTER);
    this.add(controls, BorderLayout.SOUTH);

    this.validate();
}

From source file:org.kalypso.kalypsosimulationmodel.utils.SLDHelper.java

/**
 * if lightestColor is null, than WHITE (0, 0, 0) is used instead
 *//*from  w  ww. j  a  v  a 2  s. c  o m*/
private static StyledLayerDescriptor createRasterSLD(final double minValue, final double maxValue,
        final int numberOfIntervals, final Color lightestColor, final Color darkestColor,
        final String styleName, final String styleTitle, final IProgressMonitor monitor) throws CoreException {
    final TreeMap<Double, ColorMapEntry> colorMap = new TreeMap<>();
    final FeatureTypeStyle style = StyleFactory.createFeatureTypeStyle();

    final int rd = darkestColor.getRed();
    final int gd = darkestColor.getGreen();
    final int bd = darkestColor.getBlue();
    final int rl = lightestColor == null ? 0 : lightestColor.getRed();
    final int gl = lightestColor == null ? 0 : lightestColor.getGreen();
    final int bl = lightestColor == null ? 0 : lightestColor.getBlue();
    for (int i = 0; i <= numberOfIntervals; i++) {
        final double ratio = (double) i / (double) numberOfIntervals;
        final double quantity = Math.rint(1000.0 * (minValue + (maxValue - minValue) * ratio)) / 1000.0;

        // making lighter color (color.brighter() is not so good...)
        final int r = (int) (rd * ratio + rl * (1 - ratio));
        final int g = (int) (gd * ratio + gl * (1 - ratio));
        final int b = (int) (bd * ratio + bl * (1 - ratio));

        final ColorMapEntry colorMapEntry = new ColorMapEntry_Impl(new Color(r, g, b),
                DEFAULT_RASTER_FILLOPACITY, quantity, ""); //$NON-NLS-1$
        colorMap.put(quantity, colorMapEntry);
        if (monitor.isCanceled())
            throw new CoreException(Status.CANCEL_STATUS);
    }

    final RasterSymbolizer rasterSymbolizer = new RasterSymbolizer_Impl(null, colorMap, null, null);
    final Rule rule = StyleFactory.createRule(rasterSymbolizer);
    style.addRule(rule);

    final FeatureTypeStyle[] featureTypeStyles = new FeatureTypeStyle[] { style };
    final Style[] styles = new Style[] {
            StyleFactory.createUserStyle(styleName, styleTitle, null, false, featureTypeStyles) };
    final org.kalypsodeegree.graphics.sld.Layer[] layers = new org.kalypsodeegree.graphics.sld.Layer[] {
            SLDFactory.createNamedLayer(LAYER_NAME, null, styles) };
    return SLDFactory.createStyledLayerDescriptor(layers);
}

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

private List getAllTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) {
    // TODO Auto-generated method stub
    List ticks = new java.util.ArrayList();
    Range range = getRange();//from  w  ww.  j  a  va  2s.  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
                    //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 { //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 = 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 = 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 (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)));
                    }
                    if (definition < 2 * Math.pow(10, -numberOfDigits)) {
                        numberOfDigits++;
                    }
                    double tickVal;
                    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.TOP_CENTER,
                            TextAnchor.TOP_CENTER, 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.TOP_CENTER,
                            TextAnchor.TOP_CENTER, 0.0));
                }
                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 (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)));
        }
        double tickVal;
        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.TOP_CENTER, TextAnchor.TOP_CENTER,
                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.TOP_CENTER, TextAnchor.TOP_CENTER,
                0.0));
    }
    return ticks;
}