Skip to content

New unit - #1

Closed
thomasp85 wants to merge 84 commits into
masterfrom
new-unit
Closed

thomasp85 wants to merge 84 commits into
masterfrom
new-unit

Conversation

@thomasp85

Copy link
Copy Markdown
Owner

This PR includes a new unit structure intended to simplify the unit specification as well as making it substantially faster. The reason for this is that unit operation has been identified as a recurring bottleneck in working with grid, and any improvements to this will have broad effects on grid performance.

The old unit spec was essentially covering three different structures that could be used interchangeably. The basic unit (what you get from the constructor), was an adorned numeric vector including attributes for the unit type, and potential unit data. A second type was the unit.arithmetic which was sort of an AST, containing the arithmetic function and the arguments. Lastly, a unit-list type was also provided that could contain scalar versions of the other two unit specs.

The new spec is greatly simplified and contain only a single structure, mostly resembling the unit.list. The structure is that of a list containing scalar units encoded as a list of three elements. The first element is a numeric given the value of the unit. The second element is any potential data related to the unit. The third element is the unit, given as an integer identifier (what was stored in the valid.unit attribute in the old setup). Arithmetic is supported by adding three new units: sum, min, and max. The data of these units is itself a unit vector. + and - operations are supported by converting to a sum representation: u1 + u2 -> sum(u1, u2) and u1 - u2 -> sum(u1, -u2). If possible, arithmetic operations simplify the result by inspecting the unit and data for equivalence and simply operating on the value if possible: 1cm + 5cm -> 6cm instead of 1cm + 5cm -> sum(1cm, 5cm)

Most unit operations have further been moved to C code, and more may follow (e.g. data validation)

The speed-ups are significant in almost all regards:

some common operations:
image

absolute.units are mostly used when resolving viewport dimensions
image

vectorised arithmetic is much improved
image

The only performance regression is when adding and subtracting units, but this is simply because the old spec didn't perform any operations and simply returned a pseudo AST. Further operations on the result would provoke an evaluation of some kind and remove the performance lead

The new structure has been implemented without any user-facing changes, but users relying on the underlying structure of the old implementation will of course get errors (relying on that was dangerous in the first place due to the triple nature of units in the old setup). as.numeric and as.vector methods has been provided to coerce the new structure into a numeric vector, but not all functions may call this explicitly but simply rely on automatic dropping of attributes (e.g. c(4, some_unit, 2) will no longer return a numeric vector)

@thomasp85

Copy link
Copy Markdown
Owner Author

@hadley, @lionel-, and/or @pmur002, if you could have a look at this, and maybe do a review of the code it would be much appreciated... This is my first time writing C-code so my style may be weird - just let me know...

I'll begin to work on a test suite, but as is ggplot2 works with the new spec (pending tidyverse/ggplot2#3034), which is a very good start

@lionel-

lionel- commented Dec 13, 2018

Copy link
Copy Markdown

@thomasp85 Could you cancel all whitespace changes please? This will facilitate the review.

@thomasp85

Copy link
Copy Markdown
Owner Author

oh, sure... RStudio must have done something automatically...

@thomasp85

Copy link
Copy Markdown
Owner Author

should be clean from ws changes now 😄

@hadley hadley left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I gave it a once over at a fairly high level.

Comment thread src/unit.c Resolved
Comment thread src/unit.c Resolved
Comment thread src/unit.c Resolved
Comment thread src/unit.c Resolved
Comment thread src/unit.c Resolved

@lionel- lionel- left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly styling comments:

  • It seems the grid package uses camelCase rather than snake_case.

  • Some if/else branches are not braced.

  • I think effectful expressions should be on their own line rather than hidden behind if conditions:

    # Easy to miss:
    if (long && condition && stuff) stop("foo")
    
    for (x in y) {
      if (long && condition && stuff) a <- b
    }
    
    
    # Clearer:
    if (long && condition && stuff) {
      stop("foo")
    }
    
    for (x in y) {
      if (long && condition && stuff) {
        a <- b
      }
    }
  • Control flow can be hard to read at times, for instance in Summary.unit(). Some patterns can help:

    • Switching over enums is faster and gives more structure to the control flow (whereas if-else branch conditions might be different so the reader needs to double check).

    • Extract loops in functions.

    • Avoid nested if-else branches by extracting nested branches in functions.

    • Refactor if-else branches so that each branch exits the function (either by error or by returned value). Then you can remove the else and give some breathing room to the branches. This also reassures the reader that all branches play a similar role in the function, which is very helpful to understand control flow.

Comment thread src/unit.c Resolved
Comment thread src/unit.c Resolved
Comment thread src/unit.c Resolved
Comment thread src/unit.c Resolved
@thomasp85 thomasp85 mentioned this pull request Jul 2, 2019
8 of 23 tasks
@pmur002

pmur002 commented Jul 3, 2019

Copy link
Copy Markdown
Collaborator

Thanks. I can build this ok, but a couple of tests show up some problems. To test, I am generating unit and grob objects in "old" (current release) R ...

library(grid)
## "unit"
u1 <- unit(1, "npc")
## "unit.arithmetic"
u2 <- u1 - unit(1, "in")
## "unit.list"
u3 <- unit.c(u1, u2)
save(u1, u2, u3, file="old-units.rds")

## Generate and save grid grobs containing "old" units
library(grid)
r1 <- rectGrob(x=u1)
r2 <- rectGrob(x=u1, y=u2)
r3 <- rectGrob(x=u1, y=u2, width=u3)
save(r1, r2, r3, file="old-grob.rds")

... and then trying to load them and print/draw them in new-unit build of R, which gives me a fail for the "unit.list" object ...

> load("upgradeUnit/old-units.rds")
> u1
[1] 1npc

> u2
[1] sum(1npc, -1inches)

> u3
Error in vapply(x, attr, character(1), which = "unit") : 
  values must be length 1,
 but FUN(X[[2]]) result is length 0
In addition: Warning message:
In unit(unlist(x), vapply(x, attr, character(1), which = "unit"),  :
  NAs introduced by coercion

... and bad things for all of the grobs ...

> load("upgradeUnit/old-grob.rds")
> grid.draw(r1)
Error in grid.Call.graphics(C_rect, x$x, x$y, x$width, x$height, resolveHJust(x$just,  : 
  VECTOR_ELT() can only be applied to a 'list', not a 'double'

> grid.draw(r2)
Error in grid.Call.graphics(C_rect, x$x, x$y, x$width, x$height, resolveHJust(x$just,  : 
  VECTOR_ELT() can only be applied to a 'list', not a 'double'

> grid.draw(r3)
Error in grid.Call.graphics(C_rect, x$x, x$y, x$width, x$height, resolveHJust(x$just,  : 
  VECTOR_ELT() can only be applied to a 'list', not a 'double'

Do you have time to take a look at those ?

@thomasp85

Copy link
Copy Markdown
Owner Author

Thanks for the test problems... I thought I had tested these situations but I may have messed up somewhere... Will fix

The unitType() is added because it seems a lot of people are extracting the unit attribute because they want to query it somehow... having a dedicated function for that seemed reasonable, but I'm not married to the idea, so if you don't want to expand the API I'll just remove it again

@pmur002

pmur002 commented Jul 3, 2019

Copy link
Copy Markdown
Collaborator

Maybe don't export unitType() for now. I would like some evidence that people are using it for a good reason before officially letting that cat out of the bag.

@thomasp85 thomasp85 closed this Apr 21, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants