Example usage for java.awt.geom Rectangle2D getMaxY

List of usage examples for java.awt.geom Rectangle2D getMaxY

Introduction

In this page you can find the example usage for java.awt.geom Rectangle2D getMaxY.

Prototype

public double getMaxY() 

Source Link

Document

Returns the largest Y coordinate of the framing rectangle of the Shape in double precision.

Usage

From source file:com.rapidminer.gui.new_plotter.engine.jfreechart.link_and_brush.LinkAndBrushChartPanel.java

@Override
public void mouseDragged(MouseEvent e) {
    // when not allowed to zoom / select, return
    if (blockSelectionOrZoom) {
        return;//from  www  .j  a va  2s  . c o m
    }
    // if the popup menu has already been triggered, then ignore dragging...
    if (getChartFieldValueByName("popup") != null
            && ((JPopupMenu) getChartFieldValueByName("popup")).isShowing()) {
        return;
    }

    // handle panning if we have a start point
    if (getChartFieldValueByName("panLast") != null) {
        double dx = e.getX() - ((Point) getChartFieldValueByName("panLast")).getX();
        double dy = e.getY() - ((Point) getChartFieldValueByName("panLast")).getY();
        if (dx == 0.0 && dy == 0.0) {
            return;
        }
        double wPercent = -dx / ((Double) getChartFieldValueByName("panW"));
        double hPercent = dy / ((Double) getChartFieldValueByName("panH"));
        boolean old = getChart().getPlot().isNotify();
        getChart().getPlot().setNotify(false);
        Pannable p = (Pannable) getChart().getPlot();
        if (p.getOrientation() == PlotOrientation.VERTICAL) {
            p.panDomainAxes(wPercent, getChartRenderingInfo().getPlotInfo(),
                    (Point) getChartFieldValueByName("panLast"));
            p.panRangeAxes(hPercent, getChartRenderingInfo().getPlotInfo(),
                    (Point) getChartFieldValueByName("panLast"));
        } else {
            p.panDomainAxes(hPercent, getChartRenderingInfo().getPlotInfo(),
                    (Point) getChartFieldValueByName("panLast"));
            p.panRangeAxes(wPercent, getChartRenderingInfo().getPlotInfo(),
                    (Point) getChartFieldValueByName("panLast"));
        }
        setChartFieldValue((getChartFieldByName("panLast")), e.getPoint());
        getChart().getPlot().setNotify(old);
        return;
    }

    // if no initial zoom point was set, ignore dragging...
    if (getChartFieldValueByName("zoomPoint") == null) {
        return;
    }
    Graphics2D g2 = (Graphics2D) getGraphics();

    // erase the previous zoom rectangle (if any). We only need to do
    // this is we are using XOR mode, which we do when we're not using
    // the buffer (if there is a buffer, then at the end of this method we
    // just trigger a repaint)
    if (!(Boolean) getChartFieldValueByName("useBuffer")) {
        drawZoomRectangle(g2, true);
    }

    boolean hZoom = false;
    boolean vZoom = false;
    if ((PlotOrientation) getChartFieldValueByName("orientation") == PlotOrientation.HORIZONTAL) {
        hZoom = (Boolean) getChartFieldValueByName("rangeZoomable");
        vZoom = (Boolean) getChartFieldValueByName("domainZoomable");
    } else {
        hZoom = (Boolean) getChartFieldValueByName("domainZoomable");
        vZoom = (Boolean) getChartFieldValueByName("rangeZoomable");
    }
    Point2D zoomPoint = (Point2D) getChartFieldValueByName("zoomPoint");
    Rectangle2D scaledDataArea = getScreenDataArea((int) zoomPoint.getX(), (int) zoomPoint.getY());
    if (hZoom && vZoom) {
        // selected rectangle shouldn't extend outside the data area...
        double xmax = Math.min(e.getX(), scaledDataArea.getMaxX());
        double ymax = Math.min(e.getY(), scaledDataArea.getMaxY());
        setChartFieldValue(getChartFieldByName("zoomRectangle"), new Rectangle2D.Double(zoomPoint.getX(),
                zoomPoint.getY(), xmax - zoomPoint.getX(), ymax - zoomPoint.getY()));
    } else if (hZoom) {
        double xmax = Math.min(e.getX(), scaledDataArea.getMaxX());
        setChartFieldValue(getChartFieldByName("zoomRectangle"), new Rectangle2D.Double(zoomPoint.getX(),
                scaledDataArea.getMinY(), xmax - zoomPoint.getX(), scaledDataArea.getHeight()));
    } else if (vZoom) {
        double ymax = Math.min(e.getY(), scaledDataArea.getMaxY());
        setChartFieldValue(getChartFieldByName("zoomRectangle"),
                new Rectangle2D.Double(scaledDataArea.getMinX(), zoomPoint.getY(), scaledDataArea.getWidth(),
                        ymax - zoomPoint.getY()));
    }

    // Draw the new zoom rectangle...
    if ((Boolean) getChartFieldValueByName("useBuffer")) {
        repaint();
    } else {
        // with no buffer, we use XOR to draw the rectangle "over" the
        // chart...
        drawZoomRectangle(g2, true);
    }
    g2.dispose();

}

