use of java.awt.Composite in project jvarkit by lindenb.
the class GenScan method doWork.
@Override
public int doWork(final List<String> args) {
if (this.faidxFile == null) {
LOG.error("Reference missing");
return -1;
}
if (this.maxY <= this.minY) {
LOG.error("MaxY <= MinY");
return -1;
}
this.trackNames.stream().flatMap(S -> Arrays.stream(S.split("[ ,;]"))).filter(S -> !S.isEmpty()).collect(Collectors.toSet()).forEach(LABEL -> {
this.name2track.put(LABEL, new Track(LABEL));
});
/* no track specified, add a default one */
if (this.name2track.isEmpty()) {
/**
* define default track
*/
this.defaultTrack = new Track("");
this.name2track.put(this.defaultTrack.label, this.defaultTrack);
}
final DecimalFormat niceIntFormat = new DecimalFormat("###,###");
BufferedReader r = null;
try {
final Rectangle2D.Double drawingRect = new Rectangle2D.Double(this.insets.left, this.insets.top, WIDTH - (this.insets.left + this.insets.right), HEIGHT - (this.insets.top + this.insets.bottom));
final Style styleBase = new Style();
styleBase.update(this.defaultStyleStr);
this.styleStack.add(styleBase);
final double adjustedHeight = drawingRect.getHeight() - this.distanceBetweenContigs * (this.name2track.size() - 1);
double y = drawingRect.y;
for (final Track track : this.name2track.values()) {
track.startY = y;
track.height = (adjustedHeight / this.name2track.size());
y += this.distanceBetweenContigs;
y += track.height;
}
this.dict = SAMSequenceDictionaryExtractor.extractDictionary(this.faidxFile);
for (final String rgnstr : this.regions) {
if (rgnstr.trim().isEmpty())
continue;
final DisplayRange contig;
if (rgnstr.contains(":")) {
contig = new DisplayInterval(rgnstr);
} else {
contig = new DisplayContig(rgnstr);
}
if (contig.length() == 0)
continue;
this.displayRanges.add(contig);
}
if (this.displayRanges.isEmpty()) {
// no region, add whole genome
for (final SAMSequenceRecord ssr : this.dict.getSequences()) {
if (ssr.getSequenceLength() < this.removeContigsSmallerThan) {
LOG.warn("Ignoring " + ssr.getSequenceName() + " because length =" + ssr.getSequenceLength() + " < " + this.removeContigsSmallerThan);
continue;
}
this.displayRanges.add(new DisplayContig(ssr));
}
if (this.displayRanges.isEmpty()) {
LOG.error("No range to display");
return -1;
}
}
// sort on chrom/start
Collections.sort(this.displayRanges, (DR1, DR2) -> {
final int tid1 = dict.getSequenceIndex(DR1.getContig());
final int tid2 = dict.getSequenceIndex(DR2.getContig());
int i = tid1 - tid2;
if (i != 0)
return i;
i = DR1.getStart() - DR2.getStart();
if (i != 0)
return i;
i = DR1.getEnd() - DR2.getEnd();
return i;
});
this.genomeViewLength = this.displayRanges.stream().mapToLong(DR -> DR.length()).sum();
final double adjustedImgWidth = drawingRect.getWidth() - this.distanceBetweenContigs * (this.displayRanges.size() - 1);
if (adjustedImgWidth <= 0) {
LOG.error("with such settings image width would be empty");
return -1;
}
double x = this.insets.left;
for (final DisplayRange displayRange : this.displayRanges) {
displayRange.startX = x;
displayRange.width = (displayRange.length() / (double) genomeViewLength) * adjustedImgWidth;
x += displayRange.width;
x += this.distanceBetweenContigs;
}
final BufferedImage img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
final Graphics2D g = img.createGraphics();
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(ALMOST_WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
// plot background of each contig
for (int rangeIdx = 0; rangeIdx < this.displayRanges.size(); ++rangeIdx) {
final DisplayRange displayRange = this.displayRanges.get(rangeIdx);
int trackidx = 0;
for (final Track track : this.name2track.values()) {
final Rectangle2D rec = new Pane(displayRange, track).getBounds();
g.setColor(rangeIdx % 2 != trackidx % 2 ? ColorUtils.antiquewhite : ColorUtils.navajowhite);
g.fill(rec);
trackidx++;
}
}
final SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(this.dict);
r = super.openBufferedReader(oneFileOrNull(args));
String line;
while ((line = r.readLine()) != null) {
if (line.trim().isEmpty())
continue;
if (line.startsWith("#")) {
if (line.equals("#!push")) {
this.styleStack.push(new Style(this.styleStack.peek()));
} else if (line.equals("#!pop")) {
if (this.styleStack.size() == 1) {
LOG.error("Cannot pop bottom style");
return -1;
}
this.styleStack.pop();
} else if (line.startsWith("#!log")) {
LOG.info(line);
} else if (line.startsWith("#!")) {
this.styleStack.peek().update(line);
}
continue;
}
final Data data = parseData(line);
if (data == null)
continue;
progress.watch(data.getContig(), data.getStart());
if (data.getValue() < GenScan.this.minY) {
continue;
}
if (data.getValue() > GenScan.this.maxY) {
continue;
}
if (data.track == null)
continue;
if (data.style.getAlpha() <= 0f)
continue;
final Style style = data.getStyle();
for (final DisplayRange dr : GenScan.this.displayRanges) {
if (!dr.contains(data))
continue;
final Pane panel = new Pane(dr, data.track);
final Rectangle2D.Double bounds = panel.getBounds();
final Point2D.Double point = panel.convertToPoint(data);
final Shape oldClip = g.getClip();
final Composite oldComposite = g.getComposite();
g.setClip(bounds);
//
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, style.getAlpha()));
final Shape dataShape;
final double shape_size = style.getSize();
switch(style.getShapeType()) {
case circle:
dataShape = new Ellipse2D.Double(point.x - shape_size / 2.0, point.y - shape_size / 2.0, shape_size, shape_size);
break;
case square:
dataShape = new Rectangle2D.Double(point.x - shape_size / 2.0, point.y - shape_size / 2.0, shape_size, shape_size);
break;
default:
throw new IllegalArgumentException();
}
if (style.getPaperColor() != null) {
g.setColor(style.getPaperColor());
g.fill(dataShape);
}
final float stroke_width = style.getStrokeWidth();
if (style.getPenColor() != null && stroke_width > 0) {
final Stroke oldStroke = g.getStroke();
final Stroke stroke = new BasicStroke(stroke_width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND);
g.setStroke(stroke);
g.setColor(style.getPenColor());
g.draw(dataShape);
g.setStroke(oldStroke);
}
//
g.setClip(oldClip);
g.setComposite(oldComposite);
}
}
progress.finish();
double lastTickX = 0.0;
// plot frame of each contig
for (final DisplayRange displayRange : this.displayRanges) {
for (final Track track : this.name2track.values()) {
final Rectangle2D rec = new Pane(displayRange, track).getBounds();
g.setColor(ALMOST_BLACK);
g.draw(rec);
}
final String label = displayRange.getLabel();
int fontSize = insets.top - 2;
final double labelLength = Math.min(label.length() * fontSize, displayRange.width);
if (labelLength > this.distanceBetweenContigs) {
g.setColor(ALMOST_BLACK);
this.hershey.paint(g, label, new Rectangle2D.Double(displayRange.startX + displayRange.width / 2.0 - labelLength / 2.0, 1, labelLength, (insets.top - 2)));
}
// plot ticks
for (int i = 0; i <= 10; i++) {
double bp = displayRange.getStart() + (displayRange.length() / 10.0) * i;
double tx = displayRange.convertToX(bp);
double ty = drawingRect.getMaxY();
g.setColor(ALMOST_BLACK);
g.draw(new Line2D.Double(tx, ty, tx, ty + 5));
if (tx - lastTickX > 5) {
g.translate(tx, ty + 5);
g.rotate(Math.PI / 2.0);
g.drawString(niceIntFormat.format((long) bp), 0, 0);
g.rotate(-Math.PI / 2.0);
g.translate(-tx, -(ty + 5));
lastTickX = tx + 5;
}
}
}
// plot y axis
for (final Track track : this.name2track.values()) {
for (int i = 0; i <= 10; ++i) {
double v = this.minY + ((this.maxY - this.minY) / 10.0) * i;
double ty = track.convertToY(v);
double font_size = 12;
// horizontal line
g.setColor(Color.LIGHT_GRAY);
g.draw(new Line2D.Double(drawingRect.getX() - 5, ty, drawingRect.getMaxX(), ty));
g.setColor(ALMOST_BLACK);
this.hershey.paint(g, String.format("%8s", v), new Rectangle2D.Double(0, ty - font_size, insets.left, font_size));
}
// plot track label if no default track
if (this.defaultTrack == null) {
g.setColor(ALMOST_BLACK);
g.translate(WIDTH - insets.right + 2, track.startY);
g.rotate(Math.PI / 2.0);
g.drawString(track.label, 0, 0);
g.rotate(-Math.PI / 2.0);
g.translate(-(WIDTH - insets.right + 2), -(track.startY));
}
}
g.dispose();
r.close();
r = null;
if (this.outputFile == null) {
ImageIO.write(img, "PNG", stdout());
} else {
ImageIO.write(img, this.outputFile.getName().toLowerCase().endsWith(".png") ? "PNG" : "JPG", this.outputFile);
}
return 0;
} catch (Exception e) {
LOG.error(e);
return -1;
} finally {
CloserUtil.close(r);
this.dict = null;
}
}
use of java.awt.Composite in project jvarkit by lindenb.
the class CoverageServer method writeKnownCnv.
private void writeKnownCnv(final Graphics2D g, final Locatable region) {
if (this.knownCnvFile == null)
return;
final IntToDoubleFunction position2pixel = X -> ((X - region.getStart()) / (double) region.getLengthOnReference()) * (double) image_width;
final Composite oldComposite = g.getComposite();
final Stroke oldStroke = g.getStroke();
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f));
g.setColor(Color.MAGENTA);
final double y = image_height - 8.0;
try {
this.getKnownCnv(region).forEach(R -> {
final double x1 = position2pixel.applyAsDouble(R.getStart());
final double x2 = position2pixel.applyAsDouble(R.getEnd());
g.draw(new Rectangle2D.Double(x1, y - 1, Math.max(1.0, x2 - x1), 3));
});
} catch (Throwable err) {
} finally {
g.setComposite(oldComposite);
g.setStroke(oldStroke);
}
}
use of java.awt.Composite in project jvarkit by lindenb.
the class CoverageServer method printImage.
private void printImage(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException {
int bam_id;
try {
bam_id = Integer.parseInt(StringUtils.ifBlank(request.getParameter("id"), "-1"));
} catch (Exception err) {
bam_id = -1;
}
final SimpleInterval midRegion = parseInterval(request.getParameter("interval"));
if (midRegion == null || bam_id < 0 || bam_id >= this.bamInput.size()) {
response.reset();
response.sendError(HttpStatus.BAD_REQUEST_400, "id:" + bam_id);
response.flushBuffer();
return;
}
final int extend = (int) (midRegion.getLengthOnReference() * this.extend_factor);
int xstart = Math.max(midRegion.getStart() - extend, 0);
int xend = midRegion.getEnd() + extend;
final SAMSequenceRecord ssr = this.dictionary.getSequence(midRegion.getContig());
if (ssr != null) {
xend = Math.min(xend, ssr.getSequenceLength());
}
final SimpleInterval region = new SimpleInterval(midRegion.getContig(), xstart, xend);
if (region.getLengthOnReference() > this.max_window_size) {
response.reset();
response.sendError(HttpStatus.BAD_REQUEST_400, "contig:" + midRegion);
response.flushBuffer();
return;
}
final Counter<Arc> sashimiArcs = new Counter<>();
final BamInput bam = this.bamInput.get(bam_id);
if (region.length() <= this.small_region_size) {
printRaster(bam, midRegion, region, request, response);
return;
}
final boolean normalize = request.getParameter("normalize") != null;
final SamReaderFactory srf = SamReaderFactory.make().validationStringency(ValidationStringency.LENIENT).referenceSequence(this.faidxRef);
try (SamReader sr = srf.open(bam.bamPath)) {
final int[] int_coverage = new int[region.getLengthOnReference()];
Arrays.fill(int_coverage, 0);
try (CloseableIterator<SAMRecord> iter = sr.query(region.getContig(), region.getStart(), region.getEnd(), false)) {
while (iter.hasNext()) {
final SAMRecord rec = iter.next();
if (!acceptRead(rec))
continue;
final Cigar cigar = rec.getCigar();
if (cigar == null || cigar.isEmpty())
continue;
int ref = rec.getAlignmentStart();
for (final CigarElement ce : cigar) {
final CigarOperator op = ce.getOperator();
if (op.consumesReferenceBases()) {
if (this.enable_sashimi && op.equals(CigarOperator.N)) {
sashimiArcs.incr(new Arc(ref, ref + ce.getLength()));
}
if (op.consumesReadBases()) {
for (int x = 0; x < ce.getLength(); ++x) {
int pos = ref + x;
if (pos < region.getStart())
continue;
if (pos > region.getEnd())
break;
int_coverage[pos - region.getStart()]++;
}
}
ref += ce.getLength();
}
}
}
}
/* smooth coverage */
if (int_coverage.length > image_width) {
final int[] copy = Arrays.copyOf(int_coverage, int_coverage.length);
final int len = Math.max(1, int_coverage.length / 100);
for (int i = 0; i < int_coverage.length; i++) {
int j = Math.max(0, i - len);
double sum = 0;
int count = 0;
while (j < i + len && j < copy.length) {
sum += copy[j];
j++;
count++;
}
int_coverage[i] = (int) (sum / count);
}
}
final double[] norm_coverage = new double[int_coverage.length];
final double median;
/* normalize on median */
if (normalize) {
final Coverage leftrightcov = new Coverage(extend * 2);
for (int x = region.getStart(); x < midRegion.getStart(); x++) {
final int idx = x - region.getStart();
leftrightcov.add(int_coverage[idx]);
}
for (int x = midRegion.getEnd() + 1; x <= region.getEnd(); x++) {
final int idx = x - region.getStart();
leftrightcov.add(int_coverage[idx]);
}
median = Math.max(1.0, leftrightcov.median());
// LOG.info("median is "+median+" "+leftrightcov.median());
for (int x = 0; x < int_coverage.length; ++x) {
norm_coverage[x] = int_coverage[x] / median;
}
} else /* no normalisation */
{
/* won't be used */
median = Double.NaN;
for (int x = 0; x < int_coverage.length; ++x) {
norm_coverage[x] = int_coverage[x];
}
}
final double real_max_cov = DoubleStream.of(norm_coverage).max().orElse(1.0);
final double max_cov = Math.max((normalize ? 2 : 10), real_max_cov);
final double pixelperbase = image_width / (double) norm_coverage.length;
final IntFunction<Double> pos2pixel = POS -> ((POS - region.getStart()) / (double) region.getLengthOnReference()) * image_width;
final BufferedImage img = new BufferedImage(image_width, image_height, BufferedImage.TYPE_INT_RGB);
final Graphics2D g = img.createGraphics();
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setColor(Color.WHITE);
g.fillRect(0, 0, image_width + 1, image_height + 1);
for (int x = 0; x < norm_coverage.length; ++x) {
final double height = image_height * (norm_coverage[x] / max_cov);
if (normalize)
g.setColor(Color.DARK_GRAY);
else if (max_cov < 10)
g.setColor(Color.RED);
else if (max_cov < 20)
g.setColor(Color.BLUE);
else
g.setColor(Color.DARK_GRAY);
g.fill(new Rectangle2D.Double(x * pixelperbase, image_height - height, pixelperbase, height));
}
g.setColor(Color.DARK_GRAY);
g.drawString("max-cov:" + IntStream.of(int_coverage).max().orElse(0) + (normalize ? " normalized on median (" + median + ")" : "") + " sample:" + bam.sample + " " + region.toNiceString(), 10, 10);
/* ticks for vertical axis */
g.setColor(Color.MAGENTA);
for (int i = 1; i < 10; i++) {
double cov = max_cov / 10.0 * i;
if (!normalize)
cov = Math.ceil(cov);
final double y = image_height - image_height / 10.0 * i;
if (!normalize && i > 0 && (int) cov == Math.ceil(max_cov / 10.0 * (i - 1)))
continue;
g.drawLine(0, (int) y, 5, (int) y);
g.drawString(normalize ? String.format("%.2f", cov) : String.valueOf((int) cov), 7, (int) y);
}
/* vertical line for original view */
g.setColor(Color.PINK);
double vertical = ((midRegion.getStart() - region.getStart()) / (double) region.getLengthOnReference()) * image_width;
g.draw(new Line2D.Double(vertical, 0, vertical, image_height));
vertical = ((midRegion.getEnd() - region.getStart()) / (double) region.getLengthOnReference()) * image_width;
g.draw(new Line2D.Double(vertical, 0, vertical, image_height));
if (normalize) {
/* horizontal line for median 0.5 / 1 / 1.5 */
for (int t = 1; t < 4; ++t) {
g.setColor(t == 2 ? Color.ORANGE : Color.PINK);
final double mediany = image_height - ((0.5 * t) / max_cov) * image_height;
g.draw(new Line2D.Double(0, mediany, image_width, mediany));
}
}
if (this.enable_sashimi && !sashimiArcs.isEmpty()) {
final double max_count = sashimiArcs.getMaxCount().orElse(1L);
g.setColor(Color.GREEN);
for (final Arc arc : sashimiArcs.keySet()) {
final double x1 = pos2pixel.apply(arc.start);
final double x2 = pos2pixel.apply(arc.end);
final double distance = x2 - x1;
final GeneralPath curve = new GeneralPath();
curve.moveTo(x1, image_height);
curve.curveTo(x1, image_height, x1 + distance / 2.0, image_height - Math.min(distance, image_height * 0.75), x2, image_height);
final double weight = (sashimiArcs.count(arc) / max_count) * 5;
final Stroke oldStroke = g.getStroke();
final Composite oldComposite = g.getComposite();
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
g.setStroke(new BasicStroke((float) weight, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.draw(curve);
g.setStroke(oldStroke);
g.setComposite(oldComposite);
}
}
writeGenes(g, region);
writeKnownCnv(g, region);
g.setColor(Color.GRAY);
g.drawRect(0, 0, img.getWidth(), img.getHeight());
writeImage(img, bam, region, response);
}
}
use of java.awt.Composite in project Portugol-Studio by UNIVALI-LITE.
the class DesenhoImagem method desenhar.
@Override
public void desenhar(Graphics2D graficos) {
if (opacidade == 255) {
graficos.drawImage(imagem, x, y, null);
} else {
Composite original = graficos.getComposite();
Composite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, nivelTransparencia);
graficos.setComposite(alpha);
graficos.drawImage(imagem, x, y, null);
graficos.setComposite(original);
}
}
use of java.awt.Composite in project LoboEvolution by LoboEvolution.
the class SVGSVGElementImpl method draw.
/**
* {@inheritDoc}
*/
@Override
public void draw(final Graphics2D graphics) {
recalculateViewboxToViewportTransform();
boolean display = getDisplay();
float opacity = getOpacity();
if (display && opacity > 0) {
AffineTransform oldGraphicsTransform = graphics.getTransform();
Shape oldClip = graphics.getClip();
graphics.translate(viewport.getX(), viewport.getY());
if (opacity < 1) {
SVGSVGElement root = this;
float currentScale = root.getCurrentScale();
// create buffer to draw on
Shape shape = createShape(null);
AffineTransform screenCTM = getScreenCTM().getAffineTransform();
Shape transformedShape = screenCTM.createTransformedShape(shape);
Rectangle2D bounds = transformedShape.getBounds2D();
double xInc = bounds.getWidth() / 5;
double yInc = bounds.getHeight() / 5;
bounds.setRect(bounds.getX() - xInc, bounds.getY() - yInc, bounds.getWidth() + 2 * xInc, bounds.getHeight() + 2 * yInc);
int imageWidth = (int) (bounds.getWidth() * currentScale);
int imageHeight = (int) (bounds.getHeight() * currentScale);
if (imageWidth > 0 && imageHeight > 0) {
BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D offGraphics = (Graphics2D) image.getGraphics();
RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
offGraphics.setRenderingHints(hints);
if (currentScale != 1) {
offGraphics.scale(currentScale, currentScale);
}
offGraphics.translate(-bounds.getX(), -bounds.getY());
offGraphics.transform(screenCTM);
drawChildren(offGraphics);
Composite oldComposite = graphics.getComposite();
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity);
graphics.setComposite(ac);
AffineTransform imageTransform = AffineTransform.getTranslateInstance(bounds.getX(), bounds.getY());
imageTransform.scale(1 / currentScale, 1 / currentScale);
try {
imageTransform.preConcatenate(screenCTM.createInverse());
} catch (NoninvertibleTransformException e) {
}
graphics.drawImage(image, imageTransform, null);
graphics.setComposite(oldComposite);
image.flush();
}
} else {
drawChildren(graphics);
}
graphics.setTransform(oldGraphicsTransform);
graphics.setClip(oldClip);
}
}
Aggregations