knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

Setup

By using install_miditapyr(), this should also install mido which is a dependency of miditapyr:

pyramidi::install_miditapyr(envname = "r-reticulate")

Now we'll load some R and the python mido & miditapyr libraries with the reticulate::import() function. The loading of import_builtins() into pb will allow to work with python objects from R:

library(reticulate)
library(pyramidi)
library(tidyr)
library(purrr)
library(details)
mido <- import("mido")
mt <- import("miditapyr")
pb <- import_builtins()

Load file

Here we'll load the midi file included in the package into a mido.MidiFile object:

midi_file_string <- system.file("extdata", "test_midi_file.mid", package = "pyramidi")
midi_file <- mido$MidiFile(midi_file_string)

``{details, details.summary = "Click here to show the printed midoMidiFile()` object"} midi_file

This object is a list object, containing besides some meta information
multiple `MidiTrack()`s which are themselves also lists containing the midi event
messages.

## Transform to unnested dataframe 

We can transform the midi data to a data.frame similar to the one returned by
[`unnest_midi()`](https://miditapyr.readthedocs.io/en/latest/miditapyr.html#miditapyr.mido_io.unnest_midi)
from the miditapyr package. We'll only use the data of the first track of the midi file:


```r
# access first track:
track1 <- midi_file$tracks[[1]]
# transform MidiTrack() object to an R list of mido Message()s and MetaMessage()s:
track1list <- pb$list(track1)

```{details, details.summary = "Show details of list in R"} track1list

The list contains mido `Message()` & `MetaMessage()` objects (`Message()`s seem to have a special print method).

With the function `pb$vars()` we can extract all variables for every 
event into a list of named R lists:

```r
track1Rlist <- track1list %>% 
  map(pb$vars)

```{details, details.summary = "Show details of first 10 elements of track events list in R"} track1Rlist[1:10]

We can put this list of message lists in a dataframe and write the values of 
each key in their own column:


```r
track1Rlist %>% 
  tibble(temp = .) %>% 
  unnest_wider(temp)

Compare with pyramidi

For comparison, we plot the results of unnest_midi()

mfr <- MidiFramer$new(midi_file_string)
mt$unnest_midi(dfc = mfr$mf$midi_frame_raw) %>% 
  as_tibble()

There are some differences in the types and track1Rlist only contains the data of track 1, but you can see that apart from that, the output is the same.



urswilke/pyramidi documentation built on March 7, 2024, 3:48 p.m.