From source file:org.esa.beam.visat.toolviews.stat.ScatterPlotPanel.java

private ChartPanel createChartPanel(final JFreeChart chart) {
    scatterPlotDisplay = new ChartPanel(chart) {
        @Override/*from   www. j av  a 2  s.co m*/
        public void restoreAutoBounds() {
            // here we tweak the notify flag on the plot so that only
            // one notification happens even though we update multiple
            // axes...
            final XYPlot plot = chart.getXYPlot();
            boolean savedNotify = plot.isNotify();
            plot.setNotify(false);
            xAxisRangeControl.adjustAxis(plot.getDomainAxis(), 3);
            yAxisRangeControl.adjustAxis(plot.getRangeAxis(), 3);
            plot.setNotify(savedNotify);
        }
    };

    MaskSelectionToolSupport maskSelectionToolSupport = new MaskSelectionToolSupport(this, scatterPlotDisplay,
            "correlative_plot_area", "Mask generated from selected correlative plot area", Color.RED,
            PlotAreaSelectionTool.AreaType.Y_RANGE) {
        @Override
        protected String createMaskExpression(PlotAreaSelectionTool.AreaType areaType, Shape shape) {
            Rectangle2D bounds = shape.getBounds2D();
            return createMaskExpression(bounds.getMinY(), bounds.getMaxY());
        }

        protected String createMaskExpression(double x1, double x2) {
            String bandName = BandArithmetic.createExternalName(getRaster().getName());
            return String.format("%s >= %s && %s <= %s", bandName, x1, bandName, x2);
        }
    };
    scatterPlotDisplay.getPopupMenu().addSeparator();
    scatterPlotDisplay.getPopupMenu().add(maskSelectionToolSupport.createMaskSelectionModeMenuItem());
    scatterPlotDisplay.getPopupMenu().add(maskSelectionToolSupport.createDeleteMaskMenuItem());
    scatterPlotDisplay.getPopupMenu().addSeparator();
    scatterPlotDisplay.getPopupMenu().add(createCopyDataToClipboardMenuItem());
    return scatterPlotDisplay;
}

From source file:ucar.unidata.idv.control.chart.MyScatterPlot.java

/**
 * Draws the fast scatter plot on a Java 2D graphics device (such as the
 * screen or a printer)./*from  ww w  .  j a va 2 s. c  o m*/
 * a
 * @param g2  the graphics device.
 * @param dataArea the data area
 * @param index which data set
 * @param info  collects chart drawing information (<code>null</code>
 *              permitted).
 * @param crosshairState crosshairState
 *
 * @return did something
 */
