---
title: "Note functions"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Note functions}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
options(crayon.enabled = TRUE)
sgr_wrap <- function(x, options){
  paste0("<pre class=\"r-output\"><code>", fansi::sgr_to_html(x = htmltools::htmlEscape(x)), "</code></pre>")
}
knitr::knit_hooks$set(output = sgr_wrap)
knitr::opts_chunk$set(
  collapse = TRUE, comment = "#>", message = FALSE, warning = FALSE, error = FALSE, tidy = FALSE, out.width = "100%"
)
library(tabr)
```

## Note identity checks

There are a number of functions that assist with music programming around note and pitch validation, comparison, equivalence checking, and various manipulations and transformations. In a previous section, you saw `is_note()` and `is_chord()`. Other identity functions include:

* `note_has_natural()`
* `note_has_accidental()`
* `note_has_flat()`
* `note_has_sharp()`
* `note_is_natural()`
* `note_is_accidental()`
* `note_is_flat()`
* `note_is_sharp()`
* `note_has_tick()`
* `note_has_integer()`
* `note_is_tick()`
* `note_is_integer()`
* `is_diatonic()`

```{r notes1a}
x <- "c e_ g b_"
note_has_accidental(x)
note_is_accidental(x)
```

The function `is_diatonic()` takes a `key` signature for context.

```{r notes1b}
x <- "c e_ g b_ cd#g"
is_diatonic(x, key = "c")
is_diatonic(x, key = "b_")
```

## Noteworthy string metadata

There are a number of functions that parse basic metadata about noteworthy strings.

* `n_steps()`
* `n_notes()`
* `n_chords()`
* `n_octaves()`
* `chord_size()`
* `octave_type()`
* `accidental_type()`
* `time_format()`
* `is_space_time()`
* `is_vector_time()`

See `help("note-metadata")` for details. A few examples are shown here.

```{r notes2a}
x <- "e_2 a_, c#f#a#"
n_steps(x)
n_notes(x)
n_chords(x)
chord_size(x)
octave_type(x)
time_format(x)
```
## Noteworthy string summaries

While there is not a clear delineation between the previous set of functions and the next, it helps to break them up a bit since there are many. These functions go bit further in summarizing the data in noteworthy strings.

* `tally_notes()`
* `tally_pitches()`
* `octaves()`
* `tally_octaves()`
* `distinct_notes()`
* `distinct_pitches()`
* `distinct_octaves()`
* `pitch_range()`
* `semitone_range()`
* `semitone_span()`
* `octave_range()`
* `octave_span()`

See `help("note-summaries")` for details. Here are some examples.
 
```{r notes2b}
x <- "e_2 a_, b_, c#f#a# c#'f#'a#''"
tally_notes(x)
tally_pitches(x)
distinct_notes(x)
distinct_pitches(x)
pitch_range(x)
semitone_range(x)
```

## Coercion functions

### Accidentals

Note that it is common for functions to treat notes as different if they sound the same but one is transcribed as a flat and the other as a sharp. `tabr` makes the distinction for notation purposes; same pitch, different notes. This also supports transcription. Functions like `transpose()` of course handle pitch as pitch and therefore the style of representation does not affect computation.

There are functions for enforcing a singular representation for accidentals in noteworthy strings since it is unusual to mix flats and sharps.

```{r notes3}
flatten_sharp(x)
sharpen_flat(x)
```

Do not be confused about the names of these functions. They are for enforcing a single type of accidental. To actually lower sharps by a half step or semitone as well as raise flats similarly, use `naturalize()`.

```{r notes4}
naturalize(x)
```

These are helpful building blocks for music programming. A useful wrapper around `flatten_sharp()` and `sharpen_flat()` is `note_set_key()`. Like `is_diatonic()`, this function takes a `key` argument. `key` was more meaningful for `is_diatonic`. However, providing a key signature here is helpful for the purpose of enforcing the correct representation of accidentals intended by the user, which `tabr` cannot know until informed.

Be aware that the default for functions that take a `key` argument is `c`, but `c` and `am` have no accidentals in their key signatures, so `note_set_key()` will have no effect if you pass these values to `key`. It is also important to recognize that it does not matter for this function what key you choose specifically; it only matters that you choose a key that has the type of accidentals in its signature that you wish to force your noteworthy string to use. If you want flats, it makes no difference if you set `key = "f"` or `key = "b_"`. For this function, you can also literally enter `key = "flat"` or `key = "sharp"`, options that stress the extent to which `key` actually matters to `note_set_key()`.

```{r notes5}
note_set_key(x, "c") # no change possible
note_set_key(x, "f") # key of F has a flat
note_set_key(x, "g") # key of G has a sharp
```

The intent is not to force notes which may not be diatonic to the key signature to fit that signature. All pitches remain exactly what they are. It does not matter if they are not in the key. But they are forced to conform to a key's representation of accidentals.

For other functions in `tabr`, `key` arguments utilize the specific key signature in a more complete manner, and the options `flat` and `sharp` are not relevant or allowed.

### Octave numbering

Octave numbering can be ambiguous, including both tick and integer numbering format. You can coerce a noteworthy string strictly to one of the other:

```{r notes5b}
x <- "c, c c' c2 c c4"
as_integer_octaves(x)
as_tick_octaves(x)
```

In general, functions that operate on and return noteworthy strings will perform coercion to an internally consistent format. If formatting is ambiguous, the default is tick octave numbering and flats for accidentals.

### Timestep format

Similarly, you can coerce the time format of a noteworthy string between space-delimited time and vectorized time:

```{r notes5c}
(x <- as_space_time(c("c", "e", "g", "ceg")))
(y <- as_vector_time("c e g ceg"))

