From ea370961523a52432d117634e6d923b3f29de04e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20=C4=8Cert=C3=ADk?= Date: Sat, 15 Aug 2026 15:15:00 -0600 Subject: [PATCH 1/2] Say what test_plots actually wrote Each case saved an SVG, a PDF and a PNG and then announced only the SVG, so the log read as though two thirds of the work had not happened. The line was wrong in the same way 43 times over, which is the more useful thing the report exposed: the four lines that end every case were copied out by hand, and the three savefig calls could disagree with each other or with the message without anything noticing. They are one call to a local helper now, and the options are forwarded rather than repeated, so an absent optional stays absent and a plain case still says nothing about facecolor or dpi. The file is a hundred lines shorter and each case ends with the name it is saved under. --- tests/test_plots.f90 | 236 ++++++++++++------------------------------- 1 file changed, 64 insertions(+), 172 deletions(-) diff --git a/tests/test_plots.f90 b/tests/test_plots.f90 index 9bd7a40..a94edc7 100644 --- a/tests/test_plots.f90 +++ b/tests/test_plots.f90 @@ -59,10 +59,7 @@ program test_plots call legend() call xlim(0.0_dp, 2.0_dp * pi) call ylim(-1.2_dp, 1.2_dp) - call savefig("tests/out/basic_line.svg") - call savefig("tests/out/basic_line.pdf") - call savefig("tests/out/basic_line.png") - print *, "wrote tests/out/basic_line.svg" + call save_all("basic_line") ! 2) multi_style call clf() @@ -76,10 +73,7 @@ program test_plots call legend() call xlim(0.0_dp, 2.0_dp * pi) call ylim(-1.5_dp, 1.5_dp) - call savefig("tests/out/multi_style.svg") - call savefig("tests/out/multi_style.pdf") - call savefig("tests/out/multi_style.png") - print *, "wrote tests/out/multi_style.svg" + call save_all("multi_style") ! 3) markers_only call clf() @@ -92,10 +86,7 @@ program test_plots call legend() call xlim(0.0_dp, 2.0_dp * pi) call ylim(-1.5_dp, 1.5_dp) - call savefig("tests/out/markers_only.svg") - call savefig("tests/out/markers_only.pdf") - call savefig("tests/out/markers_only.png") - print *, "wrote tests/out/markers_only.svg" + call save_all("markers_only") ! 4) semilogx call clf() @@ -107,10 +98,7 @@ program test_plots call legend() call xlim(0.1_dp, 10.0_dp) call ylim(0.0_dp, 120.0_dp) - call savefig("tests/out/semilogx.svg") - call savefig("tests/out/semilogx.pdf") - call savefig("tests/out/semilogx.png") - print *, "wrote tests/out/semilogx.svg" + call save_all("semilogx") ! 5) semilogy call clf() @@ -122,10 +110,7 @@ program test_plots call legend() call xlim(0.1_dp, 10.0_dp) call ylim(1.0e-4_dp, 20.0_dp) - call savefig("tests/out/semilogy.svg") - call savefig("tests/out/semilogy.pdf") - call savefig("tests/out/semilogy.png") - print *, "wrote tests/out/semilogy.svg" + call save_all("semilogy") ! 6) loglog call clf() @@ -137,10 +122,7 @@ program test_plots call legend() call xlim(0.1_dp, 10.0_dp) call ylim(0.01_dp, 100.0_dp) - call savefig("tests/out/loglog.svg") - call savefig("tests/out/loglog.pdf") - call savefig("tests/out/loglog.png") - print *, "wrote tests/out/loglog.svg" + call save_all("loglog") ! 7) subplots_2x1 (two rows, one column; exercises subplot(m,n,i), ! per-axes state, and suptitle) @@ -162,10 +144,7 @@ program test_plots call legend() call suptitle("fplot subplots") - call savefig("tests/out/subplots_2x1.svg") - call savefig("tests/out/subplots_2x1.pdf") - call savefig("tests/out/subplots_2x1.png") - print *, "wrote tests/out/subplots_2x1.svg" + call save_all("subplots_2x1") ! 8) subplots_2x2 (four panels; also checks per-axes log scale) call clf() @@ -190,10 +169,7 @@ program test_plots call grid(.true.) call suptitle("fplot 2x2 subplots") - call savefig("tests/out/subplots_2x2.svg") - call savefig("tests/out/subplots_2x2.pdf") - call savefig("tests/out/subplots_2x2.png") - print *, "wrote tests/out/subplots_2x2.svg" + call save_all("subplots_2x2") ! 9) markers gallery (one row per marker code) call clf() @@ -208,10 +184,7 @@ program test_plots call title("Markers") call xlim(0.0_dp, real(mk + 1, dp)) call ylim(0.0_dp, real(n_marks + 1, dp)) - call savefig("tests/out/markers_gallery.svg") - call savefig("tests/out/markers_gallery.pdf") - call savefig("tests/out/markers_gallery.png") - print *, "wrote tests/out/markers_gallery.svg" + call save_all("markers_gallery") ! 10) scatter call clf() @@ -225,10 +198,7 @@ program test_plots call ylabel("y") call grid(.true.) call legend() - call savefig("tests/out/scatter.svg") - call savefig("tests/out/scatter.pdf") - call savefig("tests/out/scatter.png") - print *, "wrote tests/out/scatter.svg" + call save_all("scatter") ! 11) bar call clf() @@ -237,10 +207,7 @@ program test_plots call xlabel("category") call ylabel("value") call legend() - call savefig("tests/out/bar.svg") - call savefig("tests/out/bar.pdf") - call savefig("tests/out/bar.png") - print *, "wrote tests/out/bar.svg" + call save_all("bar") ! 12) hist call clf() @@ -249,10 +216,7 @@ program test_plots call xlabel("value") call ylabel("count") call legend() - call savefig("tests/out/hist.svg") - call savefig("tests/out/hist.pdf") - call savefig("tests/out/hist.png") - print *, "wrote tests/out/hist.svg" + call save_all("hist") ! 13) fill_between call clf() @@ -263,10 +227,7 @@ program test_plots call ylabel("y") call grid(.true.) call legend() - call savefig("tests/out/fill_between.svg") - call savefig("tests/out/fill_between.pdf") - call savefig("tests/out/fill_between.png") - print *, "wrote tests/out/fill_between.svg" + call save_all("fill_between") ! 14) errorbar call clf() @@ -281,10 +242,7 @@ program test_plots call ylabel("y") call grid(.true.) call legend() - call savefig("tests/out/errorbar.svg") - call savefig("tests/out/errorbar.pdf") - call savefig("tests/out/errorbar.png") - print *, "wrote tests/out/errorbar.svg" + call save_all("errorbar") ! 15) hv_lines call clf() @@ -296,10 +254,7 @@ program test_plots call ylabel("y") call grid(.true.) call legend() - call savefig("tests/out/hv_lines.svg") - call savefig("tests/out/hv_lines.pdf") - call savefig("tests/out/hv_lines.png") - print *, "wrote tests/out/hv_lines.svg" + call save_all("hv_lines") ! 16) text and annotate call clf() @@ -310,10 +265,7 @@ program test_plots call xlabel("x") call ylabel("y") call grid(.true.) - call savefig("tests/out/text_annotate.svg") - call savefig("tests/out/text_annotate.pdf") - call savefig("tests/out/text_annotate.png") - print *, "wrote tests/out/text_annotate.svg" + call save_all("text_annotate") ! 17) custom ticks, minor ticks and legend placement call clf() @@ -327,10 +279,7 @@ program test_plots call title("Ticks and legend placement") call xlabel("x") call ylabel("y") - call savefig("tests/out/ticks_legend.svg") - call savefig("tests/out/ticks_legend.pdf") - call savefig("tests/out/ticks_legend.png") - print *, "wrote tests/out/ticks_legend.svg" + call save_all("ticks_legend") ! 18) a non-default figure size call figure(figsize=[8.0_dp, 3.0_dp]) @@ -340,10 +289,7 @@ program test_plots call ylabel("y") call grid(.true.) call legend() - call savefig("tests/out/figsize.svg") - call savefig("tests/out/figsize.pdf") - call savefig("tests/out/figsize.png") - print *, "wrote tests/out/figsize.svg" + call save_all("figsize") ! 19) more series than the old fixed 32-slot cap. ! figure(), not clf(), because clf() keeps the previous canvas size. @@ -354,10 +300,7 @@ program test_plots call title("Forty series") call xlabel("x") call ylabel("y") - call savefig("tests/out/many_series.svg") - call savefig("tests/out/many_series.pdf") - call savefig("tests/out/many_series.png") - print *, "wrote tests/out/many_series.svg" + call save_all("many_series") ! 20) alpha on lines and markers call figure() @@ -368,10 +311,7 @@ program test_plots call xlabel("x") call ylabel("y") call legend() - call savefig("tests/out/alpha.svg") - call savefig("tests/out/alpha.pdf") - call savefig("tests/out/alpha.png") - print *, "wrote tests/out/alpha.svg" + call save_all("alpha") ! 21) a non-default figure facecolor call figure() @@ -380,10 +320,7 @@ program test_plots call xlabel("x") call ylabel("y") call grid(.true.) - call savefig("tests/out/facecolor.svg", facecolor="#eeeeee") - call savefig("tests/out/facecolor.pdf", facecolor="#eeeeee") - call savefig("tests/out/facecolor.png", facecolor="#eeeeee") - print *, "wrote tests/out/facecolor.svg" + call save_all("facecolor", facecolor="#eeeeee") do i = 1, nzr do j = 1, nzc @@ -400,10 +337,7 @@ program test_plots call figure() call imshow(zimg) call title("imshow") - call savefig("tests/out/imshow.svg") - call savefig("tests/out/imshow.pdf") - call savefig("tests/out/imshow.png") - print *, "wrote tests/out/imshow.svg" + call save_all("imshow") ! 23) imshow with an extent, lower origin and a colorbar call figure() @@ -413,10 +347,7 @@ program test_plots call title("imshow with colorbar") call xlabel("x") call ylabel("y") - call savefig("tests/out/imshow_cbar.svg") - call savefig("tests/out/imshow_cbar.pdf") - call savefig("tests/out/imshow_cbar.png") - print *, "wrote tests/out/imshow_cbar.svg" + call save_all("imshow_cbar") ! 24) scatter with per-point sizes and color-mapped values call figure() @@ -425,10 +356,7 @@ program test_plots call title("Scatter with c and s arrays") call xlabel("x") call ylabel("y") - call savefig("tests/out/scatter_cmap.svg") - call savefig("tests/out/scatter_cmap.pdf") - call savefig("tests/out/scatter_cmap.png") - print *, "wrote tests/out/scatter_cmap.svg" + call save_all("scatter_cmap") ! 25) contour lines call figure() @@ -436,10 +364,7 @@ program test_plots call title("contour") call xlabel("x") call ylabel("y") - call savefig("tests/out/contour.svg") - call savefig("tests/out/contour.pdf") - call savefig("tests/out/contour.png") - print *, "wrote tests/out/contour.svg" + call save_all("contour") ! 26) filled contours with a colorbar call figure() @@ -448,46 +373,31 @@ program test_plots call title("contourf") call xlabel("x") call ylabel("y") - call savefig("tests/out/contourf.svg") - call savefig("tests/out/contourf.pdf") - call savefig("tests/out/contourf.png") - print *, "wrote tests/out/contourf.svg" + call save_all("contourf") ! 27) step call figure() call step(xb, hb, where="mid") call title("step") - call savefig("tests/out/step.svg") - call savefig("tests/out/step.pdf") - call savefig("tests/out/step.png") - print *, "wrote tests/out/step.svg" + call save_all("step") ! 28) stem call figure() call stem(xb, hb) call title("stem") - call savefig("tests/out/stem.svg") - call savefig("tests/out/stem.pdf") - call savefig("tests/out/stem.png") - print *, "wrote tests/out/stem.svg" + call save_all("stem") ! 29) barh call figure() call barh(xb, hb) call title("barh") - call savefig("tests/out/barh.svg") - call savefig("tests/out/barh.pdf") - call savefig("tests/out/barh.png") - print *, "wrote tests/out/barh.svg" + call save_all("barh") ! 30) pie call figure() call pie(hb, labels=["a", "b", "c", "d", "e", "f"]) call title("pie") - call savefig("tests/out/pie.svg") - call savefig("tests/out/pie.pdf") - call savefig("tests/out/pie.png") - print *, "wrote tests/out/pie.svg" + call save_all("pie") do i = 1, nd dist1(i) = sin(real(i, dp)) + 0.3_dp * cos(2.7_dp * real(i, dp)) @@ -499,20 +409,14 @@ program test_plots call boxplot(dist1) call boxplot(dist2) call title("boxplot") - call savefig("tests/out/boxplot.svg") - call savefig("tests/out/boxplot.pdf") - call savefig("tests/out/boxplot.png") - print *, "wrote tests/out/boxplot.svg" + call save_all("boxplot") ! 32) violinplot call figure() call violinplot(dist1) call violinplot(dist2) call title("violinplot") - call savefig("tests/out/violinplot.svg") - call savefig("tests/out/violinplot.pdf") - call savefig("tests/out/violinplot.png") - print *, "wrote tests/out/violinplot.svg" + call save_all("violinplot") do i = 1, nsym xsym(i) = -100.0_dp + real(i - 1, dp) @@ -523,20 +427,14 @@ program test_plots call plot(xsym, xsym) call set_yscale("symlog") call title("symlog") - call savefig("tests/out/symlog.svg") - call savefig("tests/out/symlog.pdf") - call savefig("tests/out/symlog.png") - print *, "wrote tests/out/symlog.svg" + call save_all("symlog") ! 34) axis("equal") call figure() call plot(xb, hb, marker="o") call axis("equal") call title("axis equal") - call savefig("tests/out/axis_equal.svg") - call savefig("tests/out/axis_equal.pdf") - call savefig("tests/out/axis_equal.png") - print *, "wrote tests/out/axis_equal.svg" + call save_all("axis_equal") ! 35) tick styling and hidden spines call figure() @@ -545,10 +443,7 @@ program test_plots call tick_params(axis="x", rotation=45.0_dp) call spines(top=.false., right=.false.) call title("tick_params") - call savefig("tests/out/tick_style.svg") - call savefig("tests/out/tick_style.pdf") - call savefig("tests/out/tick_style.png") - print *, "wrote tests/out/tick_style.svg" + call save_all("tick_style") ! 36) tight_layout with long tick labels call figure() @@ -560,10 +455,7 @@ program test_plots call plot(xb, hb) call xlabel("category") call tight_layout() - call savefig("tests/out/tight_layout.svg") - call savefig("tests/out/tight_layout.pdf") - call savefig("tests/out/tight_layout.png") - print *, "wrote tests/out/tight_layout.svg" + call save_all("tight_layout") ! 37) subplots_adjust call figure() @@ -572,10 +464,7 @@ program test_plots call subplot(2, 1, 2) call plot(xb, hb) call subplots_adjust(left=0.2_dp, hspace=0.5_dp) - call savefig("tests/out/subplots_adjust.svg") - call savefig("tests/out/subplots_adjust.pdf") - call savefig("tests/out/subplots_adjust.png") - print *, "wrote tests/out/subplots_adjust.svg" + call save_all("subplots_adjust") ! 38) twinx call figure() @@ -586,10 +475,7 @@ program test_plots call plot(xb, hb * 100.0_dp) call ylabel("right") call title("twinx") - call savefig("tests/out/twinx.svg") - call savefig("tests/out/twinx.pdf") - call savefig("tests/out/twinx.png") - print *, "wrote tests/out/twinx.svg" + call save_all("twinx") ! 39) color spellings call figure() @@ -605,10 +491,7 @@ program test_plots end select end do call title("color names") - call savefig("tests/out/colors.svg") - call savefig("tests/out/colors.pdf") - call savefig("tests/out/colors.png") - print *, "wrote tests/out/colors.svg" + call save_all("colors") ! 40) font sizes call figure() @@ -618,10 +501,7 @@ program test_plots call ylabel("y axis", fontsize=14.0_dp) call tick_params(labelsize=13.0_dp) call legend(fontsize=12.0_dp) - call savefig("tests/out/fontsize.svg") - call savefig("tests/out/fontsize.pdf") - call savefig("tests/out/fontsize.png") - print *, "wrote tests/out/fontsize.svg" + call save_all("fontsize") ! 41) legend options call figure() @@ -630,10 +510,7 @@ program test_plots call plot(xb, hb * 0.25_dp, label="gamma") call plot(xb, hb * 0.125_dp, label="delta") call legend(loc="upper right", ncol=2, title="series", frameon=.false.) - call savefig("tests/out/legend_opts.svg") - call savefig("tests/out/legend_opts.pdf") - call savefig("tests/out/legend_opts.png") - print *, "wrote tests/out/legend_opts.svg" + call save_all("legend_opts") ! 42) savefig(bbox_inches="tight") call figure() @@ -641,10 +518,7 @@ program test_plots call title("tight") call xlabel("x") call ylabel("y") - call savefig("tests/out/savefig_tight.svg", bbox_inches="tight", dpi=200.0_dp) - call savefig("tests/out/savefig_tight.pdf", bbox_inches="tight", dpi=200.0_dp) - call savefig("tests/out/savefig_tight.png", bbox_inches="tight", dpi=200.0_dp) - print *, "wrote tests/out/savefig_tight.svg" + call save_all("savefig_tight", bbox_inches="tight", dpi=200.0_dp) ! 43) two live figures kept apart, then closed call figure() @@ -656,11 +530,29 @@ program test_plots call title("figure two") call close() call figure(num=fig1) - call savefig("tests/out/figures.svg") - call savefig("tests/out/figures.pdf") - call savefig("tests/out/figures.png") - print *, "wrote tests/out/figures.svg" + call save_all("figures") call close(all=.true.) print *, "All test plots written." + +contains + + ! Every case is written in all three formats, so the three savefig calls + ! and the line that reports them are stated once here rather than once + ! per case. The options are passed straight through: an absent optional + ! stays absent, so a plain case says nothing about facecolor or dpi. + subroutine save_all(stem, facecolor, bbox_inches, dpi) + character(len=*), intent(in) :: stem + character(len=*), intent(in), optional :: facecolor, bbox_inches + real(dp), intent(in), optional :: dpi + + call savefig("tests/out/"//stem//".svg", facecolor=facecolor, & + bbox_inches=bbox_inches, dpi=dpi) + call savefig("tests/out/"//stem//".pdf", facecolor=facecolor, & + bbox_inches=bbox_inches, dpi=dpi) + call savefig("tests/out/"//stem//".png", facecolor=facecolor, & + bbox_inches=bbox_inches, dpi=dpi) + print *, "wrote tests/out/"//stem//".svg, .pdf and .png" + end subroutine save_all + end program test_plots From c5fd1a2f5a68e4fed35dea6d6034c580a06fef97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20=C4=8Cert=C3=ADk?= Date: Sat, 15 Aug 2026 15:15:14 -0600 Subject: [PATCH 2/2] Send an image to the backend as an image imshow was drawing one rectangle per sample. That was written when SVG was the only backend and the API had no way to say "raster", and it stayed after draw_image was added, so draw_image had no callers and two of its three implementations were empty. The cost is per sample: an 8x16 image is 128 elements, and a 200x200 image would be 40000. Every format can place a raster in one object, so the whole image is now one draw_image call. SVG embeds a PNG in a data URI, which is what matplotlib does, and PDF writes an image XObject with the samples as a FlateDecode stream, sharing the compressor the PNG backend already has. On the small images in the test suite that is 12049 bytes of SVG down to 6532 and 14433 of PDF down to 4828; the ratio grows with the image. The raster is sent at roughly the size it is drawn rather than at data resolution. This is not a detail: a renderer asked to enlarge a 16x8 image will usually interpolate it, and at these sizes interpolation turns data into a blur. Repeating each sample a whole number of times is exactly nearest neighbour, so it invents nothing, and it took the imshow case rendered through cairosvg from 5.3 to 1.6 against matplotlib. image-rendering is set as well, for renderers that honour it. A blit assumes the samples are evenly spaced on the canvas, which stops being true the moment an axis is log, so the per-cell path stays for that case. It was about to become code nothing reached, so there is now a log-axis imshow case in the suite; it lands at 1.4 against matplotlib, which also warps the image rather than stretching it. The three backends agree on where the image goes and which way up it is, which is worth stating because it is the easy thing to get wrong: PDF draws an image into the unit square with the first row at the top, under a page matrix that has already flipped y, and fplot's own rows run up the extent, with origin="upper" expressed as a descending axis rather than as reversed data. Checked by comparing each backend against a vertically flipped reference: every one of them is ~1.5 the right way up and ~23 upside down. --- scripts/build_flang.sh | 2 +- scripts/build_lfortran.sh | 2 +- src/fplot.f90 | 88 +++++++++++++++++++++++++++-- src/fplot_backend_pdf.f90 | 113 ++++++++++++++++++++++++++++++++++++-- src/fplot_backend_svg.f90 | 64 ++++++++++++++++++++- src/fplot_png.f90 | 21 ++++++- tests/gen_mpl_refs.py | 8 +++ tests/test_plots.f90 | 8 +++ 8 files changed, 292 insertions(+), 14 deletions(-) diff --git a/scripts/build_flang.sh b/scripts/build_flang.sh index 399b303..2eb538a 100755 --- a/scripts/build_flang.sh +++ b/scripts/build_flang.sh @@ -22,9 +22,9 @@ $FLANG -c "$ROOT/src/fplot_cmap.f90" $FLANG -c "$ROOT/src/fplot_ticks.f90" $FLANG -c "$ROOT/src/fplot_contour.f90" $FLANG -c "$ROOT/src/fplot_svg.f90" +$FLANG -c "$ROOT/src/fplot_png.f90" $FLANG -c "$ROOT/src/fplot_backend_svg.f90" $FLANG -c "$ROOT/src/fplot_glyphs.f90" -$FLANG -c "$ROOT/src/fplot_png.f90" $FLANG -c "$ROOT/src/fplot_raster.f90" $FLANG -c "$ROOT/src/fplot_backend_pdf.f90" $FLANG -c "$ROOT/src/fplot_backend_png.f90" diff --git a/scripts/build_lfortran.sh b/scripts/build_lfortran.sh index 72fc696..e7fca9f 100755 --- a/scripts/build_lfortran.sh +++ b/scripts/build_lfortran.sh @@ -19,9 +19,9 @@ $LFORTRAN -c "$ROOT/src/fplot_cmap.f90" $LFORTRAN -c "$ROOT/src/fplot_ticks.f90" $LFORTRAN -c "$ROOT/src/fplot_contour.f90" $LFORTRAN -c "$ROOT/src/fplot_svg.f90" +$LFORTRAN -c "$ROOT/src/fplot_png.f90" $LFORTRAN -c "$ROOT/src/fplot_backend_svg.f90" $LFORTRAN -c "$ROOT/src/fplot_glyphs.f90" -$LFORTRAN -c "$ROOT/src/fplot_png.f90" $LFORTRAN -c "$ROOT/src/fplot_raster.f90" $LFORTRAN -c "$ROOT/src/fplot_backend_pdf.f90" $LFORTRAN -c "$ROOT/src/fplot_backend_png.f90" diff --git a/src/fplot.f90 b/src/fplot.f90 index f24761d..1bbd676 100644 --- a/src/fplot.f90 +++ b/src/fplot.f90 @@ -2955,10 +2955,89 @@ pure subroutine cell_triangle(z, i, j, gx, gy, tri, tx, ty, tv) end if end subroutine cell_triangle - ! One per sample. SVG has no raster primitive we can reach without - ! embedding an encoded image, and nearest-neighbour cells are what - ! matplotlib's default interpolation looks like at these sizes anyway. + ! An image is one draw_image call. Every format has a way to place a + ! raster, and using it costs one object in the file where a rectangle per + ! sample costs nr*nc: a 200x200 image is 40000 elements the other way. + ! + ! A blit assumes the samples are evenly spaced on the canvas, which is + ! true only while both axes are linear, so a log axis keeps the per-cell + ! path below. subroutine append_image(b, a, xmin, xmax, ymin, ymax, ax_l, ax_w, ax_b, ax_h, xsc, ysc) + class(renderer_t), intent(inout) :: b + type(axes_t), intent(in) :: a + real(dp), intent(in) :: xmin, xmax, ymin, ymax, ax_l, ax_w, ax_b, ax_h + type(scale_t), intent(in) :: xsc, ysc + integer :: nr, nc, i, j, si, sj, fx, fy + integer, allocatable :: rgba(:, :, :) + real(dp) :: px0, px1, py0, py1, t + type(paint_t) :: p + logical :: flip_x, flip_y + + if (xsc%kind /= SCALE_LINEAR .or. ysc%kind /= SCALE_LINEAR) then + call append_image_cells(b, a, xmin, xmax, ymin, ymax, & + ax_l, ax_w, ax_b, ax_h, xsc, ysc) + return + end if + + nr = size(a%img, 1) + nc = size(a%img, 2) + px0 = map_x(a%img_ext(1), xmin, xmax, ax_l, ax_w, xsc) + px1 = map_x(a%img_ext(2), xmin, xmax, ax_l, ax_w, xsc) + py0 = map_y(a%img_ext(3), ymin, ymax, ax_b, ax_h, ysc) + py1 = map_y(a%img_ext(4), ymin, ymax, ax_b, ax_h, ysc) + + ! draw_image wants its rows from the top of the canvas down, and the + ! image's own rows run up the extent, so whichever end of the extent + ! lands at the top decides where row 1 goes. This is how origin= + ! "upper" reaches the file: it descends the y axis, which is what + ! puts the first row at the top. + flip_x = px1 < px0 + flip_y = py0 > py1 + + ! The raster is sent at roughly the size it will be drawn, which is + ! what matplotlib does and for the same reason: a backend or a viewer + ! asked to enlarge a 16x12 image will often interpolate it, and these + ! images are small enough that interpolating turns the data into a + ! blur. Repeating each sample a whole number of times is exactly + ! nearest neighbour, so no value is invented by doing it. + fx = fill_factor(abs(px1 - px0), nc) + fy = fill_factor(abs(py1 - py0), nr) + + allocate (rgba(4, nc*fx, nr*fy)) + do i = 1, nr*fy + si = (i - 1)/fy + 1 + if (flip_y) si = nr - si + 1 + do j = 1, nc*fx + sj = (j - 1)/fx + 1 + if (flip_x) sj = nc - sj + 1 + t = (a%img(si, sj) - a%img_vmin) / (a%img_vmax - a%img_vmin) + rgba(1:3, j, i) = hex_rgb(cmap_color(a%img_cmap, t)) + rgba(4, j, i) = 255 + end do + end do + + p%clip = g_clip + call b%draw_image(min(px0, px1), min(py0, py1), abs(px1 - px0), & + abs(py1 - py0), rgba, nc*fx, nr*fy, p) + end subroutine append_image + + ! How many times to repeat each sample so the raster covers the space it + ! is drawn in, bounded so that a large image is left as it is rather than + ! grown into something the file has to carry. + pure function fill_factor(extent, n) result(f) + real(dp), intent(in) :: extent + integer, intent(in) :: n + integer :: f + integer, parameter :: MAX_SAMPLES = 2048 + + f = max(1, ceiling(extent/real(max(n, 1), dp))) + f = min(f, max(1, MAX_SAMPLES/max(n, 1))) + end function fill_factor + + ! One rectangle per sample. Correct whatever the axes do to the spacing, + ! and so the answer when a scale is not linear and a blit would put the + ! samples in the wrong places. + subroutine append_image_cells(b, a, xmin, xmax, ymin, ymax, ax_l, ax_w, ax_b, ax_h, xsc, ysc) class(renderer_t), intent(inout) :: b type(axes_t), intent(in) :: a real(dp), intent(in) :: xmin, xmax, ymin, ymax, ax_l, ax_w, ax_b, ax_h @@ -2987,10 +3066,11 @@ subroutine append_image(b, a, xmin, xmax, ymin, ymax, ax_l, ax_w, ax_b, ax_h, xs cmap_color(a%img_cmap, t)) end do end do - end subroutine append_image + end subroutine append_image_cells ! Cells are grown by a hairline so that neighbours overlap; without it the ! renderer leaves visible seams between abutting rectangles. + ! renderer leaves visible seams between abutting rectangles. subroutine append_cell(b, x, y, w, h, color) class(renderer_t), intent(inout) :: b real(dp), intent(in) :: x, y, w, h diff --git a/src/fplot_backend_pdf.f90 b/src/fplot_backend_pdf.f90 index 0a681fe..494e285 100644 --- a/src/fplot_backend_pdf.f90 +++ b/src/fplot_backend_pdf.f90 @@ -29,6 +29,7 @@ module fplot_backend_pdf use fplot_render use fplot_svg, only: svg_builder, builder_init, builder_append, & builder_get, fmt_num + use fplot_png, only: zlib_compress implicit none private @@ -36,6 +37,18 @@ module fplot_backend_pdf integer, parameter :: MAX_OBJ = 64 integer, parameter :: MAX_ALPHA = 64 + integer, parameter :: MAX_IMG = 16 + + ! An image already compressed and ready to become an XObject. The samples + ! are kept as the deflated stream rather than as pixels because that is + ! the only form the file wants them in. + type :: pdf_image_t + integer :: w = 0, h = 0 + character(len=:), allocatable :: rgb + ! Empty unless some sample is transparent, since a fully opaque + ! image needs no soft mask. + character(len=:), allocatable :: alpha + end type pdf_image_t type, extends(renderer_t) :: pdf_renderer_t ! The page content stream. The file itself is assembled in @@ -50,6 +63,8 @@ module fplot_backend_pdf real(dp) :: alpha_stroke(MAX_ALPHA) = 1.0_dp logical :: clip_open = .false. type(clip_t) :: cur_clip + integer :: n_img = 0 + type(pdf_image_t) :: img(MAX_IMG) contains procedure :: open_canvas => pdf_open_canvas procedure :: close_canvas => pdf_close_canvas @@ -247,6 +262,7 @@ subroutine pdf_open_canvas(self, width, height, bg_rgb, bg_alpha, x0, y0) if (present(x0)) self%x0 = x0 if (present(y0)) self%y0 = y0 self%n_alpha = 0 + self%n_img = 0 call builder_init(self%c) ! One matrix for the whole page turns the API's top-left origin with @@ -411,14 +427,56 @@ subroutine pdf_draw_text(self, x, y, s, font, paint, anchor, baseline, angle) call put(self, "Q"//new_line("a")) end subroutine pdf_draw_text - ! imshow currently reaches every backend as a grid of rectangles, so no - ! figure fplot can draw needs this yet. + ! The image itself is registered for later; what goes in the content + ! stream is a matrix and one Do. PDF draws an image into the unit square + ! with the first row at the top of it, so the matrix that lands it on the + ! API's rectangle is a flip: v = 1 is the top edge, and the page is + ! already flipped underneath. subroutine pdf_draw_image(self, x, y, w, h, rgba, nx, ny, paint) class(pdf_renderer_t), intent(inout) :: self real(dp), intent(in) :: x, y, w, h integer, intent(in) :: nx, ny integer, intent(in) :: rgba(4, nx, ny) type(paint_t), intent(in) :: paint + integer, allocatable :: rgb(:), a(:) + integer :: i, j, k, id + logical :: opaque + + if (nx < 1 .or. ny < 1 .or. self%n_img >= MAX_IMG) return + + allocate (rgb(3*nx*ny), a(nx*ny)) + k = 0 + opaque = .true. + do j = 1, ny + do i = 1, nx + rgb(3*k + 1:3*k + 3) = rgba(1:3, i, j) + a(k + 1) = rgba(4, i, j) + if (rgba(4, i, j) < 255) opaque = .false. + k = k + 1 + end do + end do + + self%n_img = self%n_img + 1 + id = self%n_img + self%img(id)%w = nx + self%img(id)%h = ny + self%img(id)%rgb = zlib_compress(rgb) + if (opaque) then + self%img(id)%alpha = "" + else + self%img(id)%alpha = zlib_compress(a) + end if + + call begin_paint(self, paint) + call put_num(self, w) + call put_num(self, 0.0_dp) + call put_num(self, 0.0_dp) + call put_num(self, -h) + call put_num(self, x) + call put_num(self, y + h) + call put(self, "cm"//new_line("a")) + call put(self, "/Im"//int_str(id)//" Do"//new_line("a")) + call put(self, "Q"//new_line("a")) end subroutine pdf_draw_image ! Assemble the file. Objects have to be byte-counted as they are written @@ -426,8 +484,9 @@ end subroutine pdf_draw_image subroutine pdf_close_canvas(self) class(pdf_renderer_t), intent(inout) :: self type(svg_builder) :: f - character(len=:), allocatable :: content, res, gs + character(len=:), allocatable :: content, res, gs, xo integer :: off(MAX_OBJ), nobj, i, pos, xref_pos + integer :: img_obj(MAX_IMG), mask_obj(MAX_IMG) character(len=1) :: eol eol = new_line("a") @@ -440,13 +499,29 @@ subroutine pdf_close_canvas(self) //num_str(self%alpha_fill(i))//" /CA " & //num_str(self%alpha_stroke(i))//" >> " end do + + ! Images follow the five fixed objects, one object each and a second + ! for a soft mask where one is needed. + nobj = 5 + xo = "" + do i = 1, self%n_img + nobj = nobj + 1 + img_obj(i) = nobj + mask_obj(i) = 0 + if (len(self%img(i)%alpha) > 0) then + nobj = nobj + 1 + mask_obj(i) = nobj + end if + xo = xo//"/Im"//int_str(i)//" "//int_str(img_obj(i))//" 0 R " + end do + res = "<< /Font << /F1 5 0 R >>" if (len(gs) > 0) res = res//" /ExtGState << "//gs//">>" + if (len(xo) > 0) res = res//" /XObject << "//xo//">>" res = res//" >>" call builder_init(f) pos = 0 - nobj = 5 call emit(f, pos, "%PDF-1.4"//eol) ! A comment with high bytes marks the file as binary for tools that @@ -477,6 +552,36 @@ subroutine pdf_close_canvas(self) //"/BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"//eol & //"endobj"//eol) + do i = 1, self%n_img + off(img_obj(i)) = pos + call emit(f, pos, int_str(img_obj(i))//" 0 obj"//eol & + //"<< /Type /XObject /Subtype /Image /Width " & + //int_str(self%img(i)%w)//" /Height "//int_str(self%img(i)%h) & + //" /ColorSpace /DeviceRGB /BitsPerComponent 8" & + //" /Filter /FlateDecode") + if (mask_obj(i) > 0) then + call emit(f, pos, " /SMask "//int_str(mask_obj(i))//" 0 R") + end if + call emit(f, pos, " /Length "//int_str(len(self%img(i)%rgb))//" >>" & + //eol//"stream"//eol) + call emit(f, pos, self%img(i)%rgb) + call emit(f, pos, eol//"endstream"//eol//"endobj"//eol) + + ! The mask is the alpha channel as a greyscale image of the same + ! size, which is how PDF spells per-sample transparency. + if (mask_obj(i) > 0) then + off(mask_obj(i)) = pos + call emit(f, pos, int_str(mask_obj(i))//" 0 obj"//eol & + //"<< /Type /XObject /Subtype /Image /Width " & + //int_str(self%img(i)%w)//" /Height "//int_str(self%img(i)%h) & + //" /ColorSpace /DeviceGray /BitsPerComponent 8" & + //" /Filter /FlateDecode /Length " & + //int_str(len(self%img(i)%alpha))//" >>"//eol//"stream"//eol) + call emit(f, pos, self%img(i)%alpha) + call emit(f, pos, eol//"endstream"//eol//"endobj"//eol) + end if + end do + xref_pos = pos call emit(f, pos, "xref"//eol//"0 "//int_str(nobj + 1)//eol) call emit(f, pos, "0000000000 65535 f "//eol) diff --git a/src/fplot_backend_svg.f90 b/src/fplot_backend_svg.f90 index 5f70215..2d2cad9 100644 --- a/src/fplot_backend_svg.f90 +++ b/src/fplot_backend_svg.f90 @@ -16,6 +16,7 @@ module fplot_backend_svg use fplot_render use fplot_svg, only: svg_builder, builder_init, builder_append, & builder_get, fmt_num, xml_escape_to + use fplot_png, only: png_encode implicit none private @@ -485,17 +486,74 @@ subroutine svg_draw_text(self, x, y, s, font, paint, anchor, baseline, angle) call put_eol(self) end subroutine svg_draw_text - ! A raster block becomes a base64 data URI holding a PNG. Left until the - ! PNG backend exists, since that is where the encoder will live; fplot - ! currently draws imshow as a grid of rectangles instead. + ! A raster becomes a PNG in a base64 data URI, which is what matplotlib + ! emits and what lets the whole image be one element. Smoothing is turned + ! off: the samples are the data, and interpolating them would show the + ! reader values that were never measured. subroutine svg_draw_image(self, x, y, w, h, rgba, nx, ny, paint) class(svg_renderer_t), intent(inout) :: self real(dp), intent(in) :: x, y, w, h integer, intent(in) :: nx, ny integer, intent(in) :: rgba(4, nx, ny) type(paint_t), intent(in) :: paint + + if (nx < 1 .or. ny < 1) return + call sync_clip(self, paint%clip) + call put(self, '') + call put_eol(self) end subroutine svg_draw_image + ! Three bytes become four characters; a short final group is padded with + ! "=" so the length still divides by four. + subroutine put_base64(self, s) + class(svg_renderer_t), intent(inout) :: self + character(len=*), intent(in) :: s + character(len=64), parameter :: TBL = & + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + character(len=:), allocatable :: out + integer :: i, n, k, v, b(3), have + + n = len(s) + allocate (character(len=4*((n + 2)/3)) :: out) + k = 0 + do i = 1, n, 3 + have = min(3, n - i + 1) + b = 0 + b(1:have) = [(iachar(s(i + v - 1:i + v - 1)), v=1, have)] + v = ishft(b(1), 16) + ishft(b(2), 8) + b(3) + out(k + 1:k + 1) = TBL(iand(ishft(v, -18), 63) + 1:iand(ishft(v, -18), 63) + 1) + out(k + 2:k + 2) = TBL(iand(ishft(v, -12), 63) + 1:iand(ishft(v, -12), 63) + 1) + if (have > 1) then + out(k + 3:k + 3) = TBL(iand(ishft(v, -6), 63) + 1:iand(ishft(v, -6), 63) + 1) + else + out(k + 3:k + 3) = "=" + end if + if (have > 2) then + out(k + 4:k + 4) = TBL(iand(v, 63) + 1:iand(v, 63) + 1) + else + out(k + 4:k + 4) = "=" + end if + k = k + 4 + end do + call put(self, out) + end subroutine put_base64 + subroutine svg_begin_group(self, name) class(svg_renderer_t), intent(inout) :: self character(len=*), intent(in) :: name diff --git a/src/fplot_png.f90 b/src/fplot_png.f90 index 76f9d9d..6701ebf 100644 --- a/src/fplot_png.f90 +++ b/src/fplot_png.f90 @@ -18,7 +18,10 @@ module fplot_png implicit none private - public :: png_encode + ! zlib_compress is here rather than in the PDF backend because a PDF + ! FlateDecode stream is the same zlib stream a PNG carries, and one + ! compressor is enough. + public :: png_encode, zlib_compress ! LZ77 parameters. WSIZE is fixed by the format; CHAIN bounds how hard the ! matcher looks before settling, which is the usual size/speed dial. @@ -385,6 +388,22 @@ function png_encode(w, h, rgba) result(bytes) end do end function png_encode + ! Bytes in, a zlib stream out. Unlike a PNG the caller supplies its own + ! layout, so nothing is filtered here. + function zlib_compress(src) result(bytes) + integer, intent(in) :: src(:) + character(len=:), allocatable :: bytes + integer, allocatable :: z(:) + integer :: i, n + + n = size(src) + z = zlib_wrap(deflate(src, n), src, n) + allocate (character(len=size(z)) :: bytes) + do i = 1, size(z) + bytes(i:i) = achar(z(i)) + end do + end function zlib_compress + function zlib_wrap(comp, raw, nraw) result(z) integer, intent(in) :: comp(:), raw(:), nraw integer, allocatable :: z(:) diff --git a/tests/gen_mpl_refs.py b/tests/gen_mpl_refs.py index 16f6f1b..9867417 100644 --- a/tests/gen_mpl_refs.py +++ b/tests/gen_mpl_refs.py @@ -37,6 +37,7 @@ "facecolor", "imshow", "imshow_cbar", + "imshow_log", "scatter_cmap", "contour", "contourf", @@ -538,6 +539,13 @@ def main() -> None: plt.close(f2) save(f1, "figures") + # 44 an image on a log axis + fig, ax = setup_fig() + ax.imshow(zimg, extent=(1.0, 1000.0, 0.0, 4.0), aspect="auto") + ax.set_xscale("log") + ax.set_title("imshow on a log axis") + save(fig, "imshow_log") + print("All matplotlib references written.") diff --git a/tests/test_plots.f90 b/tests/test_plots.f90 index a94edc7..56ce116 100644 --- a/tests/test_plots.f90 +++ b/tests/test_plots.f90 @@ -533,6 +533,14 @@ program test_plots call save_all("figures") call close(all=.true.) + ! 44) an image on a log axis, where the samples are no longer evenly + ! spaced on the canvas and so cannot be sent as one raster + call figure() + call imshow(zimg, extent=[1.0_dp, 1000.0_dp, 0.0_dp, 4.0_dp], aspect="auto") + call set_xscale("log") + call title("imshow on a log axis") + call save_all("imshow_log") + print *, "All test plots written." contains