public boolean render(Graphics2D g2, Rectangle2D dataArea, int index, PlotRenderingInfo info,
        CrosshairState crosshairState) {

    if (index >= series.size()) {
        return false;
    }
    XYDataset dataset = getDataset(index);
    g2.setStroke(new BasicStroke());
    //                   getRendererForDataset(dataset).getSeriesStroke(0));
    ScatterPlotChartWrapper.MyRenderer renderer = (ScatterPlotChartWrapper.MyRenderer) getRendererForDataset(
            dataset);
    g2.setPaint(renderer.getSeriesPaint(0));
    int shape = renderer.shape;

    PlotOrientation orientation = getOrientation();
    int seenCnt = 0;

    int xx = (int) dataArea.getMinX();
    int ww = (int) dataArea.getWidth();
    int yy = (int) dataArea.getMaxY();
    int hh = (int) dataArea.getHeight();
    ValueAxis rangeAxis = getRangeAxisForDataset(index);
    ValueAxis domainAxis = getDomainAxisForDataset(index);
    double domainMin = domainAxis.getLowerBound();
    double domainLength = domainAxis.getUpperBound() - domainMin;
    double rangeMin = rangeAxis.getLowerBound();
    double rangeLength = rangeAxis.getUpperBound() - rangeMin;
    int boxWidth = 6;

    double[][] data = (double[][]) series.get(index);

    double[] d1 = data[0];
    double[] d2 = data[1];
    int size = d1.length;

    Hashtable seen = new Hashtable();
    int lastX = 0;
    int lastY = 0;
    //TODO: Check for clipping
    //TODO: Try to create a GeneralPath with the points
    //and cal g2.draw just once
    GeneralPath path = new GeneralPath();
    long t1 = System.currentTimeMillis();

    for (int i = 0; i < size; i++) {
        int transX = (int) (xx + ww * (d1[i] - domainMin) / domainLength);
        int transY = (int) (yy - hh * (d2[i] - rangeMin) / rangeLength);
        Object key = transX + "_" + transY;
        if (seen.get(key) != null) {
            seenCnt++;
            continue;
        }
        seen.put(key, key);
        if (crosshairState != null) {
            crosshairState.updateCrosshairPoint(d1[i], d2[i], transX, transY, orientation);
        }

        switch (shape) {

        case LineState.SHAPE_VLINE:
            if (i > 1) {
                g2.drawLine(lastX, lastY, transX, transY);
            }
            lastX = transX;
            lastY = transY;

        case LineState.SHAPE_POINT:
            path.append(new Rectangle((int) transX, (int) transY, 1, 1), false);
            break;

        case LineState.SHAPE_LARGEPOINT:
            path.append(new Rectangle((int) transX, (int) transY, 2, 2), false);
            break;

        case LineState.SHAPE_RECTANGLE:
            path.append(
                    new Rectangle((int) transX - boxWidth / 2, (int) transY - boxWidth / 2, boxWidth, boxWidth),
                    false);
            break;

        case LineState.SHAPE_X:
            g2.drawLine(transX - boxWidth / 2, transY - boxWidth / 2, transX + boxWidth - boxWidth / 2,
                    transY + boxWidth - boxWidth / 2);
            g2.drawLine(transX + boxWidth - boxWidth / 2, transY - boxWidth / 2, transX - boxWidth / 2,
                    transY + boxWidth - boxWidth / 2);
            break;

        case LineState.SHAPE_PLUS:
            g2.drawLine(transX + boxWidth / 2, transY, transX + boxWidth / 2, transY + boxWidth);
            g2.drawLine(transX, transY + boxWidth / 2, transX + boxWidth, transY + boxWidth / 2);
            break;

        }
    }
    g2.fill(path);
    long t2 = System.currentTimeMillis();
    //        System.out.println ("time:" + (t2-t1));
    return true;
}

From source file:org.gumtree.vis.awt.time.TimePlotPanel.java

@Override
protected void drawToolTipFollower(Graphics2D g2, int x, int y) {
    Rectangle2D dataArea = getScreenDataArea();
    if (((int) dataArea.getMinX() <= x) && (x <= (int) dataArea.getMaxX()) && ((int) dataArea.getMinY() <= y)
            && (y <= (int) dataArea.getMaxY())) {
        Date date = new Date((long) getChartX());
        String text = "";
        SimpleDateFormat format = new SimpleDateFormat("EEE d MMM HH:mm:ss");
        StringBuffer buffer = new StringBuffer();
        format.format(date, buffer, new FieldPosition(0));
        text = buffer.toString();/*  ww w .j  av  a  2  s.  c o m*/
        text = "(" + text + String.format(", %.2f)", getChartY());
        int xLoc = x + 10;
        int yLoc = y + 20;
        double width = text.length() * 5.5;
        double height = 15;
        if (xLoc + width > dataArea.getMaxX()) {
            xLoc = (int) (x - width);
        }
        if (yLoc + height > dataArea.getMaxY()) {
            yLoc = (int) (y - height);
        }

        Rectangle2D toolTipArea = new Rectangle2D.Double(xLoc, yLoc, width, height);

        g2.setColor(Color.white);
        g2.fill(toolTipArea);
        g2.setColor(Color.black);
        g2.drawString(text, xLoc + 3, yLoc + 11);
    }
}

From source file:com.rapidminer.gui.new_plotter.engine.jfreechart.link_and_brush.LinkAndBrushChartPanel.java