as.character(x)
as.character(y)
```

## Comparative equivalence

The `note_is_*` functions mentioned earlier are vectorized, but the operations they perform are self checks. Other functions are available for comparative checks of identity or equivalence between two notes. These functions are also vectorized. Each note input can be an entire noteworthy string. 

There are different dimensions along which the strictness of equality varies and are worth taking a moment to break these and other properties down clearly:

* These functions come in `*_is_equal` and `*is_identical` pairs. Equality is more relaxed than identity.
* The `note_is_*` pairs below also offer the argument `ignore_octave`. This further weakens the requirements for passing both equality and identity comparisons of two notes.
* These functions perform a noteworthy check, but do not require anything stricter. This means these comparisons work on all notes, even those belonging to chords.
* The general distinction between notes being equal and notes being identical is sound vs. transcription/written notation. If two notes sound the same, e.g. `e_` and `d#`, they are equal, but not identical.
* There are additional nuances with octave comparisons using the `octave_is_*` pairs.

First look at note and pitch comparisons. The main difference is that pitch is more complete than note in that the former implicitly carries the octave position. Setting `ignore_octave = FALSE` for note comparisons makes them equivalent to their pitch comparison counterparts.

```{r notes6}
x <- "b_2 ce_g"
y <- "b_ cd#g"
note_is_equal(x, y)
note_is_identical(x, y)

pitch_is_equal(x, y)
pitch_is_identical(x, y)
```

There are minimal requirements for equivalence that precede the forms and degrees of equivalence described and shown above. At a bare minimum, two noteworthy strings must have the same number of time steps available for pairwise comparison. Otherwise a simple `NA` is returned. In the following example, the strings `x` and `y` have the same number of notes, in the same order, but the first has three times steps and the second has two.

```{r notes7}
x <- "b_2 ce_g b_"
y <- "b_2 ce_gb_"
note_is_equal(x, y)
```

In the next example, `x` and `y` have the same number of of the same notes, again in the same order, and even have an equal number of timesteps. Having the same number of timesteps makes pairwise comparisons possible.
They return `FALSE` where unequal.

```{r notes8}
x <- "b_2 ce_g b_"
y <- "b_2 ce_ gb_"
note_is_equal(x, y)
```

Finally, there are octave comparisons, which must be defined and behave somewhat differently. `octave_is_equal()` and `octave_is_identical()` allow much weaker forms of equivalence in that they ignore notes completely. These functions are only concerned with comparing the octave numbers spanned by any pitches present at each timestep.

When checking for equality, `octave_is_equal()` only looks at the octave number associated with the first note at each step, e.g., only the root note of a chord.
`octave_is_identical()` compares all octaves spanned at a given timestep by considering all notes when a chord is present.

This still leaves open the definitions of equivalence. To clarify:

* It does not matter when comparing two chords that they may be comprised of a different numbers of notes.
* If the set of unique octaves spanned by one chord is identical to the set spanned by the other, they are considered to have identical octave coverage.

