Example usage for java.awt.geom Rectangle2D getMaxX

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

Introduction

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

Prototype

public double getMaxX() 

Source Link

Document

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

Usage

From source file:org.csa.rstb.dat.toolviews.HaAlphaPlotPanel.java

@Override
protected String getDataAsText() {
    final BufferedImage image = plot.getImage();
    final Rectangle2D bounds = plot.getImageDataBounds();

    final byte[] data = getValidData(image);
    if (data == null) {
        return null;
    }/*www  . j  a  v  a  2s  .c o m*/

    final StringBuilder sb = new StringBuilder(64000);
    final int w = image.getWidth();
    final int h = image.getHeight();

    final RasterDataNode rasterX = getRaster(X_VAR);
    final String nameX = rasterX.getName();
    final double sampleMinX = bounds.getMinX();
    final double sampleMaxX = bounds.getMaxX();

    final RasterDataNode rasterY = getRaster(Y_VAR);
    final String nameY = rasterY.getName();
    final double sampleMinY = bounds.getMinY();
    final double sampleMaxY = bounds.getMaxY();

    sb.append("Product name:\t").append(rasterX.getProduct().getName()).append("\n");
    sb.append("Dataset X name:\t").append(nameX).append("\n");
    sb.append("Dataset Y name:\t").append(nameY).append("\n");
    sb.append('\n');
    sb.append(nameX).append(" minimum:\t").append(sampleMinX).append("\t").append(rasterX.getUnit())
            .append("\n");
    sb.append(nameX).append(" maximum:\t").append(sampleMaxX).append("\t").append(rasterX.getUnit())
            .append("\n");
    sb.append(nameX).append(" bin size:\t").append((sampleMaxX - sampleMinX) / w).append("\t")
            .append(rasterX.getUnit()).append("\n");
    sb.append(nameX).append(" #bins:\t").append(w).append("\n");
    sb.append('\n');
    sb.append(nameY).append(" minimum:\t").append(sampleMinY).append("\t").append(rasterY.getUnit())
            .append("\n");
    sb.append(nameY).append(" maximum:\t").append(sampleMaxY).append("\t").append(rasterY.getUnit())
            .append("\n");
    sb.append(nameY).append(" bin size:\t").append((sampleMaxY - sampleMinY) / h).append("\t")
            .append(rasterY.getUnit()).append("\n");
    sb.append(nameY).append(" #bins:\t").append(h).append("\n");
    sb.append('\n');

    sb.append(nameX);
    sb.append('\t');
    sb.append(nameY);
    sb.append('\t');
    sb.append("Bin counts\t(cropped at 255)");
    sb.append('\n');

    int x, y, z;
    double v1, v2;
    for (int i = 0; i < data.length; i++) {
        z = data[i] & 0xff;
        if (z != 0) {

            x = i % w;
            y = h - i / w - 1;

            v1 = sampleMinX + ((x + 0.5) * (sampleMaxX - sampleMinX)) / w;
            v2 = sampleMinY + ((y + 0.5) * (sampleMaxY - sampleMinY)) / h;

            sb.append(v1);
            sb.append('\t');
            sb.append(v2);
            sb.append('\t');
            sb.append(z);
            sb.append('\n');
        }
    }

    return sb.toString();
}

From source file:Polygon2D.java

/**
 * Constructs and initializes a <code>Polygon2D</code> from the specified
 * Rectangle2D./*w w w .j a v a  2s. co 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();
}

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

/**
 * Method used to retrieve the obstacle edge nearest to the pedestrian
 * //from www .  j a va2s  .  c o m
 * @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.rapidminer.gui.plotter.charts.WeightBasedSymbolAxis.java

/**
 * Draws the grid bands for the axis when it is at the top or bottom of the plot.
 * //from w  w w  . j  a  v  a 2s .com
 * @param g2
 *            the graphics device.
 * @param drawArea
 *            the area within which the chart should be drawn.
 * @param plotArea
 *            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
 *            a list of ticks.
 */
@Override
protected void drawGridBandsVertical(Graphics2D g2, Rectangle2D drawArea, Rectangle2D plotArea,
        boolean firstGridBandIsDark, List ticks) {
    double xx = plotArea.getX();
    double yy1, yy2;

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

    Iterator iterator = ticks.iterator();
    ValueTick tick;
    Rectangle2D band;
    while (iterator.hasNext()) {
        tick = (ValueTick) iterator.next();
        int weightIndex = (int) tick.getValue();
        yy1 = valueToJava2D(tick.getValue() + 0.5d, plotArea, RectangleEdge.LEFT);
        yy2 = valueToJava2D(tick.getValue() - 0.5d, plotArea, RectangleEdge.LEFT);

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

        band = new Rectangle2D.Double(xx + outlineStrokeWidth, yy1,
                plotArea.getMaxX() - xx - outlineStrokeWidth, yy2 - yy1);
        g2.fill(band);
    }
    g2.setPaintMode();
}

From source file:com.controlj.addon.gwttree.server.OpaqueBarRenderer3D.java

/**<!====== drawItem ======================================================>
   Draws a 3D bar to represent one data item.
   <!      Name       Description>
   @param  g2         the graphics device.
   @param  state      the renderer state.
   @param  dataArea   the area for plotting the data.
   @param  plot       the plot.//from  w  ww .j a v  a 2 s  .c om
   @param  domainAxis the domain axis.
   @param  rangeAxis  the range axis.
   @param  dataset    the dataset.
   @param  row        the row index (zero-based).
   @param  column     the column index (zero-based).
   @param  pass       the pass index.
<!=======================================================================>*/
@Override
public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot,
        CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) {

    // check the value we are plotting...
    Number dataValue = dataset.getValue(row, column);
    if (dataValue == null) {
        return;
    }

    g2.setStroke(new BasicStroke(1));
    double value = dataValue.doubleValue();

    Rectangle2D adjusted = new Rectangle2D.Double(dataArea.getX(), dataArea.getY() + getYOffset(),
            dataArea.getWidth() - getXOffset(), dataArea.getHeight() - getYOffset());

    PlotOrientation orientation = plot.getOrientation();

    double barW0 = calculateBarW0(plot, orientation, adjusted, domainAxis, state, row, column);
    double[] barL0L1 = calculateBarL0L1(value);
    if (barL0L1 == null) {
        return; // the bar is not visible
    }

    RectangleEdge edge = plot.getRangeAxisEdge();
    double transL0 = rangeAxis.valueToJava2D(barL0L1[0], adjusted, edge);
    double transL1 = rangeAxis.valueToJava2D(barL0L1[1], adjusted, edge);
    double barL0 = Math.min(transL0, transL1);
    double barLength = Math.abs(transL1 - transL0);

    // draw the bar...
    Rectangle2D bar = null;
    if (orientation == PlotOrientation.HORIZONTAL) {
        bar = new Rectangle2D.Double(barL0, barW0, barLength, state.getBarWidth());
    } else {
        bar = new Rectangle2D.Double(barW0, barL0, state.getBarWidth(), barLength);
    }
    Paint itemPaint = getItemPaint(row, column);
    if (itemPaint instanceof Color) {
        Color endColor = getFrontDark((Color) itemPaint);
        Color startColor = (Color) itemPaint;
        Paint paint = new GradientPaint((float) bar.getX(), (float) bar.getY(), startColor,
                (float) (bar.getX()), (float) (bar.getY() + bar.getHeight()), endColor);
        g2.setPaint(paint);
    }
    g2.fill(bar);

    double x0 = bar.getMinX(); // left
    double x1 = x0 + getXOffset(); // offset left
    double x2 = bar.getMaxX(); // right
    double x3 = x2 + getXOffset(); // offset right

    double y0 = bar.getMinY() - getYOffset(); // offset top
    double y1 = bar.getMinY(); // bar top
    double y2 = bar.getMaxY() - getYOffset(); // offset bottom
    double y3 = bar.getMaxY(); // bottom

    //Rectangle2D.Double line = new Rectangle2D.Double(x2, y1, 2, bar.getHeight());

    Line2D.Double line = new Line2D.Double(x2, y1, x2, y3);
    g2.draw(line);

    GeneralPath bar3dRight = null;
    GeneralPath bar3dTop = null;
    g2.setPaint(itemPaint);

    // Draw the right side
    if (barLength > 0.0) {
        bar3dRight = new GeneralPath();
        bar3dRight.moveTo((float) x2, (float) y3);
        bar3dRight.lineTo((float) x2, (float) y1);
        bar3dRight.lineTo((float) x3, (float) y0);
        bar3dRight.lineTo((float) x3, (float) y2);
        bar3dRight.closePath();

        if (itemPaint instanceof Color) {
            Color startColor = getSideLight((Color) itemPaint);
            Color endColor = getSideDark((Color) itemPaint);
            Paint paint = new GradientPaint((float) x3, (float) y0, startColor, (float) x2, (float) y3,
                    endColor);
            g2.setPaint(paint);
        }
        g2.fill(bar3dRight);
    }

    // Draw the top
    bar3dTop = new GeneralPath();
    bar3dTop.moveTo((float) x0, (float) y1); // bottom left
    bar3dTop.lineTo((float) x1, (float) y0); // top left
    bar3dTop.lineTo((float) x3, (float) y0); // top right
    bar3dTop.lineTo((float) x2, (float) y1); // bottom right
    bar3dTop.closePath();
    if (itemPaint instanceof Color) {
        Color endColor = getTopDark((Color) itemPaint);
        Color startColor = getTopLight((Color) itemPaint);
        //Paint paint = new GradientPaint((float)x2, (float)y0, startColor, (float)x0, (float)(y1), endColor);
        Point2D.Double topRight = new Point2D.Double(x3, y0);
        Point2D.Double bottomLeft = new Point2D.Double(x0, y1);
        //Point2D.Double darkEnd = getTargetPoint(bottomLeft, topRight, ((y0-y1)/(x3-x2)));
        Point2D.Double darkEnd = new Point2D.Double(x1, y0 - (x3 - x1) * ((y0 - y1) / (x3 - x2)));
        Paint paint = new GradientPaint((float) topRight.getX(), (float) topRight.getY(), startColor,
                (float) darkEnd.getX(), (float) darkEnd.getY(), endColor);
        g2.setPaint(paint);
        //drawMarker(topRight, g2, startColor);
    }
    g2.fill(bar3dTop);
    g2.setPaint(itemPaint);

    if (isDrawBarOutline() && state.getBarWidth() > BAR_OUTLINE_WIDTH_THRESHOLD) {
        g2.setStroke(getItemOutlineStroke(row, column));
        g2.setPaint(getItemOutlinePaint(row, column));
        g2.draw(bar);
        if (bar3dRight != null) {
            g2.draw(bar3dRight);
        }
        if (bar3dTop != null) {
            g2.draw(bar3dTop);
        }
    }

    CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column);
    if (generator != null && isItemLabelVisible(row, column)) {
        drawItemLabel(g2, dataset, row, column, plot, generator, bar, (value < 0.0));
    }

    // add an item entity, if this information is being collected
    EntityCollection entities = state.getEntityCollection();
    if (entities != null) {
        GeneralPath barOutline = new GeneralPath();
        barOutline.moveTo((float) x0, (float) y3);
        barOutline.lineTo((float) x0, (float) y1);
        barOutline.lineTo((float) x1, (float) y0);
        barOutline.lineTo((float) x3, (float) y0);
        barOutline.lineTo((float) x3, (float) y2);
        barOutline.lineTo((float) x2, (float) y3);
        barOutline.closePath();
        addItemEntity(entities, dataset, row, column, barOutline);
    }

}

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  w  ww . 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:org.esa.snap.rcp.statistics.DensityPlotPanel.java