@Override
public void zoom(Rectangle2D selection) {
    // get the origin of the zoom selection in the Java2D space used for
    // drawing the chart (that is, before any scaling to fit the panel)
    Point2D selectOrigin = translateScreenToJava2D(
            new Point((int) Math.ceil(selection.getX()), (int) Math.ceil(selection.getY())));
    PlotRenderingInfo plotInfo = getChartRenderingInfo().getPlotInfo();
    Rectangle2D scaledDataArea = getScreenDataArea((int) selection.getCenterX(), (int) selection.getCenterY());
    if ((selection.getHeight() > 0) && (selection.getWidth() > 0)) {

        double hLower = (selection.getMinX() - scaledDataArea.getMinX()) / scaledDataArea.getWidth();
        double hUpper = (selection.getMaxX() - scaledDataArea.getMinX()) / scaledDataArea.getWidth();
        double vLower = (scaledDataArea.getMaxY() - selection.getMaxY()) / scaledDataArea.getHeight();
        double vUpper = (scaledDataArea.getMaxY() - selection.getMinY()) / scaledDataArea.getHeight();

        Plot p = getChart().getPlot();//from w w  w.ja va  2 s.  co m
        if (p instanceof LinkAndBrushPlot) {

            PlotOrientation orientation = null;
            if (p instanceof XYPlot) {
                XYPlot xyPlot = (XYPlot) p;
                orientation = xyPlot.getOrientation();
            }
            if (p instanceof CategoryPlot) {
                CategoryPlot categoryPlot = (CategoryPlot) p;
                orientation = categoryPlot.getOrientation();
            }

            // here we tweak the notify flag on the plot so that only
            // one notification happens even though we update multiple
            // axes...

            boolean savedNotify = p.isNotify();
            p.setNotify(false);
            LinkAndBrushPlot LABPlot = (LinkAndBrushPlot) p;

            List<Pair<Integer, Range>> zoomedDomainAxisRanges = new LinkedList<Pair<Integer, Range>>();
            List<Pair<Integer, Range>> zoomedRangeAxisRanges = new LinkedList<Pair<Integer, Range>>();

            if (orientation == PlotOrientation.HORIZONTAL) {
                zoomedDomainAxisRanges
                        .addAll(LABPlot.calculateDomainAxesZoom(vLower, vUpper, zoomOnLinkAndBrushSelection));
                zoomedRangeAxisRanges.addAll(LABPlot.calculateRangeAxesZoom(hLower, hUpper, plotInfo,
                        selectOrigin, zoomOnLinkAndBrushSelection));
            } else {
                zoomedDomainAxisRanges
                        .addAll(LABPlot.calculateDomainAxesZoom(hLower, hUpper, zoomOnLinkAndBrushSelection));
                zoomedRangeAxisRanges.addAll(LABPlot.calculateRangeAxesZoom(vLower, vUpper, plotInfo,
                        selectOrigin, zoomOnLinkAndBrushSelection));
            }
            p.setNotify(savedNotify);

            if (zoomOnLinkAndBrushSelection) {
                informLinkAndBrushSelectionListeners(new LinkAndBrushSelection(SelectionType.ZOOM_IN,
                        zoomedDomainAxisRanges, zoomedRangeAxisRanges));
            } else {
                informLinkAndBrushSelectionListeners(new LinkAndBrushSelection(SelectionType.SELECTION,
                        zoomedDomainAxisRanges, zoomedRangeAxisRanges));
            }

        } else {
            super.zoom(selection);
        }
    }
}

From source file:com.rapidminer.gui.plotter.charts.WeightBasedSymbolAxis.java

/**
 * Draws the grid bands for the axis when it is at the top or bottom of the plot.
 * // w ww  .  j av a  2  s .c o  m
 * @param g2
 *            the graphics device.
 * @param plotArea
 *            the area within which the chart should be drawn.
 * @param dataArea
 *            the area within which the plot should be drawn (a subset of the drawArea).
 * @param firstGridBandIsDark
 *            True: the first grid band takes the color of <CODE>gridBandPaint<CODE>.
 *                             False: the second grid band takes the
 *                             color of <CODE>gridBandPaint<CODE>.
 * @param ticks
 *            the ticks.
 */
@Override
protected void drawGridBandsHorizontal(Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea,
        boolean firstGridBandIsDark, List ticks) {
    double yy = dataArea.getY();
    double xx1, xx2;

    // gets the outline stroke width of the plot
    double outlineStrokeWidth;
    if (getPlot().getOutlineStroke() != null) {
        outlineStrokeWidth = ((BasicStroke) getPlot().getOutlineStroke()).getLineWidth();
    } else {
        outlineStrokeWidth = 1d;
    }

    Iterator iterator = ticks.iterator();
    ValueTick tick;
    Rectangle2D band;
    while (iterator.hasNext()) {
        tick = (ValueTick) iterator.next();
        int weightIndex = (int) tick.getValue();
        xx1 = valueToJava2D(tick.getValue() - 0.5d, dataArea, RectangleEdge.BOTTOM);
        xx2 = valueToJava2D(tick.getValue() + 0.5d, dataArea, RectangleEdge.BOTTOM);

        g2.setColor(PlotterAdapter.getWeightColor(this.weights[weightIndex], this.maxWeight));

        band = new Rectangle2D.Double(xx1, yy + outlineStrokeWidth, xx2 - xx1,
                dataArea.getMaxY() - yy - outlineStrokeWidth);
        g2.fill(band);
    }
    g2.setPaintMode();
}