Consider an example: `a1b2c3` is identical to `d1e1f2g3`. The notes are irrelevant. The number of notes is irrelevant. The fact that octave number one occurs a different number of times in each chord is irrelevant. What matters is that they both have the same set of unique octave positions `{1, 2, 3}`. To be equal, even less is required. In this case it only matters that the two chords begin with `x1`, where `x` is any note.

One alternative, for `octave_is_identical()` only, is to set `single_octave = TRUE`. This increases the requirement for identity to require that all notes from both chords being compared at a given timestep share a single octave.

```{r notes9}
x <- "a1 b_2 a1b2c3 a1b4 g1a1b1"
y <- "a_2 g#2 d1e1f2g3 a1b2b4 d1e1"
octave_is_equal(x, y)
octave_is_identical(x, y)
octave_is_identical(x, y, single_octave = TRUE)

x <- "a,, b_, a,,b,c a,,b' g,,a,,b,,"
y <- "a_, g#, d,,e,,f,g a,,b,b' d,,e,,"
octave_is_equal(x, y)
octave_is_identical(x, y)
octave_is_identical(x, y, single_octave = TRUE)
```

## Slice, sort, rotate, shift, arpeggiate

A noteworthy string can be subset by index. This can with specific integers or with a logical vector with the same length as the number of time steps.

```{r notes10}
x <- "a b ceg"
note_slice(x, 2:3)
note_slice(x, c(FALSE, TRUE, TRUE))
```

Vectorized time is more trivial but is of course handled the same way and still applies the noteworthiness check and class assignment.

```{r notes11}
x <- c("a", "b", "ceg")
note_slice(x, 2:3)
note_slice(x, c(FALSE, TRUE, TRUE))
```

Sorting by pitch works with chords by sorting successively across notes in a chord. For example, `a,` is sorted lower than `a,ce`, which in turn is lower than `a,e`. Below is an example where notes and chords are not sorted by pitch. The final chord in the sequence also spans three octaves. There is also a `ba`, which is itself not ordered, but this is accounted for when sorting by successive pitches in chords.

```{r notes12}
x <- "bd'f#' a c'e'g' b ba c'g' gd'g'd''"
note_sort(x)
note_sort(x, decreasing = TRUE)
```

Rotating or cycling a sequence of notes and chords in a noteworthy string is done with `note_rotate()`. This is a simple function. It only rotates the sequence left or right. It does not do any transposition. It does not break chords, but rather rotates them intact.

```{r notes13}
note_rotate(x, 1)
note_rotate(x, -1)
```

`note_shift()` also rotates notes, but does so up or down in pitch like a moving window. It requires breaking any chords into separate notes, ordering all notes by pitch, and then shifting the sorted notes `n` times, negative or positive indicating the direction.

```{r notes14}
note_shift("c e g", 1)
note_shift("c e g", -4)
```

`note_arpeggiate()` is like `note_shift()` but it repeats the entire sequence rather than shifting it a note at a time and maintaining its fixed size. `n` refers to the number of repeats and must be positive. `steps` refers to the semitone offset.

```{r notes15}
note_arpeggiate("c e_ g_ a", 3)
note_arpeggiate("c e_ g_ a", 3, -3)
```

## Transpose

An important function in `tabr` for manipulating music notation is the `transpose()` function, which also has the alias `tp()`.

```{r tp1}
notes1 <- "c b, c d e e d c b, c c c'"
notes2 <- "c' b c' d' e' e' d' c' b c' c' c''"
transpose(notes1, 12, octaves = "integer") == as_noteworthy(notes2)
```

Transposing down is done with negative integers. 

```{r tp2}
transpose("a_ b_' c'", 0)
tp("a_ b_' c'", -1)
tp("a_ b_' c'", 1)
tp("a# b' c#'", 11)
tp("a# b' c#'", -12)
tp("a# b' c#'", 13)
```

`transpose` also offers the arguments found in `as_noteworthy()` for direct control over the format of the transposed output. You can specify the key signature with `key` as an optional override to `accidentals`. It does not do anything more than enforce the desired format for accidentals.

```{r tp3}
tp("a3 b4 c5", 2, key = "f")
tp("a3 b4 c5", 2, octaves = "tick", key = "g")
tp("a b' c''", 2, accidentals = "flat")
tp("a, b c'e'g'", 2, octaves = "integer", accidentals = "sharp")
```

`transpose()` also works when chords are present. The next section on music programming covers various functions related to chords.