@Override
protected String getDataAsText() {
    final BufferedImage image = plot.getImage();
    final Rectangle2D bounds = plot.getImageDataBounds();

    final byte[] data = getValidData(image);
    if (data == null) {
        return null;
    }/*from ww w .  ja va2 s .  c  o m*/

    final StringBuilder sb = new StringBuilder(64000);
    final int w = image.getWidth();
    final int h = image.getHeight();

    final RasterDataNode rasterX = getRaster(X_VAR);
    assert rasterX != null;
    final String nameX = rasterX.getName();
    final double sampleMinX = bounds.getMinX();
    final double sampleMaxX = bounds.getMaxX();

    final RasterDataNode rasterY = getRaster(Y_VAR);
    assert rasterY != null;
    final String nameY = rasterY.getName();
    final double sampleMinY = bounds.getMinY();
    final double sampleMaxY = bounds.getMaxY();

    sb.append("Product name:\t").append(rasterX.getProduct().getName()).append("\n");
    sb.append("Dataset X name:\t").append(nameX).append("\n");
    sb.append("Dataset Y name:\t").append(nameY).append("\n");
    sb.append('\n');
    sb.append(nameX).append(" minimum:\t").append(sampleMinX).append("\t").append(rasterX.getUnit())
            .append("\n");
    sb.append(nameX).append(" maximum:\t").append(sampleMaxX).append("\t").append(rasterX.getUnit())
            .append("\n");
    sb.append(nameX).append(" bin size:\t").append((sampleMaxX - sampleMinX) / w).append("\t")
            .append(rasterX.getUnit()).append("\n");
    sb.append(nameX).append(" #bins:\t").append(w).append("\n");
    sb.append('\n');
    sb.append(nameY).append(" minimum:\t").append(sampleMinY).append("\t").append(rasterY.getUnit())
            .append("\n");
    sb.append(nameY).append(" maximum:\t").append(sampleMaxY).append("\t").append(rasterY.getUnit())
            .append("\n");
    sb.append(nameY).append(" bin size:\t").append((sampleMaxY - sampleMinY) / h).append("\t")
            .append(rasterY.getUnit()).append("\n");
    sb.append(nameY).append(" #bins:\t").append(h).append("\n");
    sb.append('\n');

    sb.append(nameX);
    sb.append('\t');
    sb.append(nameY);
    sb.append('\t');
    sb.append("Bin counts\t(cropped at 255)");
    sb.append('\n');

    int x, y, z;
    double v1, v2;
    for (int i = 0; i < data.length; i++) {
        z = data[i] & 0xff;
        if (z != 0) {

            x = i % w;
            y = h - i / w - 1;

            v1 = sampleMinX + ((x + 0.5) * (sampleMaxX - sampleMinX)) / w;
            v2 = sampleMinY + ((y + 0.5) * (sampleMaxY - sampleMinY)) / h;

            sb.append(v1);
            sb.append('\t');
            sb.append(v2);
            sb.append('\t');
            sb.append(z);
            sb.append('\n');
        }
    }

    return sb.toString();
}