From source file:org.proteosuite.FastScatterPlot.java

/**
 * Draws the fast scatter plot on a Java 2D graphics device (such as the 
 * screen or a printer)./*ww w .java2  s .c  o m*/
 *
 * @param g2  the graphics device.
 * @param area   the area within which the plot (including axis labels)
 *                   should be drawn.
 * @param anchor  the anchor point (<code>null</code> permitted).
 * @param parentState  the state from the parent plot, if there is one.
 * @param info  collects chart drawing information (<code>null</code> 
 *              permitted).
 */
public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState,
        PlotRenderingInfo info) {

    // set up info collection...
    if (info != null) {
        info.setPlotArea(area);
    }

    // adjust the drawing area for plot insets (if any)...
    RectangleInsets insets = getInsets();
    insets.trim(area);

    AxisSpace space = new AxisSpace();
    space = this.domainAxis.reserveSpace(g2, this, area, RectangleEdge.BOTTOM, space);
    space = this.rangeAxis.reserveSpace(g2, this, area, RectangleEdge.LEFT, space);
    Rectangle2D dataArea = space.shrink(area, null);

    if (info != null) {
        info.setDataArea(dataArea);
    }

    // draw the plot background and axes...
    drawBackground(g2, dataArea);

    AxisState domainAxisState = null;
    AxisState rangeAxisState = null;
    if (this.domainAxis != null) {
        domainAxisState = this.domainAxis.draw(g2, dataArea.getMaxY(), area, dataArea, RectangleEdge.BOTTOM,
                info);
    }
    if (this.rangeAxis != null) {
        rangeAxisState = this.rangeAxis.draw(g2, dataArea.getMinX(), area, dataArea, RectangleEdge.LEFT, info);
    }
    drawDomainGridlines(g2, dataArea, domainAxisState.getTicks());
    drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks());

    Shape originalClip = g2.getClip();
    Composite originalComposite = g2.getComposite();

    g2.clip(dataArea);
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha()));

    render(g2, dataArea, info, null);

    g2.setClip(originalClip);
    g2.setComposite(originalComposite);
    drawOutline(g2, dataArea);

}

From source file:it.unibo.alchemist.model.implementations.actions.SocialForceAgent.java

/**
 * Method used to retrieve the obstacle edge nearest to the pedestrian
 * /*from   w  ww .  j  a  v a 2  s  . c  om*/
 * @param myx
 *            - the current pedestrian x-coordinate position
 * @param myy
 *            - the current pedestrian y-coordinate position
 * @param bounds
 *            - the rectangle obstacle bounds
 * @return nearest - an array containing two Continuous2DEuclidean object
 *         representing nearest edge vertices
 */
private Continuous2DEuclidean[] getNearestEdge(final double myx, final double myy, final Rectangle2D bounds) {

    Continuous2DEuclidean[] nearest = null;

    final double minX = bounds.getMinX();
    final double maxX = bounds.getMaxX();
    final double minY = bounds.getMinY();
    final double maxY = bounds.getMaxY();

    if (myx > minX && myx < maxX) {
        if (myy > maxY) { // above the obstacle
            nearest = new Continuous2DEuclidean[] {
                    new Continuous2DEuclidean(bounds.getMinX(), bounds.getMaxY()),
                    new Continuous2DEuclidean(bounds.getMaxX(), bounds.getMaxY()) };
        } else if (myy < minY) { // under the obstacle
            nearest = new Continuous2DEuclidean[] {
                    new Continuous2DEuclidean(bounds.getMinX(), bounds.getMinY()),
                    new Continuous2DEuclidean(bounds.getMaxX(), bounds.getMinY()) };
        }
    } else if (myy > minY && myy < maxY) {
        if (myx < minX) { // to the left the obstacle
            nearest = new Continuous2DEuclidean[] {
                    new Continuous2DEuclidean(bounds.getMinX(), bounds.getMaxY()),
                    new Continuous2DEuclidean(bounds.getMinX(), bounds.getMinY()) };
        } else if (myx > maxX) { // to the right the obstacle
            nearest = new Continuous2DEuclidean[] {
                    new Continuous2DEuclidean(bounds.getMaxX(), bounds.getMaxY()),
                    new Continuous2DEuclidean(bounds.getMaxX(), bounds.getMinY()) };
        }
    }

    return nearest;
}

