--- title: "The NestedScale object" description: "Anatomy of a NestedScale: the leaftable, frames, members, the attribute and alias tables and meta; what the validator guarantees; definition files; the rule registry." output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{The NestedScale object} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set(collapse = TRUE, comment = "#>") library(nestedscales) ``` This vignette takes one object apart. The example is a small classification of industries by business code, in the style of a statistical classification of activities: sections (`C`, Manufacturing) hold divisions (`C10`, Food products), which hold classes (`C101`). The codes, the names and every number are invented for illustration and reproduce no official classification. The example has every awkward feature: a code reused at two frames, a frame that cross-cuts another, a leaf with no code at one frame, and attributes stored at three different frames. The cross-cutting frame is `size`, a grouping of the classes by the typical size of their firms, `small` or `large`. Public administration (`O84`) is not made of firms and has no size, and it is not subdivided, so its only class carries the code of its division. ```{r industries} lt <- data.frame( section = c("C", "C", "C", "C", "C", "D", "D", "D", "O"), size = c("small", "large", "small", "large", "large", "large", "small", "small", NA), division = c("C10", "C10", "C11", "C24", "C24", "D35", "D35", "D35", "O84"), class = c("C101", "C102", "C110", "C241", "C242", "D351", "D352", "D353", "O84") ) at <- data.frame( frame = c("class", "class", "division", "section", "class", "division"), member = c("C101", "C102", "D35", "C", "C241", "D35"), attribute = c("wage", "wage", "wage", "wage", "floor_area", "floor_area"), kind = c(rep("property", 4), "factor", "factor"), value = c(30, 28, 45, 32, 60, 20), unit_of_measure = c(rep("thousand/employee", 4), "m2/employee", "m2/employee"), source = "example" ) al <- data.frame( frame = c("class", "division", "class", "division", "division"), member = c("C101", "C10", "O84", "O84", "O84"), alias = c("meat", "food", "public admin", "public admin", "government"), source = "example" ) x <- scale_from_leaftable( lt, frames = c("section", "size", "division", "class"), leaf = "class", attributes = at, aliases = al, name = "industries" ) x ``` ## The object A `NestedScale` is an S7 object with eight properties. `str()` lists them with their size and purpose: ```{r props} str(x) ``` The standard S7 tools apply: `S7::prop_names(x)` gives the names, `x@frames` or `S7::prop(x, "frames")` reads one property, and `S7::props(x)` returns all of them as a list. ```{r props-s7} S7::prop_names(x) x@frames ``` The object is a **definition**: the leaves, the frames that group them, and the weights that say how big each leaf is. It never holds data. Data stays in ordinary tables, and a table is tied to a scale by its code columns; see [The data link](#the-data-link) below. | property | type | holds | |---|---|---| | `leaftable` | `data.frame` | one row per leaf: one column per frame, the leaf column, weight columns | | `frames` | `character` | the hierarchy, ordered coarsest first | | `members` | named `list` | the ordered code vocabulary at each frame | | `leaf` | `character` | the name of the leaf column (`"leaf"` by default) | | `meta` | `list` | `name`, `desc`, `weights`, `default_weight`, and whatever the builder adds | | `attributes` | `data.frame` | values keyed by `(frame, member)`: `attribute`, `kind`, `value`, `lower`, `upper`, `unit_of_measure`, `source`, `note` | | `aliases` | `data.frame` | alternative spellings keyed by `(frame, member)`: `alias`, `source` | | `labels` | `data.frame` | display names keyed by `(frame, member, variant)`: `label` | Everything else -- parent/child tables, ancestry, shares, resolved attributes -- is derived on demand; nothing is cached on the object. The three tables are empty unless the builder fills them; a scale saved by an earlier version, which had no such properties, loads and validates unchanged. ## The leaftable ```{r leaftable} scale_leaftable(x) ``` Each row is one leaf. The leaf column (`class` here) is unique and complete. Frame columns may hold `NA`: `O84` has no firm size, so it does not participate at the `size` frame, and `na_action=` decides what recasts do about it. The leaf column may be the finest frame, as here: the frame column *is* the leaf column. ## Frames, members, ranks ```{r frames} scale_frames(x) scale_leaf_frame(x) # the finest frame, or the leaf column scale_members(x, "division") # the members at one frame scale_members(x) # the leaves scale_rank(x, "division") ``` Codes are **not unique across frames**: `O84` is a division and a class here. Every function that takes a code therefore takes its frame as well. Navigation is derived from the leaftable and routed through the leaves, so a frame that cross-cuts another reports overlap rather than invented containment: ```{r navigate} scale_nests(x, "division", "class") # a tree scale_nests(x, "size", "division") # C10 and D35 are small and large scale_parents(x, "division", "D35", target = "size") scale_ancestors(x, "class", "D352") scale_descendants(x, "section", "C") head(scale_ancestry(x), 4) ``` ## The attribute table Attributes live in one long table, and a row may sit on **any** member, not only on a leaf. Here a wage per employee is given for two classes, one division and one section, and a floor area per employee for one class and one division: ```{r attributes} scale_attributes(x) ``` Reading with a `frame` resolves one value per member, walking to the nearest coarser frame when a member has none of its own, and says where the value came from: ```{r resolve} scale_attributes(x, "wage", frame = "class")[ c("member", "value", "unit_of_measure", "origin_frame", "origin_member")] ``` Attributes are **not weights**. A weight says how big a leaf is and drives aggregation; an attribute is a per-member conversion factor and is consumed only by `convert_scale()`. The constructor promotes numeric leaftable columns to weights, so a wage must be passed as `attributes=`, never as a leaftable column. Every attribute name carries a `kind`: `property` (an invertible ratio) or `factor` (one-way). ```{r kinds} SCALE_ATTRIBUTE_KINDS ``` `vignette("attributes")` has the reasoning and the full account of inheritance, sources and conversion. ## The alias table The members of this scale are codes; the alias table holds the names and spellings by which other tables refer to the same activities. ```{r aliases} scale_aliases(x) scale_match(x, c("meat", "Public Admin", "C242")) ``` One alias may point at several members (`public admin` above); matching reports that as ambiguous unless `frame=` narrows it. Matching is exact and case-insensitive, with no fuzzy stage. ## The label table Labels are display names. A label belongs to a member and to a named *variant*, so one member may carry a full name, a short one and a translation, while another frame carries none at all and is shown by its codes. A row with `member = NA` names the frame itself. The divisions get two variants here, a short name and a long one, and the short one is declared the default: ```{r labels} x <- attach_labels_scale( x, data.frame( frame = "division", member = rep(c("C10", "C24", "O84", NA), 2), variant = rep(c("short", "long"), each = 4), label = c("Food", "Metals", "Administration", "Division", "Manufacture of food products", "Manufacture of basic metals", "Public administration", "Division of activity") ), default = "short" ) scale_labels(x) scale_label(x, c("C10", "C11", "O84"), frame = "division") scale_label(x, c("C10", "C11", "O84"), frame = "division", variant = "long") scale_label(x, scale_members(x, "size"), frame = "size") # no labels: codes ``` `C11` has no label in either variant and is shown by its code. Aliases and labels serve different purposes. An alias is a spelling to be *recognised* (`scale_match()`); a label is a name to be *shown* (`scale_label()`, `join_scale(labels = )`). ## Weights and meta ```{r meta} scale_weights(x) # none declared here S7::prop(x, "meta")[c("name", "desc")] ``` `meta$name` is load-bearing: `join_scale()` prefixes the columns it attaches with `"."`, `scale_map_between()` names its label columns after the objects, and `write_scale()` needs a name for the definition. Further fields passed to the constructor are kept in `meta` as given. ## The data link A table of data is tied to a scale by its code columns. Unbound, the tie is the column name alone: a column called `division` is read as codes at the `division` frame. Two scales can share frame names and codes, so the name does not say *which* scale the data is on. `bind_scale()` records it on the column itself, together with the scale's identity. The link is experimental: it is lost when the column is converted to a factor or a plain character vector, and it may change. ```{r link} scale_id(x) d <- data.frame(class = scale_members(x), jobs = seq_along(scale_members(x))) b <- bind_scale(d, x) scale_link(b) ``` `scale_id()` is the scale's name plus a hash of its structure -- leaf column, frames and memberships. Weights, attributes, aliases and labels do not enter, so enriching a scale does not detach the data bound to it; a subset or a re-grouping is a different scale. A bound column is still a character vector. It keeps the link through row subsetting, `mutate()`, grouping, joins and row binding, and the verbs use it: the source frame is taken from the link, the result is bound to the target frame, and data bound to another scale is refused. ```{r link-verbs} register_scale_rule("jobs", "sum") out <- recast_scale(b, x, target = "division") scale_link(out) clear_scale_rules("jobs") ``` Unbound data behaves as before, and its results stay unbound. A lazy table (arrow, dtplyr) cannot carry the link in memory; `write_scale_dataset()` records it in the store and `scale_link()` reads it back. ## What the validator guarantees `scale_from_leaftable()` and every operation that rebuilds a scale enforce: - the leaf column is present, unique and complete; every frame is a leaftable column and `members` are exactly its non-`NA` values, in a stable order; - weights are numeric and finite; - every attribute and alias row names a `(frame, member)` that is a member; `value` is finite; `lower <= value <= upper` where given; `kind` is one of `SCALE_ATTRIBUTE_KINDS` and one attribute name has one kind; `unit_of_measure` and `source` are non-empty; no duplicate `(frame, member, attribute, source)` rows and no duplicate alias rows. The order of `frames` is a convention, coarsest first; the direction-dependent rules (`share`, residuals, reconciliation) follow it. Subsetting keeps the tables consistent: `filter_scale()` and `[` keep the attribute and alias rows of every surviving member at every frame, and `prune_scale()` keeps the rows at the frames that survive the collapse. ```{r subset} manufacturing <- x["section", "C"] scale_attributes(manufacturing)[c("frame", "member", "attribute", "value")] ``` `prune_scale()` needs the frames above the new leaf frame to nest, so the cross-cutting `size` has to go first: ```{r prune} tree <- scale_from_leaftable( lt[c("section", "division", "class")], frames = c("section", "division", "class"), leaf = "class", attributes = at, aliases = al, name = "tree" ) scale_aliases(prune_scale(tree, "division")) ``` ## Definition files A scale is stored as a definition, not as an R object: a JSON header with the three tables inline, or, for large scales, a `.scale/` bundle directory holding the header and the tables as Arrow IPC or CSV files. The Python binding reads and writes the same files. ```{r definition} path <- file.path(tempdir(), "industries.json") write_scale(x, path) cat(head(readLines(path), 12), sep = "\n") back <- read_scale(path) identical(scale_frames(back), scale_frames(x)) identical(scale_attributes(back), scale_attributes(x)) ``` `write_scale(format = "yaml")` writes the same header as YAML, and `read_scale()` accepts either. Installed packages register directories of definitions; `scale_catalog()` lists them and `read_scale(id)` opens one by its id: ```{r catalog} scale_catalog()[c("id", "name", "kind", "frames", "n_leaves", "package")] ``` ```{r cleanup, include = FALSE} unlink(path) ``` ## The registry One package-level registry changes behaviour explicitly. **Rules** map value-column names to their aggregation rule; there is no fallback, and an unregistered column without `rule=` is an error: ```{r rules} SCALE_RULES register_scale_rule("jobs", "sum") register_scale_rule("wage", "weighted_mean", weight = "jobs") get_scale_rule("wage") list_scale_rules() clear_scale_rules() ``` A rule may be scoped to one dimension with `scope=`, so a `jobs` column aggregates the same way over industries, regions and months without being registered three times -- or differently, when it should. ## Where to next? - `vignette("nestedscales")` -- the tour of the main functions. - `vignette("attributes")` -- attributes, aliases and conversion on a small scale of cities.