From source file:org.kalypso.ogc.sensor.diagview.jfreechart.ObservationPlot.java

/**
 * Draw alarmlevels (horizontal line and text annotation)
 *///from   w  w  w.j a  v  a  2 s. c  o m
private void drawAlarmLevels(final Graphics2D g2, final Rectangle2D dataArea) {
    for (final Object element : m_yConsts.keySet()) {
        final AlarmLevelPlotElement vac = m_yConsts.get(element);

        final ValueAxis axis = m_diag2chartAxis.get(vac.getAxis());
        if (axis == null)
            continue;

        if (axis.getRange().contains(vac.getAlarm().value)) {
            final double yy = axis.valueToJava2D(vac.getAlarm().value, dataArea, RectangleEdge.LEFT);
            final Line2D line = new Line2D.Double(dataArea.getMinX(), yy, dataArea.getMaxX(), yy);
            // always set stroke, else we got the stroke from the last drawn line
            g2.setStroke(AlarmLevelPlotElement.STROKE_ALARM);
            g2.setPaint(vac.getAlarm().color);
            g2.draw(line);

            // and draw the text annotation: if annotation is outside (on top); label it below the line
            if (yy < dataArea.getMinY() + 20)
                vac.getAnnotation().setAngle(Math.toRadians(20));
            else
                vac.getAnnotation().setAngle(Math.toRadians(340));

            vac.getAnnotation().draw(g2, this, dataArea, getDomainAxis(), axis);
        }
    }
}

From source file:org.eurocarbdb.application.glycoworkbench.plugin.PeakListChartPanel.java

public void mouseReleased(MouseEvent e) {
    if (MouseUtils.isPopupTrigger(e)) {
        // clear all
        if (zoom_rectangle != null) {
            Graphics2D g2 = (Graphics2D) getGraphics();
            g2.setXORMode(java.awt.Color.gray);
            g2.draw(zoom_rectangle);/*from w w  w . ja  va2 s  . c o  m*/
            g2.dispose();
        }
        mouse_start_point = null;
        zoom_rectangle = null;

        // open popup
        current_peak = findPeakAt(e.getPoint());
        enforceSelection(current_peak);
        createPopupMenu(current_peak != null).show(theChartPanel, e.getX(), e.getY());
    } else {
        if (zoom_rectangle != null && mouse_start_point != null) {
            if (Math.abs(e.getX() - mouse_start_point.getX()) > 10) {
                //if( e.getX() < mouse_start_point.getX() ) {
                // unzoom all
                //    onZoomNone();
                //}
                //else {        

                // zoom area           
                double start_x = Math.min(e.getX(), mouse_start_point.getX());
                double end_x = Math.max(e.getX(), mouse_start_point.getX());

                Rectangle2D data_area = theChartPanel.getScreenDataArea((int) start_x,
                        (int) mouse_start_point.getY());
                double new_lower_bound = screenToDataCoordX(start_x);
                double new_upper_bound = screenToDataCoordX(Math.min(end_x, data_area.getMaxX()));
                thePlot.getDomainAxis().setRange(new Range(new_lower_bound, new_upper_bound));
            } else {
                // clear rectangle
                Graphics2D g2 = (Graphics2D) getGraphics();
                g2.setXORMode(java.awt.Color.gray);
                g2.draw(zoom_rectangle);
                g2.dispose();
            }
        }

        // restore zooming
        if (!was_moving && is_moving)
            onActivateZooming();

        zoom_rectangle = null;
        mouse_start_point = null;
    }
}

From source file:org.logisticPlanning.utils.graphics.chart.impl.jfree._JFCXYItemRenderer.java

/** {@inheritDoc} */
@Override/*from ww w. ja  va  2 s  .c  om*/
public final XYItemRendererState initialise(final Graphics2D arg0, final Rectangle2D arg1, final XYPlot arg2,
        final XYDataset arg3, final PlotRenderingInfo arg4) {
    final double x1, y1, x2, y2;
    // AffineTransform t;

    if (arg1 != null) {

        x1 = arg1.getMinX();
        x2 = arg1.getMaxX();
        y1 = arg1.getMinY();
        y2 = arg1.getMaxY();

        this.m_minX = Math.min(this.m_minX, Math.min(x1, x2));
        this.m_maxX = Math.max(this.m_maxX, Math.max(x1, x2));

        this.m_minY = Math.min(this.m_minY, Math.min(y1, y2));
        this.m_maxY = Math.max(this.m_maxY, Math.max(y1, y2));

        //

        // this.m_src[0] = x1;
        // this.m_src[1] = y1;
        // this.m_src[2] = x2;
        // this.m_src[3] = y1;
        // this.m_src[4] = x2;
        // this.m_src[5] = y2;
        // this.m_src[6] = x1;
        // this.m_src[7] = y2;
        //
        // t = arg0.getTransform();
        // if ((t != null) && (!(t.isIdentity()))) {
        // t.transform(this.m_src, 0, this.m_dst, 0, 4);
        // } else {
        // System.arraycopy(this.m_src, 0, this.m_dst, 0, 8);
        // }
        //
        // this.m_maxX = Math.min(this.m_maxX, Math.max(//
        // Math.max(this.m_dst[0], this.m_dst[2]),//
        // Math.max(this.m_dst[4], this.m_dst[6])));
        //
        // this.m_maxY = Math.min(this.m_maxY, Math.max(//
        // Math.max(this.m_dst[1], this.m_dst[3]),//
        // Math.max(this.m_dst[5], this.m_dst[7])));
        //
        // this.m_minX = Math.max(this.m_minX, Math.min(//
        // Math.min(this.m_dst[0], this.m_dst[2]),//
        // Math.min(this.m_dst[4], this.m_dst[6])));
        //
        // this.m_minY = Math.max(this.m_minY, Math.min(//
        // Math.min(this.m_dst[1], this.m_dst[3]),//
        // Math.min(this.m_dst[5], this.m_dst[7])));
    }

    return this.m_out.initialise(arg0, arg1, arg2, arg3, arg4);
}