From source file:com.github.lindenb.jvarkit.tools.misc.BamCmpCoverage.java

@Override
public Collection<Throwable> call() throws Exception {

    if (getOutputFile() == null) {
        return wrapException("output image file not defined");
    }//from ww w  .  j a  v a 2  s  .  c o m

    if (this.imgageSize < 1) {
        return wrapException("Bad image size:" + this.imgageSize);
    }

    if (this.minDepth < 0) {
        return wrapException("Bad min depth : " + this.minDepth);
    }
    if (this.minDepth >= this.maxDepth) {
        return wrapException("Bad min<max depth : " + this.minDepth + "<" + this.maxDepth);
    }

    if (this.getBedFile() != null) {
        readBedFile(this.getBedFile());
    }

    if (regionStr != null && this.intervals != null) {
        return wrapException("bed and interval both defined.");
    }

    final SamRecordFilter filter = new SamRecordFilter() {
        @Override
        public boolean filterOut(SAMRecord first, SAMRecord second) {
            return filterOut(first);
        }

        @Override
        public boolean filterOut(SAMRecord rec) {
            if (rec.getReadUnmappedFlag())
                return true;
            if (rec.isSecondaryOrSupplementary())
                return true;
            if (rec.getDuplicateReadFlag())
                return true;
            if (rec.getNotPrimaryAlignmentFlag())
                return true;
            if (rec.getReadFailsVendorQualityCheckFlag())
                return true;
            if (rec.getMappingQuality() == 0)
                return true;
            /* ignore non-overlapping BED, already checked with QuertInterval 
            if( intervals!=null &&
               ! intervals.containsOverlapping(
               new Interval(rec.getReferenceName(),
             rec.getAlignmentStart(),
             rec.getAlignmentEnd()))
             )
               {
               return true;
               }
               */

            return false;
        }
    };
    Set<File> files = new HashSet<File>();
    try {

        SamReaderFactory srf = SamReaderFactory.makeDefault().validationStringency(ValidationStringency.SILENT);
        srf.disable(SamReaderFactory.Option.EAGERLY_DECODE);
        srf.disable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS);
        srf.disable(SamReaderFactory.Option.VALIDATE_CRC_CHECKSUMS);
        final List<String> args = this.getInputFiles();
        for (String arg : args) {
            File f = new File(arg);
            if (f.getName().endsWith(".list")) {
                LOG.info("Reading BAM list from " + f);
                BufferedReader in = IOUtils.openFileForBufferedReading(f);
                String line;
                while ((line = in.readLine()) != null) {
                    if (line.trim().isEmpty() || line.startsWith("#"))
                        continue;
                    files.add(new File(line));
                }
                in.close();
            } else {
                files.add(f);
            }
        }
        if (files.isEmpty()) {
            return wrapException("No BAM defined");
        }

        Comparator<SAMRecord> comparator = new Comparator<SAMRecord>() {
            @Override
            public int compare(SAMRecord samRecord1, SAMRecord samRecord2) {
                final int refIndex1 = samRecord1.getReferenceIndex();
                final int refIndex2 = samRecord2.getReferenceIndex();
                if (refIndex1 == -1) {
                    return (refIndex2 == -1 ? 0 : 1);
                } else if (refIndex2 == -1) {
                    return -1;
                }
                final int cmp = refIndex1 - refIndex2;
                if (cmp != 0) {
                    return cmp;
                }
                return samRecord1.getAlignmentStart() - samRecord2.getAlignmentStart();
            }
        };
        List<SamReader> readers = new ArrayList<SamReader>(files.size());
        List<CloseableIterator<SAMRecord>> iterators = new ArrayList<CloseableIterator<SAMRecord>>(
                files.size());

        Set<String> samples = new TreeSet<String>();
        SAMSequenceDictionary dict = null;

        /* will be initialized below once, if needed */
        QueryInterval queryIntervalArray[] = null;

        //scan samples names
        for (File bamFile : files) {
            SamReader r = srf.open(bamFile);
            readers.add(r);

            SAMFileHeader h = r.getFileHeader();
            if (h.getSortOrder() != SortOrder.coordinate) {
                r.close();
                return wrapException("file " + bamFile + " not sorted on coordinate");
            }
            if (dict == null) {
                dict = h.getSequenceDictionary();
            } else if (!SequenceUtil.areSequenceDictionariesEqual(dict, h.getSequenceDictionary())) {
                return wrapException("Found more than one dictint sequence dictionary");
            }

            //fill query interval once
            List<QueryInterval> queryIntervals = new ArrayList<>();
            if (regionStr != null && queryIntervalArray == null) {
                int colon = regionStr.indexOf(':');
                String chrom;
                int chromStart;
                int chromEnd;

                if (colon == -1) {
                    chrom = regionStr;
                } else {
                    chrom = regionStr.substring(0, colon);
                }

                SAMSequenceRecord ssr = dict.getSequence(chrom);
                if (ssr == null) {
                    return wrapException("Chromosome " + chrom + " not present in dictionary");
                }
                int hyphen = regionStr.indexOf('-', colon + 1);
                if (hyphen != -1) {
                    chromStart = Integer.parseInt(regionStr.substring(colon + 1, hyphen));
                    chromEnd = Integer.parseInt(regionStr.substring(hyphen + 1));
                } else {
                    chromStart = 0;
                    chromEnd = ssr.getSequenceLength() - 1;
                }
                if (chromStart < 0 || chromEnd < chromStart) {
                    return wrapException("bad position in " + regionStr);
                }

                queryIntervals.add(new QueryInterval(ssr.getSequenceIndex(), chromStart, chromEnd));
            }

            if (this.intervals != null && queryIntervalArray == null) {
                for (Interval interval : this.intervals.keySet()) {
                    SAMSequenceRecord ssr = dict.getSequence(interval.getContig());
                    if (ssr == null) {
                        return wrapException(
                                "Chromosome " + interval.getContig() + " not present in dictionary");
                    }
                    queryIntervals.add(
                            new QueryInterval(ssr.getSequenceIndex(), interval.getStart(), interval.getEnd()));
                }
            }

            if (!queryIntervals.isEmpty() && queryIntervalArray == null) {
                Collections.sort(queryIntervals);
                queryIntervalArray = queryIntervals.toArray(new QueryInterval[queryIntervals.size()]);
            }

            for (SAMReadGroupRecord rg : h.getReadGroups()) {
                String sample = rg.getSample();
                if (sample == null)
                    continue;
                samples.add(sample);
            }
            CloseableIterator<SAMRecord> reciterator = null;
            if (queryIntervalArray == null) {
                reciterator = r.iterator();
            } else {
                reciterator = r.query(queryIntervalArray, false);
            }

            reciterator = new FilteringIterator(reciterator, filter);
            iterators.add(reciterator);
        }
        //free GC
        queryIntervalArray = null;

        LOG.info("Samples:" + samples.size());
        for (String sample : samples) {
            this.sample2column.put(sample, this.sample2column.size());
        }

        //create merging sam-reader
        MergingSamRecordIterator iter = new MergingSamRecordIterator(comparator, iterators);

        //create image
        LOG.info("Creating image " + this.imgageSize + "x" + this.imgageSize);
        this.image = new BufferedImage(this.imgageSize, this.imgageSize, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = this.image.createGraphics();
        this.marginWidth = this.imgageSize * 0.05;
        double drawingWidth = (this.imgageSize - 1) - marginWidth;
        this.sampleWidth = drawingWidth / samples.size();
        //g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, this.imgageSize, this.imgageSize);
        g.setColor(Color.BLACK);
        Hershey hershey = new Hershey();
        for (String sample_x : samples) {
            double labelHeight = marginWidth;
            if (labelHeight > 50)
                labelHeight = 50;

            g.setColor(Color.BLACK);
            hershey.paint(g, sample_x, marginWidth + sample2column.get(sample_x) * sampleWidth,
                    marginWidth - labelHeight, sampleWidth * 0.9, labelHeight * 0.9);

            AffineTransform old = g.getTransform();
            AffineTransform tr = AffineTransform.getTranslateInstance(marginWidth,
                    marginWidth + sample2column.get(sample_x) * sampleWidth);
            tr.rotate(Math.PI / 2);
            g.setTransform(tr);
            hershey.paint(g, sample_x, 0.0, 0.0, sampleWidth * 0.9, labelHeight * 0.9); //g.drawString(this.tabixFile.getFile().getName(),0,0);
            g.setTransform(old);

            for (String sample_y : samples) {

                Rectangle2D rect = new Rectangle2D.Double(
                        marginWidth + sample2column.get(sample_x) * sampleWidth,
                        marginWidth + sample2column.get(sample_y) * sampleWidth, sampleWidth, sampleWidth);
                g.setColor(Color.BLUE);
                g.draw(new Line2D.Double(rect.getMinX(), rect.getMinY(), rect.getMaxX(), rect.getMaxY()));
                g.setColor(Color.BLACK);
                g.draw(rect);
            }
        }

        //ceate bit-array
        BitSampleMatrix bitMatrix = new BitSampleMatrix(samples.size());

        //preivous chrom
        //int prev_tid=-1;
        BufferedList<Depth> depthList = new BufferedList<Depth>();
        g.setColor(Color.BLACK);
        SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(dict);
        LOG.info("Scanning bams...");
        while (iter.hasNext()) {
            SAMRecord rec = iter.next();
            if (filter.filterOut(rec))
                continue;
            progress.watch(rec);

            SAMReadGroupRecord gr = rec.getReadGroup();
            if (gr == null)
                continue;
            String sample = gr.getSample();
            if (sample == null)
                continue;
            int sample_id = this.sample2column.get(sample);

            Cigar cigar = rec.getCigar();
            if (cigar == null)
                continue;
            int refPos = rec.getAlignmentStart();

            /* cleanup front pos */
            while (!depthList.isEmpty()) {
                Depth front = depthList.getFirst();

                if (front.tid != rec.getReferenceIndex().intValue() || front.pos < refPos) {
                    paint(bitMatrix, front);
                    depthList.removeFirst();
                    continue;
                } else {
                    break;
                }
            }

            for (CigarElement ce : cigar.getCigarElements()) {
                CigarOperator op = ce.getOperator();
                if (!op.consumesReferenceBases())
                    continue;
                if (op.consumesReadBases()) {
                    for (int i = 0; i < ce.getLength(); ++i) {
                        Depth depth = null;
                        int pos = refPos + i;

                        //ignore non-overlapping BED
                        if (this.intervals != null && !this.intervals
                                .containsOverlapping(new Interval(rec.getReferenceName(), pos, pos))) {
                            continue;
                        } else if (depthList.isEmpty()) {
                            depth = new Depth();
                            depth.pos = pos;
                            depth.tid = rec.getReferenceIndex();
                            depthList.add(depth);
                        } else if (depthList.getLast().pos < pos) {
                            Depth prev = depthList.getLast();

                            while (prev.pos < pos) {
                                depth = new Depth();
                                depth.pos = prev.pos + 1;
                                depth.tid = rec.getReferenceIndex();
                                depthList.add(depth);
                                prev = depth;
                            }
                            depth = prev;
                        }

                        else {
                            int lastPos = depthList.get(depthList.size() - 1).pos;
                            int distance = lastPos - pos;
                            int indexInList = (depthList.size() - 1) - (distance);
                            if (indexInList < 0) {
                                //can appen when BED declared and partially overlap the read
                                continue;
                            }

                            depth = depthList.get((depthList.size() - 1) - (distance));
                            if (depth.pos != pos) {
                                return wrapException(" " + pos + " vs " + depth.pos + " " + lastPos);
                            }
                        }
                        depth.depths[sample_id]++;
                    }
                }
                refPos += ce.getLength();
            }
        }
        while (!depthList.isEmpty()) {
            //paint(g,depthList.remove(0));
            paint(bitMatrix, depthList.remove(0));
        }
        progress.finish();
        iter.close();

        //paint bitset

        for (int x = 0; x < bitMatrix.n_samples; ++x) {
            for (int y = 0; y < bitMatrix.n_samples; ++y) {
                LOG.info("Painting...(" + x + "/" + y + ")");
                paint(g, bitMatrix.get(x, y));
            }
        }

        g.dispose();
        //close readers
        for (SamReader r : readers)
            r.close();

        //save file
        LOG.info("saving " + getOutputFile());
        if (getOutputFile().getName().toLowerCase().endsWith(".png")) {
            ImageIO.write(this.image, "PNG", getOutputFile());
        } else {
            ImageIO.write(this.image, "JPG", getOutputFile());
        }

        return Collections.emptyList();
    } catch (Exception err) {
        return wrapException(err);
    } finally {

    }
}

From source file:Polygon2D.java

/**
 * Constructs and initializes a <code>Polygon2D</code> from the specified
 * Rectangle2D./*from  w w w.j a  va 2 s.c  o m*/
 * @param rec the Rectangle2D
 * @exception  NullPointerException rec is <code>null</code>.
 */
public Polygon2D(Rectangle2D rec) {
    if (rec == null) {
        throw new IndexOutOfBoundsException("null Rectangle");
    }
    npoints = 4;
    xpoints = new float[4];
    ypoints = new float[4];
    xpoints[0] = (float) rec.getMinX();
    ypoints[0] = (float) rec.getMinY();
    xpoints[1] = (float) rec.getMaxX();
    ypoints[1] = (float) rec.getMinY();
    xpoints[2] = (float) rec.getMaxX();
    ypoints[2] = (float) rec.getMaxY();
    xpoints[3] = (float) rec.getMinX();
    ypoints[3] = (float) rec.getMaxY();
    calculatePath();
}