Repository navigation
Modular, extensible status line via AbstractProgressElement - #369
milankl-claude wants to merge 6 commits into
Conversation
|
@milankl if that's your PR please review it before submitting and make a human explanation to it |
milankl
left a comment
There was a problem hiding this comment.
Hi @MarcMush, yes, after our discussion in #357 I had a discussion with Claude how to implement this in detail and this is what we came up with. I knew what we wanted from #357 but Claude helped me to figure out the details to map across ProgressThresh and ProgressUnknown (that I don't use) and wrote the tests. I normally review at least once also on github so that others have input on the discussion of the more critical points and can form their opinion instead of just seeing fully reviewed code.
Human summary: We introduce elements to the progress types to create a user interface for custom progress elements, especially those that depend on whatever is happening while a Progress is visualising that progress, e.g. some statistic of a big data analysis or a simulation. New elements just have to be <: AbstractProgressElement and have to extend the print_element function, as we wrote into the README. Furthermore all the current lines of code that concatenate the msg string of the progress line are rewritten using that interface now, which removes some duplicated code. I've highlighted some more specific points in the comments
| @static if VERSION >= v"1.11.0-DEV.469" | ||
| eval(Meta.parse("public AbstractProgressElement, ProgressStatus, print_element, Description, Percentage, Bar, ETA, Speed, ElapsedTime, Counter, Threshold, Spinner")) | ||
| end |
There was a problem hiding this comment.
This is to make the new types only public after the current version, I let you decide how to export or make them public given changes to them afterwards would probably treated as breaking
There was a problem hiding this comment.
@milankl-claude why did you choose v"1.11.0-DEV.469"? v"1.11.0" is already released
There was a problem hiding this comment.
That is the Julia dev build in which the public keyword was added, the cutoff that Compat.jl's @compat public uses too. Unlike v"1.11", it also covers the 1.11 alpha/beta/rc releases, which already parse public. In practice the two behave the same, so I can change it to v"1.11" if that reads better. The eval(Meta.parse(...)) is still needed because 1.10 cannot parse public.
| "(12.34 ms/it)" to the description by setting `showspeed=true`. | ||
| To customize the status line pass a tuple of `elements`, e.g. | ||
| `elements=(ProgressMeter.Description(), ProgressMeter.Bar(), " ", MyElement())`, | ||
| see [`ProgressMeter.AbstractProgressElement`](@ref). |
There was a problem hiding this comment.
I believe this only really does something when there's a properly built documentation but doesn't hurt to have a @ref already? @milankl-claude can you comment on this?
There was a problem hiding this comment.
Right, ProgressMeter has no Documenter build, so nothing resolves these links yet. They do no harm either: in the REPL ?Progress shows [X](@ref) as plain X, which I checked. I kept them so they work if docs are ever built, but I can turn them into plain code spans if you prefer.
| done::Bool # is the task done? | ||
| spinner::Bool # show a spinner | ||
| spincounter::Int # counter for spinner | ||
| spinnerchars::Union{AbstractChar,AbstractString,AbstractVector{<:AbstractChar}} # spinner characters of the current update |
There was a problem hiding this comment.
@milankl-claude Maybe worth introducing const SpinnerTypes = Union{...} here?
There was a problem hiding this comment.
Done in b41cfc3, const SpinnerTypes = Union{...}, used both for the field and for the spinner kwarg of _updateProgress!(::ProgressUnknown).
| struct ProgressStatus | ||
| t::Float64 | ||
| elapsed::Float64 | ||
| finished::Bool | ||
| end |
There was a problem hiding this comment.
This new type (created on the fly on every progress line update) was created as many progress elements depend on that information (e.g. to calculate percentage, the bar length etc) and so it allows a single argument in the print_element(..., ::ProgressStatus) API to define a custom progress element
There was a problem hiding this comment.
Also with the finished field here any progress element can decide to print differently in print_element while running/when finished, e.g. to turn into some summary statistic instead of information of snapshot during progress. Like ETA turns into total time elapsed when finished.
| whatever the element shows. Strings are elements that print themselves. | ||
| """ | ||
| function print_element end | ||
| print_element(s::AbstractString, ::AbstractProgress, ::ProgressStatus) = s |
There was a problem hiding this comment.
@milankl-claude is this method actually used, if purely defined as fallback, mark that in a comment?
There was a problem hiding this comment.
It is used, not only a fallback. The default layouts of ProgressThresh and ProgressUnknown contain string separators such as " " and " Time: ", and users can write e.g. elements = (Description(), " | ", Bar()). I added a comment in b41cfc3.
| msg = @sprintf "%s Time: %s (%d iterations)" p.desc dur p.counter | ||
| if p.showspeed | ||
| sec_per_iter = elapsed_time / p.counter | ||
| msg = @sprintf "%s (%s)" msg speedstring(sec_per_iter) | ||
| end |
There was a problem hiding this comment.
This PR also removes these duplications across the update for Progress, ProgressTresh, ... see comment above that comments on similar/identical lines of code
| const spinner_chars = ['◐','◓','◑','◒'] | ||
| const spinner_done = '✓' |
There was a problem hiding this comment.
moved up to where Spinner element is defined, not removed
There was a problem hiding this comment.
Small correction: they sit just above ProgressUnknown, whose constructor uses spinner_chars as its default, rather than next to Spinner. Doing that put them between the ProgressUnknown docstring and the struct, so ?ProgressUnknown showed nothing. Fixed in b41cfc3.
| # Generated from ProgressMeter v1.11.0 output; the refactor must reproduce these exactly. | ||
| const GOLDEN_OUTPUTS = Dict( |
There was a problem hiding this comment.
"Golden" here means non-breaking in terms of progress bar appearance -- I wouldn't consider this breaking if the progress bar looks different from one version to the other (in contrast to the user interface of constructing a progress) but here it serves to verify that the progress does indeed print the same as before. You may want to take these tests out before merging as you'd otherwise get a failure in the future if you decide to change the appearance ... happy to leave it or to disable these tests
| elements = (ProgressMeter.Description(), ProgressMeter.Percentage(), | ||
| ProgressMeter.Bar(), ProgressMeter.ETA(), MaxValue(data))) | ||
| for i in eachindex(data) | ||
| data[i] = i / 10 |
There was a problem hiding this comment.
@milankl-claude maybe make it clear here (or in the paragraph above) that because the progress element was externally defined with a pointer to some data, that information can now be easily included as an element into the progress line, otherwise it seems a bit confusing of why you do data[i] = i / 10 here. While it's nice to have some customization on the progress line of course, the overall motivation is to print information that depends on whatever is happening (e.g. some big computation) while the progress bar visualises its progress
There was a problem hiding this comment.
Done in b41cfc3. A paragraph before the example now explains that the element holds a reference to the data being computed, so each redraw shows its current state, and that this is the main use case.
| | `Threshold()` | `(thresh = 0.1, value = 0.5)` | `ProgressThresh` | | ||
| | `Spinner()` | a spinning character | `ProgressUnknown` | | ||
|
|
||
| Without `elements` the layout is the same as before and determined by `desc`, `showspeed` |
There was a problem hiding this comment.
@milankl-claude given this is a readme "before" is likely relative, so maybe just give an example for Progress and say this would correspond to elements = (...) during construction?
There was a problem hiding this comment.
Done in b41cfc3. The README now shows that Progress(n; showspeed=true) corresponds to elements = (Description(), Percentage(), Bar(), ETA(), Speed()), and notes that only the bar length can differ by a few characters (estimated vs measured width).
|
Here are some thoughts (open to discussion of course) the Elements can be in a different file to reduce the size of the main file and to try to simplify Could we call it templates? still made of elements, which means a template is made of elements I wonder if we can remove some fields in function default_elements(p::Progress, showspeed, showeta, showelapsed, check_iterations)
elements = (Description(), Percentage(), Bar(true))
elements = p.showspeed ? (elements..., Speed(check_iterations)) : elements
elements = p.showeta ? (elements..., ETA(check_iterations)) : elements
elements = p.showelapsed ? (elements..., Elapsed()) : elements
return elements
endWe should have a way to colour each element a different color, or even multiple colors in a single element ? (#361).
maybe show_values could also be included in the template? would this mean we should be able to change other elements with we should have a way of disabling escape characters for text output or basic terminals (#151, #222, #223) These are big design decision, I would like to have other maintainers thoughts @timholy @IanButterworth |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #369 +/- ##
==========================================
- Coverage 96.39% 96.14% -0.26%
==========================================
Files 3 4 +1
Lines 610 596 -14
==========================================
- Hits 588 573 -15
- Misses 22 23 +1 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
I also wonder what's the best way of constructing the progressbar
|
The status line of all progress meters is now assembled from elements (Description, Percentage, Bar, ETA, Speed, ...) rendered by one shared code path instead of six format strings. Users can pass their own elements to customize what is shown without overriding internals (timholy#357). The default layout is unchanged, checked byte for byte by new golden output tests recorded from v1.11.0.
…ssUnknown docstring The spinner constants sat between the ProgressUnknown docstring and the struct, so the docstring was attached to spinner_chars instead.
…to ProgressCore, Colored element - Move elements, default_elements and render_line to src/elements.jl, inside an exported submodule Elements that exports the element names - Remove ProgressStatus: ProgressCore gets tcurrent and finished, set before each redraw; print_element(element, p) now takes two arguments - Add Elements.Colored(element, color); render_line returns text => color segments, merged when neighbours share a color, so the default output is unchanged - printover styles the segments into a buffer and writes the line at once
44b4664 to
5bdde06
Compare
|
Thanks for the thorough review, @MarcMush! Here's every suggestion from your two comments, with what I did or what I'd propose. The changes are in 5bdde06. (I also force-pushed the branch to fix the author of the earlier commits, which had been committed under milankl's git identity by mistake. The code is unchanged.) Done in this PR
Construction of the line (your second comment)
Open for discussion / proposed follow-ups
Tests: the golden outputs (all 13 cases, colored one included) and the new color tests pass. The full suite passes locally on Julia 1.13 with 4 threads, |
|
Agree with most of your points @MarcMush, but not sure about "templates", a template would be a typical progress line one would start from and then only make few changes to it, but given that the elements are now an immutable tuple, I don't really see the idea of them being a "template". Hence I continue to prefer The discussion on what to do with Some of the other points mentioned should probably get their own PR to not grow this too much. |
…hmarks (timholy#370) Resolve conflicts by keeping the shared draw! path of this PR and porting master's print_repeat into draw!; printover colors segments with printcolored, which now also takes Int colors for Elements.Colored.
Benchmark Results (Julia v1)Time benchmarks
Memory benchmarks
|
|
@MarcMush ping. Is there more I can do to get this merged? |
|
ping |
Implements the proposal from #357: the status line of every progress meter is assembled from elements that users can rearrange or extend, so custom information no longer requires overriding internals.
Closes #357
What changes for users
AbstractProgressElementandprint_element(element, p): besides the usual fields,p.tcurrentholds the time of the redraw andp.finishedwhether the meter is finished (both new fields ofProgressCore).print_elementis only called when the meter is actually redrawn (throttled bydt), so elements can compute what they show on the fly.Description,Percentage,Bar,ETA,Speed,ElapsedTime,Counter,Threshold,Spinner. Plain strings act as separators.Colored(element, color)prints an element in its own color; all others use the meter'scolor.elementsandbarlen=nothing,Bar()fills whatever width the other elements leave, measured withtextwidth. This replaces the fixed 29/14 column estimate.src/elements.jl, in the exported submoduleProgressMeter.Elements. The submodule exports the element names, sousing ProgressMeter.Elementsbrings them into scope on request, and generic names likeBar/Counternever clash otherwise.Non-breaking
elementsisn't passed (defaultnothing), the meters render the same layout as before. That layout is rebuilt on each redraw, so changes top.showspeedandupdate!(p; desc=...)still take effect.test/golden_cases.jl,test/golden_outputs.jl) were recorded on master (v1.11.0) before the refactor. They cover 13 configurations, includingshowspeed,barglyphs/barlen,start,max_steps,descchanges,showvalueswithoffset,cancel, colors,ProgressThreshandProgressUnknownwith spinner. The refactored code reproduces all of them byte for byte; only machine-dependent times and speeds are normalized.Progressskips the newline handling while IJulia clears output (guard_ijulia). Unifying that would be a reasonable follow-up, but it's out of scope here.next!on the hot path still allocates nothing new; timings match master on my machine.Refactor
As suggested in #357, the six copy-pasted format-and-print branches of
_updateProgress!(running and finished, for each of the three meter types) are now a shared path:render_linebuilds the line from the elements.draw!prints it, together with the cursor movement,showvaluesandkeep.canceluses it too.draw_running!contains the timing logic.The per-type
_updateProgress!methods now only decide when to draw. Adding an option like #356'sshowelapsed/showetathen mostly means choosing elements.Motivation: SpeedyWeather.jl currently pirates
ProgressMeter.speedstringand uses globalRefs to show simulation time, speed in simulated years/day, maximum wind speed and temperature range in its progress bar. With elements this becomes a set of types holding references to the simulation, which compute those diagnostics (and new ones, like a Courant number) only when the bar is redrawn.Testing
--check-bounds=yes, andtest/test_elements.jlpasses on Julia 1.10. The local-only timing assertiont_prog < 9*t_noprogincore.jlfails on my (noisy) machine for master as well, so I ran withCI=true.test/test_elements.jl:print_elementcalled only on redrawp.elementsafter constructionProgressThresh/ProgressUnknownbarlen, and two bars sharing the width🤖 Generated with Claude Code